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,
						},
					},
				},
			};
		}
	},
posted @   Math点PI  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示