webpck之多頁面應用打包通用方案
-
利用glob插件
glob.sync
entry:glob.sync(path.join(_dirname,’./src/*/index.js’)), -
在webpack配置文件中寫入以下代碼配置
const setMAP = () => { const entry = { }; const HtmlWebpackPlugins = []; const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js')); Object.keys(entryfiles).map((index) => { const entryFile = entryFiles[index] const match = entryFile.mach(/src\(.*)\/index\.js/) const pageName = match && match[1]; entry[pageName] = entryFile htmlWebpackPlugins.push( new HtmlWebpackPlugin({ //需要壓縮的文件模板 template: path.join(__dirname, 'src/${pageName}/index.html'), //壓縮後的文件名 filename: `${pageName}.html`, //chunk chunks: [pageName], inject: true, minify: { html5: true, collapseWhitespace: true, preserveLineBreaks: false, minifyCSS: true, minifyJS: true, removeComments: false } }), ) }) return { entry, htmlWebpackPlugins } } const { entry, htmlWebpackPlugins } = setMAP();
-
更改plugins配置
plugins: [ new MiniCssExtractPlugin({ filename: `[name][contenthash:8].css` }), new OptimizeCSSAssetsPlugin({ assetNameRegExp: /\.css$/g, cssProcessor: require('cssnano') }), new CleanWebpackPlugin() ].concat(htmlWebpackPlugins),
-
重新運行打包