我有3页。
Page1&page2依赖于vue,page2&page3依赖于jquery。因此,我使用SplitChunksPlugin
从页面包中分离出块。
但是问题出在使用html-webpack-plugin
上。每个页面html必须包含同时需要main.bundle.js和通用块js(例如page1〜page2.js)的js,因此我必须获取commonChunk名称进行过滤我只能从名称函数中获取该信息,但它是异步的。因此,在名称回调结束后,如何生成HtmlWebpackPlugin obj ...
这是我的webpack配置。
const pageDir = './page';
const indexPage = 'page1';
const pages = fs.readdirSync(pageDir);
console.log('__dirname', __dirname);
let splitChunksName = [];
const getPagesHtmlWebpackPluginList = () => {
console.log('splitChunksName',splitChunksName); // log [], expect after get splitChunksName to call
return pages.map( page => {
let regex = new RegExp(page);
let commonChunks = splitChunksName.filter(name => regex.test(name));
return new HtmlWebpackPlugin({
filename: `${page}/index.html`,
chunks: [`${page}/main`, ...commonChunks],
});
});
};
const getEntryObj = () => {
let entry = {};
pages.forEach(page => {
Object.assign(entry, {
[`${page}/main`]: [path.resolve(process.cwd(), pageDir, `./${page}/main.js`)]
})
});
return entry;
};
module.exports = {
mode: 'none',
entry: getEntryObj(),
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].bundle.js'
},
optimization: {
splitChunks: {
chunks: 'all',
name: module => {
// set 'name:true' the output dir becomes ugly, if chunk1 names 'a/b', chunk2 names 'c/d',
//then the common chunk12 will be 'venders~a/b~c/d.bundle.js', two ugly folders(venders~a , b~c)generated.
//So I write my own name function.
let arr = [];
module._chunks.forEach(chunk => {
arr.push(chunk.name.replace('/main',''));
});
let splitChunkName = 'vender/' + arr.join('~');
splitChunksName.push(splitChunkName);
//splitChunksName is needed,I need common chunk info to use with html-webpack-plugin
return splitChunkName;
}
}
},
plugins: [
...getPagesHtmlWebpackPluginList()
]
};
答案 0 :(得分:0)
从 html-webpack-plugin 版本4开始,该功能现已受本机支持。
How to use Webpack 4 SplitChunksPlugin with HtmlWebpackPlugin for Multiple Page Application?