


例如:
config文件为: webpack.common.js
// 可以通过传入env来做一些判断,是否是生产环境,或开发环境module.exports = env => {console.log(env);let common = {entry: {app: './app.js'},output: {path: __dirname+"/src/dist",filename: './[name].bundle.js'},module: {rules: []}};return common;}
运行:
webpack —config webpack.common.js —env production
文件目录结构:
这个项目里有两个环境,一个production环境,一个development环境。
webpack.common.js
注意css文件的名字。需要安装包 webpack-merge。
下面是以雪碧图为例,生产模式下需要雪碧图,而开发模式下不需要雪碧图,定义了一个数组 postPlugins,然后根据环境来设置具体需要还是不需要。
const webpack=require('webpack');const extractTextCss=require('extract-text-webpack-plugin');const dev=require('./webpack.dev.js');const pro=require('./webpack.pro.js');const merge=require('webpack-merge');module.exports=env=>{var postPlugins=[require('autoprefixer')(), require('postcss-cssnext')()];postPlugins.concat(env==='production'?[require('postcss-sprites')({spritePath: 'dist/sprite',retina: true})]:[])//配置对象var common={entry:'./app.js',output:{filename:'bundle.js'},module:{rules: [//js处理{test:/\.js$/,use:{loader:'babel-loader',}},//css处理{test:/\.less$/,use:extractTextCss.extract({fallback:{loader:'style-loader',options:{//insertInto:"#mydiv",singleton:true,//transform:"./transform.js"}},use:[{loader:'css-loader',options:{modules:{localIdentName:'[path][name]_[local]_[hash:4]'}}},{loader:'postcss-loader',options:{ident:'postcss',plugins:postPlugins}},{loader:'less-loader'}]})},]},plugins:[//提取额外css文件new extractTextCss({filename:env==='production'?'app.bundle.css':'app.dev.css'})]};//返回配置对象return merge(common,env==='production'?pro:dev);}
webpack.dev.js:
const webpack = require('webpack')module.exports={devtool: 'cheap-module-source-map',devServer: {port: 9001,overlay: true,hot: true,hotOnly: true,},plugins: [new webpack.HotModuleReplacementPlugin(),new webpack.NamedModulesPlugin(),]}
webpack.pro.js
var webpack = require('webpack')var HtmlWebpackPlugin = require('html-webpack-plugin');module.exports={optimization: {minimize: false},plugins:[new HtmlWebpackPlugin({filename: 'index.html',template: './index.html',minify: {collapseWhitespace: true},inject:true,}),]}
package.json:
"scripts": {"test": "echo \"Error: no test specified\" && exit 1","build": "webpack --env production --config webpack.common.js","dev": "webpack-dev-server --env development --config webpack.common.js"},
webpack4中的环境区分:
设置mode就可以区分了,如 运行 webpack —mode production。
及时没有设置是否压缩,但是指定了mode为production,webpack会自动压缩打包文件。
{mode: "production",entry:'./app.js',output:{filename:'bundle.js'}}
