多页面打包配置

webpack4.0(七):多页面打包配置

webpack.config.js

const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');


/**
 * @param { Object } 
 * @return { Object }
 */
const makeHtml = (configs) => {
    let pluginsDll = [
        new CleanWebpackPlugin(),
    ];
    Object.keys(configs.entry).forEach(key => {
        console.log(key)
        pluginsDll.push(
            new HtmlWebpackPlugin({
                filename:`${key}.html`,
                template:'./src/index.html',
                chunks:['lodash','react',key]
            })
        )
    })
    const files = fs.readdirSync(path.resolve(__dirname,'../dll'));
    files.forEach(file => {
        if(/.*\.dll.js$/.test(file)){
            pluginsDll.push(
                new AddAssetHtmlWebpackPlugin({
                    filepath:path.resolve(__dirname,'../dll',file)
                })
            )
        }
        if(/.*\.manifest.json$/.test(file)){
            new webpack.DllReferencePlugin({
                manifest: require(path.resolve(__dirname,'../dll',file)),
            })
        }
    });
    return pluginsDll;
}



const config = {
    entry:{
        index:'./src/index.js',
        list:'./src/list.js'
    },
    output:{
        path:path.resolve(__dirname,'../dist')
    },
    module:{
        rules:[
            {
                test:/\.jsx?$/,
                loader:'babel-loader'
            }
        ]
    }
};

config.plugins = makeHtml(config);

module.exports = config;

webpack.dll.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
    mode:"production",
    entry:{
        react:['react','react-dom','react-router-dom'],
        lodash:['lodash-es']
    },
    output:{
        filename:'[name].dll.js',
        path : path.resolve(__dirname,'../dll'),
        library:'_dll_[name]'
    },
    plugins:[
        new webpack.DllPlugin({
            name: "_dll_[name]",
            path: path.join(__dirname, "../dll/[name].manifest.json"),
        })
    ]
}
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!