问题是,当我使用HtmlWebpackPlugin和splitChunks时,无法将块注入到生成的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].js
,1.[hash].js
和index.html
。但是1.[hash].js
并没有注入html.HtmlWebpackPlugin版本是3.2.0。如何解决此问题?谢谢!
答案 0 :(得分:0)
因为我使用react-loadable
,所以这些块将不会注入生成的html中。因此,这不是问题。
答案 1 :(得分: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"
})