webpack动态加载组件,components is=xxx; xxxx自动加载,加载不到还能保底加载个base组件
目前有个vue2项目,h5;展示多个卡片内容,卡片内容根据后台返回的数据结构展示对应的内容。
1、template中:【组件渲染】
点击查看代码
<component
:is="chartsName"
:id="name"
:focusTag='focusTag'
ref="tplItem"
:title="cardName"
:res="res"
:guidanceId="guidanceId"
@chooseClassify="chooseClassify"
:index="index"
:cardType="cardType"
:cardName="cardName"
></component>
2、js中:【组件动态加载,主要是webpack带的功能 require.ensure】
点击查看代码
computed: {
chartsName() {
const nameArr = this.name.split("_");
const zbName = nameArr.pop();
const path = nameArr.join("/");
return (r) =>
// eslint-disable-next-line no-undef
require.ensure(
[],
// 正常情况下加载这个
() => r(require(`@/components/tpl/${path}/${zbName}.vue`)),
// 当组件加载不到,就加载通用的组件
() => {
return r(require(`@/components/tpl/components/commonCard.vue`))
}
);
},
},
3、vue.config.js【开启分离js】
"compression-webpack-plugin": "^5.0.0",
点击查看代码
const Timestamp = new Date().getTime(); // 当前时间为了防止打包缓存不刷新,所以给每个js文件都加一个时间戳
const pro = process.env.NODE_ENV === 'production';
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const path = require('path');
点击查看代码
configureWebpack: (config) => {
config.externals = assetsCDN.externals;
config.output.filename = `js/[name].${Timestamp}.js`;
config.output.chunkFilename = `js/[name].${Timestamp}.js`;
config.devtool = pro ? undefined : "source map";
if (pro) {
// 开启gzip压缩
const productionGzipExtensions =
/\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i;
config.plugins.push(
new CompressionWebpackPlugin({
filename: "[path].gz[query]",
algorithm: "gzip",
test: productionGzipExtensions,
threshold: 10240,
minRatio: 0.8,
})
);
// 开启分离js
config.optimization = {
splitChunks: {
chunks: "all",
cacheGroups: {
// 新增分离vant
vant: {
name: "chunk-vant",
priority: 20,
test: /[\\/]node_modules[\\/]_?vant(.*)/,
},
vendors: {
name: "chunk-vendors",
test: /[\\/]node_modules[\\/]/,
priority: 10,
chunks: "initial",
},
common: {
name: "chunk-common",
minChunks: 2,
priority: 5,
chunks: "initial",
reuseExistingChunk: true,
},
},
},
};
}
},
本文来自博客园,作者:Math点PI,个性签名:“不写bug怎么进步?”,转载请注明原文链接:https://www.cnblogs.com/MrZhous/p/18230621
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构