其实还是非常简单的,原理上来说就是配置多个入口文件,使webpack生成多个依赖关系,从而构建出多个bundlejs。这样我们在不同的html文件引入对应的bundle就行了。但是有一个问题,这样的配置我们每增加一个子页面都需要去写一个entry的键值对,非常的麻烦。那有没有什么办法可以一次性获取到这些子页面然后自动生成entry呢?
npm i glob -D const setMPA = ()=>{ const entry = {} const htmlWebpackPlugin = [] const entryFile = glob.sync('./pages/*/main.js') entryFile.forEach((filePath,index)=>{ //根据获取到的路劲生成多入口entry对象 const entryName = filePath.split('/pages/')[1].split('/main.js')[0] entry[entryName] = filePath //接着生成每个入口的html模板 htmlWebpackPlugin.push( new HtmlWebpackPlugin({ filename: `${entryName}.html`, template: path.resolve(__dirname,`./pages/${entryName}/public/index.html`), chunks: [entryName], //只打入指定的chunks,不然的话webpack会将所有bundle都引入 inject: true,//配置所有js资源放置在html得哪个位置 minify:{ //压缩配置 collapseWhitespace: true, preserveLineBreaks:false, html5:true, minifyCSS:true, minifyJS:true, removeComments: true, } }) ) }) return{ entry, htmlWebpackPlugin } }有了这个函数,就能拿到最新的entry以及最新的htmlWebpackPlugin配置。