webpack4+react项目搭建(五)
2023-05-02 本文已影响0人
幻城之雪
框架优化
优化一:添加代码分割配置
页面加载过程中很有可能会出现加载很慢或者白屏的问题,这时候就需要考虑
页面需要引入的资源是否过大,如果过大导致这种问题,就可以使用代码分割去解
决。
针对本项目,具体配置如下:
optimization:{
splitChunks:{
cacheGroups:{
vendors:{
test: /(react|react-dom)/,
name: 'vendors',
priority: 10,
chunks: 'initial'
},
commons: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
name: function(module, chunks, cacheGroupKey){
return (projectName && projectName != 'all') ? `commons-${projectName}` : `commons`;
},
chunks: 'all'
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
}
优化二:添加webpack打包日志打印配置
这个就比较简单了,有专门的友好插件:
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
plugins: [
new FriendlyErrorsWebpackPlugin()
]
优化三:css中背景图片路径配置
这个问题是需要注意开发和打包时的路径输出,经研究发现,这个路径,是由url-loader配置的,具体配置如下:
{
test: /\.(jpg|png|svg|gif|jpeg)$/,
use: [
{
loader: 'url-loader', //可以设置较小资源自动base64
options: {
limit: 10240,
name(file) {
//backgroud中图片路径
let str = file.substring(file.indexOf('assets'), file.length);
let prodStr = file.substring(file.indexOf('images'), file.length);
if (options.mode === 'development') {
return '/' + str;
} else {
return '../' + prodStr;
}
}
}
}
]
}
但是这种方法会在打包的时候再项目中生成其他的文件夹,这个时候就需要在打包之后将其清除
具体配置如下:
new CleanWebpackPlugin({
cleanOnceBeforeBuildPatterns: getCleanPath(projectName),
cleanAfterEveryBuildPatterns: [path.resolve(process.cwd(), 'images/')]
})