因此,我有一个使用Webpack打包的React项目,其中“供应商”文件太大(+ 5mb)。我使用webpack-bundle-analyzer来检查发生了什么:
如您所见,我的包装占用太多空间,例如:
我认为问题出在我的weback.config上,如下所示:
const webpack = require('webpack')
const path = require('path')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const CompressionWebpackPlugin = require('compression-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const config = {
mode: 'production',
devtool: 'inline-source-map',
entry: {
front: [path.resolve('./assets/index.js')],
},
resolve: {
modules: ['assets', 'node_modules'],
extensions: ['.js', '.jsx'],
},
output: {
path: path.resolve('dist'),
filename: '[name].min.js',
chunkFilename: '[name].min.js'
},
optimization: {
runtimeChunk: false,
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
styles: {
name: 'styles',
test: /\.css$/,
chunks: 'all',
enforce: true,
},
},
},
minimizer: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true,
}),
new OptimizeCSSAssetsPlugin({}),
],
},
module: {
rules: [{
test: /\.(js|jsx)$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
}
},
{
test: /react-icons\/(.)*(.js)$/,
loader: 'babel-loader',
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.(eot|woff|woff2|ttf|svg|png|jpe?g|gif)(\?\S*)?$/,
use: [{
loader: 'url-loader',
options: {
limit: 100000,
name: '[name].[ext]',
},
}, ]
},
]
},
plugins: [
new HtmlWebpackPlugin({
template: './assets/index.html',
favicon: './assets/favicon.ico',
filename: 'index.html',
inject: 'body',
excludeChunks: [ 'server' ]
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
new webpack.optimize.AggressiveMergingPlugin(),
new CompressionWebpackPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\\.(js|css)$'),
threshold: 10240,
minRatio: 0.8,
}),
new BundleAnalyzerPlugin()
]
}
module.exports = config