12、区分开发环境和生产环境

开发环境和生产环境的构建目标差异很大。在开发环境中,我们需要强大的、具有实时重新加载或热模块替换能力和本地服务器。而在生产环境中,我们目标则转向于关注更小的包,以及资源的优化,以改善加载时间。所以我们通常建议每个环境编写独立的webpack配置。

现在我们把下面的webpack配置分别写在3个文件上

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry : './js/index.js', 
    output : { 
        path : path.resolve(__dirname, 'dist'), 
        filename : 'js/index.js' 
    },
    devtool : 'source-map',
    devServer : {
        contentBase : './dist',
        host : 'localhost',
        port : 8080,
        open : true,
    },
    module:{
        rules : [{
            test : /\.css$/,
            use : ['style-loader',
            {
                loader:MiniCssExtractPlugin.loader,
                options:{
                    publicPath: '../'
                }
            },
            {
                loader : 'css-loader',
                options : {
                    sourceMap : true
                }
            },{
                loader : 'postcss-loader',
                options : {
                    plugins : [
                        require('autoprefixer')({
                            browsers : [
                                'ie >=8',
                                'Firefox >=20',
                                'Safari >=5',
                                'Android >=4',
                                'Ios >=6',
                                'last 4 version'
                            ]
                        })
                    ]
                }
            }]
        },{
            test : /\.(png|jpg|gif|jpeg)$/,
            use : [{
                loader : 'file-loader',
                options : {
                    esModule: false,
                    outputPath : './images'
                } 
            },
            {
                loader: 'image-webpack-loader',
                options: {
                    mozjpeg: {
                        progressive: true,
                        quality: 65
                    },
                    quality: [0.65, 0.90],
                    speed: 4
                }
            }]
        },{
            test: /\.(htm|html)$/i,
            use:['html-withimg-loader'] 
        }]
    },
    resolve : {
        alias : {
            jQuery : path.resolve(__dirname, './js/jquery-3.1.1.min.js')
        }
    },
    plugins:[
        new CleanWebpackPlugin(),
        new webpack.ProvidePlugin({
            $ : "jQuery"
        }),
        new HtmlWebpackPlugin({
            template : './index.html', 
            filename : 'index.html', 
            minify : {
                minimize : true, 
                removeAttributeQuotes : true, 
                removeComments : true, 
                collapseWhitespace : true,
                minifyCSS : true, 
                minifyJS : true, 
                removeEmptyElements : false, 
            },
            hash : true 
        }),
        new MiniCssExtractPlugin({ 
            filename : './css/index.css'
        }),
        new OptimizeCssAssetsWebpackPlugin({
            assetNameRegExp : /\.css$/g, 
            cssProcessor : require('cssnano'), 
            cssProcessorPluginOptions : {
                preset : ['default', {
                    discardComments : { 
                        removeAll: true
                    }
                }]
            },
            canPrint :true
        })
    ]
}

步骤

1、安装webpack-merge

cnpm i webpack-merge -S

2、新建一个config文件夹,在这个文件夹上个写3个webpack配置的文件,分别是 :

webpack.common.conf.js  //共用的

webpack.dev.conf.js //开发环境使用的

webpack.prod.conf.js //生产环境使用的

3、提取公共的配置到webpack.common.conf.js , 如下 :

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry : './js/index.js', 
    output : { 
        path : path.resolve(__dirname, '../dist'), 
        filename : 'js/index.js' 
    },
    module:{
        rules : [{
            test : /\.css$/,
            use : ['style-loader',
            {
                loader:MiniCssExtractPlugin.loader,
                options:{
                    publicPath: '../'
                }
            },
            'css-loader',
            {
                loader : 'postcss-loader',
                options : {
                    plugins : [
                        require('autoprefixer')({
                            browsers : [
                                'ie >=8',
                                'Firefox >=20',
                                'Safari >=5',
                                'Android >=4',
                                'Ios >=6',
                                'last 4 version'
                            ]
                        })
                    ]
                }
            }]
        },{
            test : /\.(png|jpg|gif|jpeg)$/,
            use : [{
                loader : 'file-loader',
                options : {
                    esModule: false,
                    outputPath : './images'
                } 
            },
            {
                loader: 'image-webpack-loader',
                options: {
                    mozjpeg: {
                        progressive: true,
                        quality: 65
                    },
                    quality: [0.65, 0.90],
                    speed: 4
                }
            }]
        },{
            test: /\.(htm|html)$/i,
            use:['html-withimg-loader'] 
        }]
    },
    resolve : {
        alias : {
            jQuery : path.resolve(__dirname, '../js/jquery-3.1.1.min.js')
        }
    },
    plugins:[
        new CleanWebpackPlugin(),
        new webpack.ProvidePlugin({
            $ : "jQuery"
        }),
        new HtmlWebpackPlugin({
            template : './index.html', 
            filename : 'index.html', 
            minify : {
                minimize : true, 
                removeAttributeQuotes : true, 
                removeComments : true, 
                collapseWhitespace : true,
                minifyCSS : true, 
                minifyJS : true, 
                removeEmptyElements : false, 
            },
            hash : true 
        }),
        new MiniCssExtractPlugin({ 
            filename : './css/index.css'
        })
    ]
}

4、提取开发环境配置到webpack.dev.conf.js,如下 :

const merge = require('webpack-merge');
const common = require('./webpack.common.conf.js')

module.exports = merge(common, {
    devtool : 'cheap-module-eval-source-map',
    devServer : {
        contentBase : './dist',
        host : 'localhost',
        port : 8080,
        open : true,
    }
}); 

5、提取生产环境配置到webpack.prod.conf.js,如下 :

const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const merge = require('webpack-merge');
const common = require('./webpack.common.conf.js')

module.exports = merge(common, {
    devtool : 'source-map',
    plugins:[
        new OptimizeCssAssetsWebpackPlugin({
            assetNameRegExp : /\.css$/g, 
            cssProcessor : require('cssnano'), 
            cssProcessorPluginOptions : {
                preset : ['default', {
                    discardComments : { 
                        removeAll: true
                    }
                }]
            },
            canPrint :true
        })
    ]
});

ps :上面的merge是一个函数,第一个参数是公共配置的webpack配置,第二个是json对象。需要注意的是,我们把webpack的配置放在了config文件夹,则里面的一些文件路径需要做出改变,比如上面的

output : { 
    path : path.resolve(__dirname, '../dist'), 
    filename : 'js/index.js' 
}

现在变成 ../dist

6、在package.json新建打包命令,如下 : 

"scripts": {
    "build:dev": "webpack --mode development --config ./config/webpack.dev.conf.js",
    "build:prod": "webpack --mode development --config ./config/webpack.prod.conf.js",
    "start": "webpack-dev-server --mode development --config ./config/webpack.dev.conf.js"
  }

build:dev 是开发环境的webpack配置,执行这个命令打包的时候,webpack则会以webpack.dev.conf.js这个文件的配置来打包

build:prod 是生产环境的webpack配置,执行这个命令打包的时候,webpack则会以webpack.prod.conf.js这个文件的配置来打包

 

例子下载

案例

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值