webpack配置多页应用

259 阅读1分钟

网上有很多相关教程了。这里我就不做复述了。我这里仅仅写一个最小的demo,总结下多页配置的使用。

主要修改3个地方:

  1. entry
  2. output
  3. css(mini-css-extract-plugin)
  4. html-webpack-plugin

entry

    entry: {
        index: './src/index.js',
        login: './src/login.js'
    },

output

    output: {
        filename: '[name].js',
        path: path.resolve(__dirname, 'dist'),
    },

css(mini-css-extract-plugin)

const HtmlWebpackPlugin = require('html-webpack-plugin');
//...其他代码

            {
                test: /index.module\.css$/,
                exclude: /node_modules/,
                use: [
                    // 'style-loader',
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 2,
                            // localsConvention: '[name]--[local]--[hash:base64:5]',
                            sourceMap: true,
                            modules: true  //重点                            
                        }
                    }
                ]

            },
            {
                test: /login.module\.css$/,
                exclude: /node_modules/,
                use: [
                    // 'style-loader',
                    MiniCssExtractPlugin.loader,
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 2,
                            // localsConvention: '[name]--[local]--[hash:base64:5]',
                            sourceMap: true,
                            modules: true  //重点                            
                        }
                    }
                ]

            }, 
            
            

分别生成loader,再用mini-css-extract-plugin处理


    plugins: [
        new HtmlWebpackPlugin({
            template: './index.html',
            filename: 'index.html',
            chunks:['index']
        }),
        new HtmlWebpackPlugin({
            template: './login.html',
            filename: 'login.html',
            chunks: ['login']
        }),        

        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css'
        }),        
    ]

html-webpack-plugin

        new HtmlWebpackPlugin({
            template: './index.html',
            filename: 'index.html',
            chunks:['index']//这个很重要,一定要对应entry的key值,否则所有js和css都加进来了!
        }),
        new HtmlWebpackPlugin({
            template: './login.html',
            filename: 'login.html',
            chunks: ['login']
        }), 

至此,最基本的多页应用配置已完毕。

参考文献

juejin.cn/post/684490…