Webpack HTML 为每个入口点生成一个 javascript

Webpack HTML generate one javascript for each entry point

我正在为项目设置 Webpack,并使用 HTML webpack 插件生成 HTML 文件。

我的问题是正在生成的 HTML 包含所有包而不是特定 HTML 文件的特定入口点。这是我的代码 ATM

    const path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: {
    one: './js/one.js',
    two: './js/two.js',
    three: './js/three.js',
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: './js/[name].js',
  },
  module: {
        loaders: [],
        rules:[
          {
            test: /\.css$/,
            use: [ 'style-loader', 'css-loader' ]
          },
          {
            test: /\.(png|jpg|woff|woff2|eot|ttf|svg)$/,
            use: ['url-loader?limit=100000&name=./img/[hash].[ext]'],
          }

        ]
  },
  plugins: [
  new HtmlWebpackPlugin({
    title: 'One',
    template: 'one.ejs', // Load a custom template (ejs by default see the FAQ for details)
    filename: 'one.htm'
  }),
  new HtmlWebpackPlugin({
    title: 'Two',
    template: 'two.ejs', // Load a custom template (ejs by default see the FAQ for details)
    filename: 'two.htm'
  }),
  new HtmlWebpackPlugin({
    title: 'Three',
    template: 'three.ejs', // Load a custom template (ejs by default see the FAQ for details)
    filename: 'three.htm'
  })
  ]

};

根据文档:

https://webpack.js.org/plugins/html-webpack-plugin/

If you have multiple webpack entry points, they will all be included with script tags in the generated HTML.

有没有办法将 one.js 附加到 one.htm?还有两个 two.htm?

HtmlWebpackPlugin options 中将 inject 选项设置为 false,然后在您的 EJS 模板中过滤出您想要的条目。

new HtmlWebpackPlugin({
  inject: false,
  title: 'One',
  template: 'one.ejs',
  filename: 'one.htm'
})

然后您可以使用这些条目为您想要包含的标签创建 <script> 标签模板。

像这样的模板应该可以解决问题,它会根据条目检查所需输出文件的基本名称,如果它们与它匹配,则会模板化 <script> 标记。按照此 EJS 模板的编写方式,您应该能够将其用作所有 HtmlWebpackPlugin 选项的模板文件。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <%
    for (let chunk in htmlWebpackPlugin.files.chunks) {
      if (chunk === htmlWebpackPlugin.options.filename.split('.')[0]) {
  %><script type="text/javascript" src="<%= htmlWebpackPlugin.files.chunks[chunk].entry %>"></script><%
      }
    }
    %>
  </body>
</html>

这会产生以下输出文件。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>One</title>
  </head>
  <body>
    <script type="text/javascript" src="./dist/one.js"></script>
  </body>
</html>
new HtmlWebpackPlugin({
    title: 'One',
    chunks: ['one'],
    template: 'ejs-render-loader!./one', 
    filename: 'one'
}),

对于谷歌搜索的任何人,我也刚刚发现您可以使用块来做同样的事情。