安装
yarn add --dev webpack-bundle-analyzer
原始webpack.config.js
代码定义了 Webpack 的配置,主要任务是将 JavaScript 和 CSS 文件打包,并将 CSS 提取到单独的文件中,配置了对 Electron 应用的支持,同时还将 React 相关的模块映射到 Preact,以减小打包体积。
const path = require ( 'path' ) ;
const ExtractTextPlugin = require ( 'extract-text-webpack-plugin' ) ;
const extractCSSPlugin = new ExtractTextPlugin ( {
filename : 'css/[name].css' ,
allChunks : true ,
} ) ;
module. exports = {
entry : path. resolve ( __dirname, 'src' , 'ui' , 'index.js' ) ,
output : {
filename : 'js/bundle.js' ,
path : path. resolve ( __dirname, 'src' , 'static' ) ,
} ,
target : 'electron' ,
module : {
rules : [
{
test : / \.(js|jsx)$ / ,
loader : 'babel-loader' ,
include : [
path. resolve ( __dirname, 'src' , 'ui' ) ,
] ,
} ,
{
test : / \.(css|scss)$ / ,
loader : extractCSSPlugin. extract ( {
use : [
{
loader : 'css-loader' ,
options : {
modules : true ,
importLoaders : 2 ,
localIdentName : '[name]--[local]___[hash:base64:5]' ,
} ,
} ,
] ,
} ) ,
} ,
] ,
} ,
resolve : {
alias : {
'react' : 'preact-compat' ,
'react-dom' : 'preact-compat' ,
} ,
modules : [
path. resolve ( __dirname, 'node_modules' ) ,
path. resolve ( __dirname, 'src' , 'ui' ) ,
path. resolve ( __dirname, 'src' , 'electron' ) ,
] ,
extensions : [ '.js' , '.jsx' , '.json' ] ,
} ,
plugins : [ extractCSSPlugin] ,
} ;
使用webpack-bundle-analyzer
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const extractCSSPlugin = new ExtractTextPlugin({
filename: 'css/[name].css',
allChunks: true,
});
// 1.引入webpack的 BundleAnalyzerPlugin 插件
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const bundleAnalyzerPlugin = new BundleAnalyzerPlugin();
module.exports = {
entry: path.resolve(__dirname, 'src', 'ui', 'index.js'),
output: {
filename: 'js/bundle.js',
path: path.resolve(__dirname, 'src', 'static'),
},
target: 'electron',
module: {
rules: [
{
test: /\.(js|jsx)$/,
loader: 'babel-loader',
include: [
path.resolve(__dirname, 'src', 'ui'),
],
},
{
test: /\.(css|scss)$/,
loader: extractCSSPlugin.extract({
use: [
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 2,
localIdentName: '[name]--[local]___[hash:base64:5]',
},
},
],
}),
},
],
},
resolve: {
alias: {
'react': 'preact-compat',
'react-dom': 'preact-compat',
},
modules: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, 'src', 'ui'),
path.resolve(__dirname, 'src', 'electron'),
],
extensions: ['.js', '.jsx', '.json'],
},
plugins: [extractCSSPlugin,bundleAnalyzerPlugin], // 2.注册BundleAnalyzerPlugin插件
};
可视化结果
PS C:\Users\kingchuxing\Documents\IPFS\party\Partyshare-master> npx webpack
…………
Webpack Bundle Analyzer is started at http://127.0.0.1:8888
Use Ctrl+C to close it