Javascript 使用webpack或自定义扩展注入一些预先格式化的html
有没有一种方法可以只使用Javascript 使用webpack或自定义扩展注入一些预先格式化的html,javascript,webpack,html-webpack-plugin,Javascript,Webpack,Html Webpack Plugin,有没有一种方法可以只使用webpack插入下面的代码块(即注释和字符串格式,而不将其折叠成一行)。最好是在构建阶段,以这种方式将生成的文件注入 <!-- Comment --> <script>/* script goes here */</script> <!-- End Commnet --> /*脚本在这里*/ 我不确定作为一个网页从哪一方面入手对我来说是新的,除了他们文档中的一些逐步配置之外 我一直在研究webpackhtml插件,但
webpack
插入下面的代码块(即注释和字符串格式,而不将其折叠成一行)。最好是在构建阶段,以这种方式将生成的文件注入
<!-- Comment -->
<script>/* script goes here */</script>
<!-- End Commnet -->
/*脚本在这里*/
我不确定作为一个网页从哪一方面入手对我来说是新的,除了他们文档中的一些逐步配置之外
我一直在研究webpackhtml插件
,但没有找到将块指定为字符串的方法,因为只允许使用文件
我已经找到了一种使用
insertAdjacentHTML
将其作为字符串注入的方法(但仅当react应用程序已经运行时),但这不是我想要的。我希望能够使用其配置文件将参数传递给webpack
,但某些参数会因环境而异。您可以使用html webpack plugin
您可以在webpack.config.js
中定义任何变量,包括html:
new HtmlWebpackPlugin({
template: './src/index.html',
header: '<h1>A title</h1>',
anyElement: '<b>I am an html element</b>'
})
如果您有要使用的外部html文件,可以使用名为fs
的node js集成模块读取文件,然后将文件传递到变量中。无需安装nodejs附带的fs
let fs = require('fs');
const myFile = fs.readFileSync(__dirname + '/myfile.html');
const thatFile = fs.readFileSync(__dirname + '/thatfile.html');
module.exports = {
// your config
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
myFile: myFile,
thatFile: thatFile,
})
]
});
现在,当您运行Webpack时,您的HTML文件将被注入您指定的位置
<html>
<head></head>
<body>
<%= htmlWebpackPlugin.options.myFile %>
<h1>Some other html content</h1>
<%= htmlWebpackPlugin.options.yourFile %>
</body>
</html>
其他一些html内容
嘿,凯瑟琳,如果答案对你有帮助,你能选择作为你问题的答案吗?谢谢!:)
<html>
<head></head>
<body>
<%= htmlWebpackPlugin.options.myFile %>
<h1>Some other html content</h1>
<%= htmlWebpackPlugin.options.yourFile %>
</body>
</html>