一、背景
主应用:vue3、vite
子应用:vue3、webpack
二、代码-接入子应用
2.1、src/public-path.js
if (window.__POWERED_BY_QIANKUN__) { __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__; }
2.2、src/global.d.ts
interface Window { __POWERED_BY_QIANKUN__?: any; }
2.3、tsconfig.json
"include": [ "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx", "src/global.d.ts" ],
2.4、main.ts
import './public-path'; // qiankun import { createApp } from 'vue' import ElementPlus from 'element-plus' import 'element-plus/dist/index.css' import App from './App.vue' import router from './router' import store from './store' const app = createApp(App) app.use(store).use(router).use(ElementPlus) // .mount('#app') let instance:any = null; const render = (container:any) => { // 如果是在主应用的环境下就挂载主应用的节点,否则挂载到本地 const appDom = container ? container : "#app" app.mount(appDom) } // 独立运行时 if (!window.__POWERED_BY_QIANKUN__) { render(null); } export async function bootstrap() { console.log('[vue] vue app bootstraped'); } export async function mount(props:any) { console.log('[vue] props from main framework', props); render(props.container); } export async function unmount() { instance.$destroy(); instance.$el.innerHTML = ''; instance = null; }
2.5、vue.config.ts
'use strict' const path = require('path') const { merge } = require('webpack-merge') // 管理配置文件 const tsImportPluginFactory = require('ts-import-plugin') // 按需引入 // const config = require('./config') // 根目录配置文件 const { name } = require('./package') function resolve(dir) { return path.join(__dirname, dir) } module.exports = { publicPath: '/', outputDir: 'dist', assetsDir: 'static', lintOnSave: process.env.NODE_ENV === 'development', parallel: process.env.NODE_ENV === 'development', devServer: { headers: { // qiankun 'Access-Control-Allow-Origin': '*', }, overlay: { warnings: false, errors: true }, }, transpileDependencies: [ 'vuex-module-decorators' ], configureWebpack: { devtool: 'source-map', name: 'vue-h5-template', resolve: { alias: { '@': resolve('src') } }, output: { // qiankun library: `${name}-[name]`, libraryTarget: 'umd', // 把微应用打包成 umd 库格式 jsonpFunction: `webpackJsonp_${name}`, }, }, chainWebpack(config) { // set ts-loader config.module .rule('ts') .use('ts-loader') .tap(options => { options = merge(options, { transpileOnly: true, compilerOptions: { module: 'es2015' } }) return options }) }, css: { extract: true, sourceMap: false, requireModuleExtension: true, }, }
2.6、访问项目
三、过程记录:
解决:
src目录下创建global.d.ts
interface Window { __POWERED_BY_QIANKUN__?: any; }
tsconfig.json
"include": [ "src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx", "src/global.d.ts" ],
重启项目,不再报错,成功。