javascript - 使用 webpack 或自定义扩展注入一些预格式化的 html
问题描述
有没有办法只使用webpack
. 优选地,在构建阶段,以这种方式生成的文件将其注入。
<!-- Comment -->
<script>/* script goes here */</script>
<!-- End Commnet -->
我不确定从哪方面接近 webpack 对我来说是一种新事物,除了可能从他们的文档中逐步配置。
我一直在研究webpack-html-plugin
,但没有找到将块指定为字符串的方法,因为只允许文件。
我已经找到了一种使用 将其作为字符串注入的方法(但仅在 react 应用程序已经运行时)insertAdjacentHTML
,但这不是我想要的。我希望能够将参数传递给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>'
})
然后你可以像这样将它们插入你的index.html
:
<html>
<head></head>
<body>
<%= htmlWebpackPlugin.options.header %>
<h1>Some Other Html Content</h1>
<%= htmlWebpackPlugin.options.footer %>
</body>
</html>
如果您有想要使用的外部 html 文件,您可以使用调用的节点 js 集成模块fs
来读取文件,然后将其传递到您的变量中。你不需要安装fs
nodejs 自带的
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>
推荐阅读
- r - R中使用dplyr的日期数据
- ffmpeg - 使用 FFMPEG 将 -movflags +faststart 添加到 MP4 的最快方法,其他所有内容保持原样
- bash - 如何保存 GhostScript 输出
- android - 填充画布上 2 条路径之间的间隙
- java - 使用 Java 从网页中抓取信息?
- database - DynamoDB 是否支持 Tombstone 记录处理?
- javascript - 如何配置 package.json 在 js 和 jsx 文件上运行 eslint
- reactjs - 如何使用 redux-thunk 调度操作让 connected-react-router 重定向?
- r - 在 R 中创建具有类似观察结果的数据框
- javascript - 如何使用其中包含 HTML 标记的文本创建 DOM 节点