生产模式中,要求css和js文件尽可能小,因此需要把css和js文件压缩;开发模式中,要便于代码的调试,不能压缩css和js文件。
使用webpack-merge
安装插件webpack-merge
npm install --save-dev webpack-merge 复制代码
按照模式创建不同的配置文件
创建文件
webpack.prod.js:用于生产环境 webpack.dev.js:用户开发环境webpack.common.js:两个环境公共配置复制代码
webpack.common.js文件内容
const path = require('path');var htmlWebpackPlugin = require('html-webpack-plugin');const extractTextPlugin = require("extract-text-webpack-plugin");const extractCSS = new extractTextPlugin("css/[name]-[hash].css");module.exports = { entry: './src/js/app.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'js/[name]-[hash].js' }, module: { rules: [ { test: /\.css$/, use: extractCSS.extract({ fallback: "style-loader", // 编译后用什么loader来提取css文件 use: [ { loader: 'css-loader' }, { //浏览器添加前缀 loader: 'postcss-loader', options: { ident: 'postcss', plugins: [ require('autoprefixer')({ broswers: ['last 5 versions'] }) ] } } ] }) }, { test: /\.less$/, use: extractCSS.extract({ fallback: "style-loader", // 编译后用什么loader来提取css文件 use: [ { loader: 'css-loader' }, { //浏览器添加前缀 loader: 'postcss-loader', options: { ident: 'postcss', plugins: [ require('autoprefixer')({ broswers: ['last 5 versions'] }) ] } }, { loader: 'less-loader' } ] }) }, { test: /\.js$/, //添加正则,处理js文件 use: [ //把ES6语法转换为ES5 { loader: 'babel-loader', options: { "presets": ["@babel/preset-env"] } } ] }, { test:/\.(png|gif|jpg)$/i, use:[ { loader:'url-loader', options:{ name:'images/[name].[ext]', limit:20000, publicPath:'../' } } ] } ] }, plugins: [ new htmlWebpackPlugin({ filename: 'index.html', template: './src/template/index.html', title: 'this is webpack title' }), extractCSS ]};复制代码
webpack.dev.js文件内容
const path = require('path')const merge = require('webpack-merge');const common = require('./webpack.common.js');module.exports = merge(common,{ mode:'development', //开发模式});复制代码
webpack.prod.js文件内容
const path = require('path')const merge = require('webpack-merge');const common = require('./webpack.common.js');module.exports = merge(common,{ mode:'production', //生产模式});复制代码
修改package.json文件
"scripts": { "dev": "webpack --config webpack.dev.js --progress --display-moudle --colors --display-reasons", "prod": "webpack --config webpack.prod.js --progress --display-moudle --colors --display-reasons" }复制代码
执行打包
生产环境 npm run prod
开发环境 npm run dev
生产环境打包js文件会被压缩。因为没有使用css压缩插件,所以css看不出效果。
总结
使用插件webpack-merge,区分生产环境和开发环境 npm install --save-dev webpack-merge
webpack.dev.js文件内容
const path = require('path')const merge = require('webpack-merge');const common = require('./webpack.common.js');module.exports = merge(common,{ mode:'development', //开发模式});复制代码
webpack.prod.js文件内容
const path = require('path')const merge = require('webpack-merge');const common = require('./webpack.common.js');module.exports = merge(common,{ mode:'production', //生产模式});复制代码