如何使用HtmlWebpackPlugin将代码块注入到HTML中

8
问题在于当我使用HtmlWebpackPlugin和splitChunks时,chunk不能注入到生成的html中。 我的Webpack 4配置如下:
var loading = {
  ejs: fs.readFileSync(path.resolve(__dirname, 'template/loading.ejs')),
  css: fs.readFileSync(path.resolve(__dirname, 'template/loading.css')),
};

module.exports = {
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.[hash].js',
    chunkFilename: '[name].[chunkhash].js',
  },
  mode: 'production',
  // ...
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        include: path.resolve(__dirname, 'src'),
        exclude: path.resolve(__dirname, 'node_modules'),
        use: 'happypack/loader?id=babel',
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(['dist']),
    new HappyPack({
      id: 'babel',
      loaders: ['babel-loader?cacheDirectory'],
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'template/index.ejs'),
      loading: loading,
    }),
    new ScriptExtHtmlWebpackPlugin({
      defaultAttribute: 'defer',
    }),
  ],
  optimization: {
    splitChunks: {
      chunks: 'all',
      name: true,
      automaticNameDelimiter: '-',
      cacheGroups: {
        vendors: {
          test: /[\\/]node_modules[\\/]/,
          priority: -10,
        },
        default: {
          minChunks: 2,
          priority: -20,
          reuseExistingChunk: true,
        },
      },
    },
  },
};

模板文件index.ejs是...
<!DOCTYPE html>
<html lang="en">

<head>
    // ...
    <title>React</title>
    <style>
        <%=htmlWebpackPlugin.options.loading.css %>
    </style>
</head>

<body>
    <div id="root">
        <%= htmlWebpackPlugin.options.loading.ejs %>
    </div>
    <script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js" defer></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js" defer></script>
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js" defer></script>

</body>

</html>

当我运行yarn build时,它会生成main.[hash].js1.[hash].jsindex.html。但是1.[hash].js没有被注入到html中。HtmlWebpackPlugin的版本是3.2.0。如何解决这个问题?谢谢!
2个回答

0
因为我使用了react-loadable,所以代码块不会被注入到生成的HTML中。所以这不是一个问题。

0

最终我通过将html-webpack-plugin升级到4.0.0-alpha版本并在插件配置中添加chunks: 'all'来解决了这个问题:

      new HtmlWebpackPlugin({
        filename: `${f}.html`,
        template: paths.appHtml,
        inject: true,
        minify: {
          removeComments: true,
          collapseWhitespace: true,
          removeRedundantAttributes: true,
          useShortDoctype: true,
          removeEmptyAttributes: true,
          removeStyleLinkTypeAttributes: true,
          keepClosingSlash: true,
          minifyJS: true,
          minifyCSS: true,
          minifyURLs: true
        },
        chunks: "all"
      })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接