webpck之多頁面應用打包通用方案

webpck之多頁面應用打包通用方案

  1. 利用glob插件
    glob.sync
    entry:glob.sync(path.join(_dirname,’./src/*/index.js’)),

  2. 在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();
    
  3. 更改plugins配置

     plugins: [
            new MiniCssExtractPlugin({
                filename: `[name][contenthash:8].css`
            }),
            new OptimizeCSSAssetsPlugin({
                assetNameRegExp: /\.css$/g,
                cssProcessor: require('cssnano')
            }),
    
            new CleanWebpackPlugin()
        ].concat(htmlWebpackPlugins),
    
  4. 重新運行打包

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章