生产环境 webpack 配置

const {resolve} = require(‘path‘)
const MiniCssExtractPlugin = require(‘mini-css-extract-plugin‘)
const OptimizeCssAssetsWebpackPlugin = require(‘optimize-css-assets-webpack-plugin‘)
const HtmlWebpackPlugin = require(‘html-webpack-plugin‘)

process.env.NODE_ENV = ‘production‘

//复用loader
const commonCssLoader = [
    MiniCssExtractPlugin.loader,
    ‘css-loader‘,
    {
        loader:‘postcss-loader‘,
        options:{
            ident:‘postcss‘,
            plugins:()=>[require(‘postcss-preset-env‘)()]
        }
    }
]

module.exports={
    entry:‘./src/index.js‘,
    output:{
        filename:‘bundle.js‘,
        path:resolve(__dirname,‘build‘)
    },
    module:{
        rules:[
            {
                test:/\.css$/,
                use:[...commonCssLoader]
            },
            {
                test:/\.less$/,
                use:[...commonCssLoader]
            },
            {
                test:/\.js$/,
                exclude:/node_modules/,
                enforce:‘pre‘, //优先执行,正常的,一个文件只能被一个loader处理,当一个文件要被多个loader处理,一定要指定loader执行的先后顺序,先执行eslint再执行babel
                loader:‘eslint-loader‘,
                options:{
                    fix:true
                }
            },
            {
                test:/\.js$/,
                exclude:/node_modules/,
                loader:‘babel-loader‘,
                options:{
                    presets:[
                        [‘@babel/preset-env‘,{
                            useBuiltIns:‘usage‘,
                            corejs:{version:3},
                            targets:{
                                chrome:‘60‘,
                                firefox:‘50‘
                            }
                        }]
                    ]
                }
            },
            {
                test:/\.(jpg|png|gif)$/,
                loader:‘url-loader‘,
                options:{
                    limit:8*1024,
                    name:‘[hash:10].[ext]‘,
                    outputPath:‘imgs‘,
                    esModule:false
                }
            },
            {
                test:/\.html$/,
                loader:‘html-loader‘
            },
            {
                exclude:/\.(js|css|less|html|jpg|png|gif)$/,
                loader:‘file-loader‘,
                options:{
                    outputPath:‘media‘
                }
            }
        ]
    },
    plugins:[
        new MiniCssExtractPlugin({
            filename:‘bundle.css‘
        }),
        new OptimizeCssAssetsWebpackPlugin(),
        new HtmlWebpackPlugin({
            template:‘./src/index.html‘,
            minify:{
                collapseWhitespace:true,
                removeComments:true
            }
        })
    ],
    mode:‘production‘
}

相关推荐