The problem is that when I use HtmlWebpackPlugin and splitChunks, chunks can not be injected into the generated html. My configure of Webpack 4 is
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,
},
},
},
},
};
The template index.ejs is
<!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>
When I run yarn build, it will generate main.[hash].js, 1.[hash].js and index.html.But the 1.[hash].js isn't injected into the html.The HtmlWebpackPlugin's version is 3.2.0.How can I solve this problem?Thanks!
Finally I fixed it by upgrade the html-webpack-plugin to 4.0.0-alpha and add chunks: 'all' to the plugin configurations:
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"
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With