在乾坤微前端优化(一)的基础上再次进行了优化,本次优化的是子模块共同的配置,以及dll包。
DllReferencePlugin配置
直接上dll配置的代码:
const path = require('path');
const webpack = require('webpack');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
// antd 模块
const antdModules = ['form', 'upload',
'switch', 'button',
'input', 'table',
'message', 'modal',
'tooltip', 'select',
'tree-select', 'date-picker',
'input-number', 'radio',
'popconfirm', 'grid'
];
// ['echarts/lib/echarts',
// 'echarts/lib/chart/line', 'echarts/lib/chart/bar', 'echarts/lib/chart/pie',
// 'echarts/lib/component/tooltip', 'echarts/lib/component/grid', 'echarts/lib/component/title', 'echarts/lib/component/legend']
module.exports = {
mode: 'production',
entry: {
echarts: ['echarts'],
xlsx: ['xlsx'],
antd: antdModules.map(item => `antd/es/${item}`).concat(['history', 'react-router-dom', 'react-router']), // 链接到这里是因为打包会产生react.js代码
vendor: ['axios', 'scroll-into-view-if-needed']
},
output: {
filename: 'dll.[name].js',
path: path.resolve(__dirname, '../dll'),
// 全局变量名称
library: '[name]_library'
},
plugins: [
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: [path.resolve(__dirname, '../dll/**/*')]
}),
new webpack.DllPlugin({
// 和library 一致,输出的manifest.json中的name值
name: '[name]_library',
// path 指定manifest.json文件的输出路径
path: path.resolve(__dirname, '../dll/[name]-manifest.json'),
}),
// new BundleAnalyzerPlugin(),
new FriendlyErrorsPlugin(),
],
stats: 'errors-only',
// 关闭文件过大检查
performance: {
hints: false
},
}
以上配置基本满足要求了。
缺点:不能自动按需加载,需要自己配置。
比如说我自己配置的antd按需加载,自己写加载的路径。
ps:echarts按需加载不知道怎么写。
webpack.config配置
主应用的配置基本不变,第二版主要是改变了子应用的webpack配置,把子应用的webpack配置放到了基础模板中,后续子应用直接从基础模板中导入webpack配置并合并配置。
公共配置
webpack.config.base
// webpack.config.base.js
const path = require('path');
// 动态生成html文件
const HtmlWebpackPlugin = require('html-webpack-plugin');
// 清除文件夹
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// 抽取css代码
const MiniCssRxtractPlugin = require('mini-css-extract-plugin');
// 控制台删除无效的打印
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin');
// 压缩css
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// 给模块做缓存
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
// 生产包分析
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// js压缩
const TerserPlugin = require('terser-webpack-plugin');
//
const Webpack = require('webpack');
const { isEnvProduction, isEnvDevelopment, lessLoader, cssLoader, tsxLoader, sourceLoader, ttfLoader } = require('./utils');
// 引入配置文件
const { dllReferencePlugins } = require('./path.json');
module.exports = {
// 入口
entry: "./src/index.tsx",
// 生产模式下关闭map文件
devtool: isEnvProduction ? "none" : "source-map",
// 解析相关
resolve: {
extensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
alias: {
// '@': resolve('../src')
}
},
// 模块
module: {
rules: [tsxLoader, isEnvProduction ? null : sourceLoader, cssLoader, lessLoader, ttfLoader].filter(Boolean),
},
// 插件
plugins: [
new MiniCssRxtractPlugin({
filename: `static/styles/[name]${isEnvProduction ? '.[hash:8]' : ''}.css`,
chunkFilename: `static/styles/[name]${isEnvProduction ? '.[hash:8]' : ''}.css`
}),
new HtmlWebpackPlugin({
template: './public/index.html',
inject: true,
minify: {
removeComments: true, // 移除注释
collapseWhitespace: true, // 移除空格
}
}),
// 导入
...dllReferencePlugins.map(item => new Webpack.DllReferencePlugin({
manifest: path.join(__dirname, `../../cstmr-paltform-base/dll/${item}-manifest.json`)
})),
isEnvDevelopment && new Webpack.HotModuleReplacementPlugin(),
new HardSourceWebpackPlugin(),
isEnvProduction && new CleanWebpackPlugin(),
new FriendlyErrorsPlugin(),
isEnvProduction ? new BundleAnalyzerPlugin({
analyzerPort: Math.floor(Math.random() * 9000) + 1000
}) : null,
].filter(Boolean),
stats: 'errors-only',
// // 关闭文件过大检查
performance: {
hints: false
},
// 优化
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
antd: {
test: /[\\/]node_modules[\\/]antd[\\/]/,
name: 'antd',
priority: 10 // 需要级别高点
},
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendor',
priority: 8
}
}
},
runtimeChunk: {
name: 'runtime'
},
minimizer: [
new TerserPlugin({
terserOptions: {
parse: {
// we want terser to parse ecma 8 code. However, we don't want it
// to apply any minfication steps that turns valid ecma 5 code
// into invalid ecma 5 code. This is why the 'compress' and 'output'
// sections only apply transformations that are ecma 5 safe
// https://github.com/facebook/create-react-app/pull/4234
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
// Disabled because of an issue with Uglify breaking seemingly valid code:
// https://github.com/facebook/create-react-app/issues/2376
// Pending further investigation:
// https://github.com/mishoo/UglifyJS2/issues/2011
comparisons: false,
// Disabled because of an issue with Terser breaking valid code:
// https://github.com/facebook/create-react-app/issues/5250
// Pending futher investigation:
// https://github.com/terser-js/terser/issues/120
inline: 2,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
// Turned on because emoji and regex is not minified properly using default
// https://github.com/facebook/create-react-app/issues/2488
ascii_only: true,
},
},
// Use multi-process parallel running to improve the build speed
// Default number of concurrent runs: os.cpus().length - 1
// Disabled on WSL (Windows Subsystem for Linux) due to an issue with Terser
// https://github.com/webpack-contrib/terser-webpack-plugin/issues/21
parallel: false,
// Enable file caching
cache: true,
sourceMap: false,
}),
new OptimizeCSSAssetsPlugin({
cssProcessor: require('cssnano'), //引入cssnano配置压缩选项
cssProcessorOptions: {
discardComments: { removeAll: true }
},
canPrint: false
})
]
},
// devServer 配置
devServer: {
historyApiFallback: true,
port: '9001',
hot: true,
hotOnly: true,
inline: true,
headers: {
"Access-Control-Allow-Origin": "*"
},
proxy: {
'/api': {
target: 'https://dev.mhealth100.com',
changeOrigin: true, // 跨域
pathRewrite: {
'^/api': '/'
}
},
},
}
}
// path.json
{
"root": {
"development": "/",
"production": "/dist"
},
"dllReferencePlugins": [
"echarts",
"xlsx",
"vendor",
"antd"
]
}
webpack.config
const path = require('path');
const resolve = dir => path.resolve(__dirname, dir);
// 选取最后一个值
const mode = process.argv.slice(-1)[0];
const isEnvProduction = mode === 'production';
const { merge } = require('webpack-merge');
//
const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin');
const webpackConfg = require('../../base-template/webpack-config/webpack.config');
const packageName = require('../package.json').name;
const { root: { production: pathName } } = require('./../../base-template/webpack-config/path.json');
// 图片解析
const imageLoader = {
test: /\.(png|svg|jpe?g)$/,
use: [
{
loader: 'url-loader',
options: {
limit: 1024 * 10,
name: `/images/[name].[hash:7].[ext]`,
publicPath: isEnvProduction ? `${pathName}/${packageName}/` : '/'
}
}
]
}
module.exports = merge([webpackConfg, {
// 出口
output: {
filename: `static/js/[name]${isEnvProduction ? '.[hash:8]' : ''}.js`,
path: path.join(__dirname, `../${packageName}`),
publicPath: isEnvProduction ? `${pathName}/${packageName}/` : "/",
library: `${packageName}`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_${packageName}`,
},
// 模块
module: {
rules: [imageLoader],
},
plugins: [new WatchMissingNodeModulesPlugin(resolve('../node_modules'))],
resolve: {
alias: {
'@': resolve('../src')
}
},
devServer: {
port: '9001'
}
}])
注意:这个需要重新定义文件的相对地址,比如说pathName和packageName等数据,重新定义resolve,不然他会打包到base-template模板的代码,而不会打包当前子应用的代码。
打包上线
至此,打包上线即可。