webpack.config.js文件拆分
建议拆分成base(公共部分)、dev(开发环境)、prod(生产环境)三个文件,再用webpack-merge整合起来。
webpack.base.conf.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const NODE_ENV = process.env.NODE_ENV || 'development';
module.exports = {
mode: NODE_ENV,
entry: {
index: ['./apps/index.js'],
},
output: {
path:'/',
publicPath: '/static/performance',
filename: `js/[name]${NODE_ENV === 'production' ? '_[contenthash:6]' : ''}.js`,
libraryTarget: 'umd',
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader?cacheDirectory',
options: {
presets: [['env', { module: false }], 'stage-0', 'react'],
plugins: [
'transform-object-rest-spread',
'transform-runtime',
'transform-decorators-legacy',
'lodash',
['import', { libraryName: 'antd', style: 'css' }],
],
env: {
development: {},
},
},
}, {
test: /.*\.(gif|png|jpe?g)$/i,
use: [
{
loader: 'file-loader',
options: {
name: 'static/imgs/[name].[ext]',
},
},
],
}, {
test: /\.(ttf|eot|svg|woff)(.*)?$/,
use: [
{
loader: 'file-loader',
options: {
name: 'static/fonts/[name].[ext]',
},
},
],
},
],
},
resolve: {
extensions: ['.js', '.css', '.less'],
alias: {
'@': path.join(__dirname, './apps/'),
},
symlinks: false,
},
plugins: [
new HtmlWebpackPlugin({
template: './apps/index.html',
}),
],
optimization: {
splitChunks: {
chunks: 'initial',
name: 'vendors',
},
},
};
webpack.dev.conf.js
const webpackMerge = require('webpack-merge');
const baseConfig = require('./webpack.base.conf');
const config = {
watchOptions: {
ignored: /node_modules/,
},
module: {
rules: [
{
test: /\.less$/,
use: [
'style-loader',
'css-loader?importLoaders=2',
'postcss-loader',
'less-loader',
],
}, {
test: /\.css$/,
use: [
'style-loader',
'css-loader?importLoaders=1',
'postcss-loader',
],
},
],
},
devtool: 'cheap-module-eval-source-map',
};
module.exports = webpackMerge(config, baseConfig);
webpack.prod.conf.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const webpackMerge = require('webpack-merge');
const webpack = require('webpack');
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const baseConfig = require('./webpack.base.conf');
const config = {
module: {
rules: [
{
test: /\.less$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader?importLoaders=2',
'postcss-loader',
'less-loader',
],
}, {
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader?importLoaders=1',
'postcss-loader',
],
},
],
},
plugins: [
new MiniCssExtractPlugin({
filename: 'css/[name]_[contenthash:6].css',
allChunks: true,
}),
new webpack.HashedModuleIdsPlugin(),
],
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
},
};
module.exports = webpackMerge(config, baseConfig);