微前端qiankun子应用把webpack换成vite

 一、项目技术

vue3 + qiankun + antdesign + lerna + less + pinia + yarn + ts

目前除了主应用是vite,其他子应用都是webpack

想要子应用用vite,得依赖vite-plugin-qiankunvite-plugin-qiankun

yarn add vite-plugin-qiankun

二、改造main和新建vite.config.ts

改造main.ts

import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper';



function render(props: any = {}) {
//...等代码
}

renderWithQiankun({
  mount(props) {
    render(props);
    // store.commit("updateUserInfo",props);
    // 在vue全局注册主应用的状态监听和状态改变事件
    instance.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
    instance.config.globalProperties.$setGlobalState = props.setGlobalState;

    props.onGlobalStateChange((state: Record<keyof GlobalState, any>) => {
      const userStore = useUserStore();

      userStore.$patch({ ...state });
    }, true);
  },
  bootstrap() {
    console.log('bootstrap');
  },
  unmount() {
    console.log('unmount');
    const store = useUserStore();
    store.$reset();
    instance.unmount();
    instance._container.innerHTML = '';
    instance = null;
    router = null;
    history.destroy();
  },
  update() {
    console.log('jfm-vite-update');
  }
});

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render();
}

添加vite.config.ts

我这里大部分借鉴gitHub的Vben的配置,可以自己去看一下Vben

用vite的库模式把子应用打包成umd格式

import path from 'path';
import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite';
import { themeConfig, microAppConfig } from '@2shu/common';
import pkg from './package.json';
// const { loadEnv, getEnvConfig } = require('./build/env');
import { wrapperEnv } from './build/utils';

import { createVitePlugins } from './build/plugins';

const { jfm } = microAppConfig;
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  console.log(path.resolve(__dirname, './src/main.ts'));
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const viteEnv = wrapperEnv(env);
  const { VITE_DROP_CONSOLE } = viteEnv;
  const isProd: boolean = command === 'build';
  return {
    base: isProd ? '' : '/',
    // root: resolve(__dirname, './public/'),
    resolve: {
      alias: [
        {
          find: '@',
          replacement: path.resolve(__dirname, './src')
        },
        {
          find: 'vue',
          replacement: 'vue/dist/vue.esm-bundler.js' // compile template
        }
      ],
      extensions: ['.ts', '.js']
    },
    define: {
      'process.env': {}
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            ...themeConfig
          },
          javascriptEnabled: true
        }
      }
    },

    build: {
      target: 'es2015',
      lib: {
        name: 'umd',
        entry: path.resolve(__dirname, './src/main.ts'),
        formats: ['umd'],
        fileName: pkg.name
      },
      minify: 'terser',
      outDir: 'dist',
      terserOptions: {
        compress: {
          keep_infinity: true,
          // Used to delete console in production environment
          drop_console: VITE_DROP_CONSOLE
        }
      },
      rollupOptions: {
        // input: {
        //   1: path.resolve(__dirname, './public/index.html')
        // },
        output: {
        }
      },
      chunkSizeWarningLimit: 2000
    },
    //@ts-ignore
    plugins: [createVitePlugins(viteEnv, isProd, jfm.name)],

    experimental: {
      renderBuiltUrl: (filename: string) => {
        return `${process.env.ORIGIN}${filename}`;
      }
    },
    optimizeDeps: {
      include: ['ant-design-vue/es/locale/zh_CN']
    }
  };
});

替换变量格式、

将子应用各个地方的类型或者变量,之前的VUE_APP_GLOB_API_URL这种格式换VITE_GLOB_API_URL

改造index.html、 

改造index.html,之前index.html在public文件夹里面,将它移到根目录下,放在public里面也可以,但是vite.config.ts的input要指定他的路径即可。官方放在根目录下面,我们就老老实实的的放在根目录下。

index.html详细看这里

开始 | Vite 官方中文文档镜像Vite 是下一代前端开发与构建工具。Vite 意在提供开箱即用的配置,同时它的 插件 API 和 JavaScript API 带来了高度的可扩展性,并有完整的类型支持。https://vitejs.bootcss.com/guide/#index-html-and-project-root

 <title><%= title %></title>
    <script><%- injectEnvConfig %></script>
  </head>
  <body>
    <div id="app" style="height: 100%"></div>
    <script type="module" src="/src/main.ts"></script>
    <!-- built files will be auto injected -->
  </body>

步骤三、

src目录下面新建vite-env.d.ts文件

/// <reference types="vite/client" />

declare module '*.vue' {
  import type { DefineComponent } from 'vue';
  const component: DefineComponent<{}, {}, any>;
  export default component;
}

interface Window {
  ENV_CONFIG: {
    VITE_GLOB_API_URL: string;
    VITE_GLOB_CLIENT_ID: string;
  };
  __POWERED_BY_QIANKUN__?: boolean;
  __INJECTED_PUBLIC_PATH_BY_QIANKUN__?: string;
}

根目录下面新建components.d.ts文件

// generated by unplugin-vue-components
// We suggest you to commit this file into source control
// Read more: https://github.com/vuejs/core/pull/3399
import '@vue/runtime-core'

export {}

declare module '@vue/runtime-core' {
  export interface GlobalComponents {
    RouterLink: typeof import('vue-router')['RouterLink']
    RouterView: typeof import('vue-router')['RouterView']
  }
}

总体大概是这些,最后打包出来的,上面是webpack打包出来的格式,下面是vite打包出来的umd格式

我所安装的依赖,记得package.json的这里也要改

 

 

有错误可以指点出来,有疑问也可以提出

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值