通过环境变量,对webpack的配置做一些拆分和merge。
打包配置文件目录:
分别是通用配置项,开发环境配置项,生产环境配置项
打包时,脚本选择的weback配置文件:webpack.common.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
// 引入webpack用于合并配置的merge
const merge = require('webpack-merge');
// 开发环境配置
const devConfig = require('./webpack.dev.js');
// 生产环境配置
const prodConfig = require('./webpack.prod.js');
// 通用配置项
const commonConfig = {
entry: {
main: './src/index.js',
},
module: {
rules: [{
test: /\.js$/,
exclude: /node_modules/,
use: [{
loader: 'babel-loader'
}, {
loader: 'imports-loader?this=>window'
}]
}, {
test: /\.(jpg|png|gif)$/,
use: {
loader: 'url-loader',
options: {
name: '[name]_[hash].[ext]',
outputPath: 'images/',
limit: 10240
}
}
}, {
test: /\.(eot|ttf|svg)$/,
use: {
loader: 'file-loader'
}
}]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new CleanWebpackPlugin(['dist'], {
root: path.resolve(__dirname, '../')
}),
new webpack.ProvidePlugin({
$: 'jquery',
_join: ['lodash', 'join']
}),
],
optimization: {
runtimeChunk: {
name: 'runtime'
},
usedExports: true, //tree shaking的配置
splitChunks: {
chunks: 'all',
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
name: 'vendors',
}
}
}
},
performance: false, //关闭终端有关性能优化的提示
output: {
path: path.resolve(__dirname, '../dist')
}
}
// 利用环境变量,来组合最终的打包配置
module.exports = (env) => {
if(env && env.production) {
return merge(commonConfig, prodConfig);
}else {
return merge(commonConfig, devConfig);
}
}