說(shuō)明:將webpack.config.js拆分成開發(fā)時(shí)兩個(gè)配置文件webpack.dev.js和webpack.prod.js分別用于開發(fā)愚争、和生產(chǎn)惠昔,將公共部分集成到webpack.common.js中,打包的時(shí)候再合并己肮,webpack-merge可以幫我干這個(gè)事胚泌。
安裝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"
}
項(xiàng)目目錄
總結(jié):對(duì)于生產(chǎn)環(huán)境來(lái)說(shuō)是不需要devServer菌瘪、hmr這些模塊的功能將webpack.config.js文件分開须眷,更利于項(xiàng)目的維護(hù).