说明:将webpack.config.js拆分成开发时两个配置文件webpack.dev.js和webpack.prod.js分别用于开发、和生产,将公共部分集成到webpack.common.js中,打包的时候再合并,webpack-merge可以帮我干这个事。
安装merge
npm install webpack-merge -D
webpack.common.js
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const {CleanWebpackPlugin}= require('clean-webpack-plugin');
module.exports={
entry:{
main:'./index.js'
},
module:{
rules:[
{
test:/\.jpg$/,
use:{
loader:'file-loader',
options:{
outputPath:'images',
name:'img.jpg'
}
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},{
test: /\.scss$/,
use: [
"style-loader", // creates style nodes from JS strings
"css-loader", // translates CSS into CommonJS
"sass-loader" // compiles Sass to CSS, using Node Sass by default
]
},{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
output:{
path:path.resolve(__dirname,'./dist'),
filename:'index_bundle.js'
},
plugins:[
new HtmlWebpackPlugin({template:'./index.html'}),
new CleanWebpackPlugin()
]
}
webpack.dev.js
const webpack=require('webpack');
const merge=require('webpack-merge');
const commonConfig=require('./webpack.common.js');
const devConfig={
mode:'development',
devtool:'cheap-module-eval-source-map',
devServer:{
contentBase:'./dist',
open:true,
port:8000,
hot:true,
hotOnly:true
},
plugins:[new webpack.HotModuleReplacementPlugin()]
}
module.exports=merge(commonConfig,devConfig)
webpack.prod.js
const merge=require('webpack-merge');
const commonConfig=require('./webpack.common.js');
const prodConfig={
mode:'production',
devtool:'cheap-module-source-map'
}
module.exports=merge(commonConfig,prodConfig)
配置package.json
"scripts": {
"dev": "webpack-dev-server --config ./build/webpack.dev.js",
"build":"webpack --config ./build/webpack.prod.js"
}
项目目录
总结:对于生产环境来说是不需要devServer、hmr这些模块的功能将webpack.config.js文件分开,更利于项目的维护.