阅读 211

webpack 多页面打包

  1. 引入glob

npm install glob -D

  1. 改造entry和htmlwebpackplugin
const setMPA = ()=> {
    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.match(/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`,
                    chunks:[pageName],
                    inject:true,
                    minify:{
                        html5:true,
                        collapseWhitespace:true,
                        preserveLineBreaks:false,
                        minifyCSS:true,
                        removeComments:false
                    } 
                })
            )
        })
    return {
        entry,
        htmlWebpackPlugins
    }
}

const { entry,htmlWebpackPlugins} =  setMPA();
复制代码

3.修改webpack配置

 entry:entry,
 output:{
    path:path.resolve(__dirname,'dist'),
    filename:'[name].js'
 },
 plugins:[
    ...
 ].concat(htmlWebpackPlugins)
复制代码
文章分类
前端
文章标签