首页 > 解决方案 > 使用 webpack 或自定义扩展注入一些预格式化的 html

问题描述

有没有办法只使用webpack. 优选地,在构建阶段,以这种方式生成的文件将其注入。

<!-- Comment -->
<script>/* script goes here */</script>
<!-- End Commnet -->

我不确定从哪方面接近 webpack 对我来说是一种新事物,除了可能从他们的文档中逐步配置。

我一直在研究webpack-html-plugin,但没有找到将块指定为字符串的方法,因为只允许文件。

我已经找到了一种使用 将其作为字符串注入的方法(但仅在 react 应用程序已经运行时)insertAdjacentHTML,但这不是我想要的。我希望能够将参数传递给webpack使用其配置文件,但某些参数因环境而异。

标签: javascriptwebpackhtml-webpack-plugin

解决方案


您可以使用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来读取文件,然后将其传递到您的变量中。你不需要安装fsnodejs 自带的

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>

推荐阅读