保留vite es特性,快速接入乾坤微前端子应用

Overview

简介

vite-plugin-qiankun: 帮助应用快速接入乾坤的vite插件

  • 保留vite构建es模块的优势
  • 一键配置,不影响已有的vite配置

快速开始

1、在 vite.config.ts 中安装插件
// vite.config.ts

import qiankun from 'vite-plugin-qiankun';

export default {
  // 这里的 'myMicroAppName' 是子应用名,主应用注册时AppName需保持一致
  plugins: [qiankun('myMicroAppName')],
  // 生产环境需要指定运行域名作为base
  base: 'http://xxx.com/'
}
2、在入口文件里面写入乾坤的生命周期配置
// main.ts
import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper';

// some code
renderWithQiankun({
  mount(props) {
    console.log('mount');
    render(props);
  },
  bootstrap() {
    console.log('bootstrap');
  },
  unmount(props: any) {
    console.log('unmount');
    const { container } = props;
    const mountRoot = container?.querySelector('#root');
    ReactDOM.unmountComponentAtNode(
      mountRoot || document.querySelector('#root'),
    );
  },
});

if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
  render({});
}
3、其它使用注意点 qiankunWindow

因为es模块加载与qiankun的实现方式有些冲突,所以使用本插件实现的qiankun微应用里面没有运行在js沙盒中。所以在不可避免需要设置window上的属性时,尽量显示的操作js沙盒,否则可能会对其它子应用产生副作用。qiankun沙盒使用方式

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

qiankunWindow.customxxx = 'ssss'

if (qiankunWindow.__POWERED_BY_QIANKUN__) {
  console.log('我正在作为子应用运行')
}

例子

详细的信息可以参考例子里面的使用方式

git clone xx
npm install
npm run example:install
npm run example:start

todo

  • 支持vite开发环境
Comments
  • react+vite 已经可以了,但 vue+vite 还不行。。。

    react+vite 已经可以了,但 vue+vite 还不行。。。

    可复现示例:https://github.com/rxliuli/micro-app-demo

    overlay.ts:185 Uncaught (in promise) DOMException: Failed to execute 'define' on 'CustomElementRegistry': the name "vite-error-overlay" has already been used with this registry
    

    vite 配置

    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import qiankun from 'vite-plugin-qiankun'
    
    //useDevMode 开启时与热更新插件冲突
    const useDevMode = true
    
    export default defineConfig({
      plugins: [
        //TODO vue 仍然不能正常支持
        vue(),
        qiankun('vue-app', {
          useDevMode,
        }),
      ],
      server: {
        port: 3102,
        cors: true,
      },
    })
    
    

    src/main.ts

    import { createApp, App as VueInstance } from 'vue'
    import App from './App.vue'
    
    import {
      renderWithQiankun,
      qiankunWindow,
    } from 'vite-plugin-qiankun/dist/helper'
    import {
      createRouter,
      createWebHashHistory,
      Router,
      RouterHistory,
    } from 'vue-router'
    import { routeList } from './constants/routeList'
    
    let app: VueInstance | null = null
    let history: RouterHistory | null = null
    let router: Router | null = null
    
    function render(props: any) {
      const { container } = props
      app = createApp(App)
      history = createWebHashHistory(
        qiankunWindow.__POWERED_BY_QIANKUN__ ? '/app/vue-app' : '',
      )
      router = createRouter({
        history: history,
        routes: routeList,
      })
      app.use(router)
      app.mount(
        container
          ? container.querySelector('#root')
          : document.getElementById('root'),
      )
    }
    
    renderWithQiankun({
      mount(props) {
        console.log('vue mount')
        render(props)
      },
      bootstrap() {
        console.log('bootstrap')
      },
      unmount(props: any) {
        console.log('vue unmount')
        app!.unmount()
        ;(app!._container as HTMLDivElement).innerHTML = ''
        app = null
        router = null
        history!.destroy()
        history = null
      },
    })
    
    if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
      render({})
    }
    
    

    react 版本其实也有个不影响运行的错误

    Uncaught (in promise) DOMException: Failed to execute 'define' on 'CustomElementRegistry': the name "vite-error-overlay" has already been used with this registry
    
    opened by rxliuli 19
  • 以vue为主配置vite与qiankun后,在作为子应用接入后,页面一直重定向跳转

    以vue为主配置vite与qiankun后,在作为子应用接入后,页面一直重定向跳转

    main.ts `import { App as VueInstance, createApp } from 'vue' import App from './App.vue'

    import { qiankunWindow, renderWithQiankun, } from 'vite-plugin-qiankun/dist/helper' import { createMemoryHistory, createRouter, Router, RouterHistory, createWebHashHistory } from 'vue-router' import { routeList } from './constants/routeList' // import 'ant-design-vue/dist/antd.less'

    let app: VueInstance | null = null let history: RouterHistory | null = null let router: Router | null = null

    function render(props: any) { const { container } = props app = createApp(App) history = createWebHashHistory( // qiankunWindow.POWERED_BY_QIANKUN ? '/app/vue-app' : '', qiankunWindow.POWERED_BY_QIANKUN ? '#' : '', ) history = createWebHashHistory() router = createRouter({ history: history, routes: routeList, }) app.use(router) app.mount( container ? container.querySelector('#root') : document.getElementById('root'), ) }

    renderWithQiankun({ mount(props: any) { console.log('vue mount') render(props) }, bootstrap() { console.log('bootstrap') }, unmount(props: any) { console.log('vue unmount') app!.unmount() ; (app!._container as HTMLDivElement).innerHTML = '' app = null router = null history!.destroy() history = null }, })

    if (!qiankunWindow.POWERED_BY_QIANKUN) { console.log('本地执行') render({}) } `

    opened by LiZheGuang 8
  • 依赖包下载失败

    依赖包下载失败

    我这边下载依赖就失败了,可以帮忙看看吗

    `npm i vite-plugin-qiankun npm ERR! code 1 npm ERR! path E:\crm-static\node_modules\canvas npm ERR! command failed npm ERR! command C:\windows\system32\cmd.exe /d /s /c node-gyp rebuild npm ERR! gyp info it worked if it ends with ok npm ERR! gyp info using [email protected] npm ERR! gyp info using [email protected] | win32 | x64 npm ERR! gyp ERR! find Python npm ERR! gyp ERR! find Python Python is not set from command line or npm configuration npm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON npm ERR! gyp ERR! find Python checking if "python3" can be used npm ERR! gyp ERR! find Python - "python3" is not in PATH or produced an error npm ERR! gyp ERR! find Python checking if "python" can be used npm ERR! gyp ERR! find Python - "python" is not in PATH or produced an error npm ERR! gyp ERR! find Python checking if "python2" can be used npm ERR! gyp ERR! find Python - "python2" is not in PATH or produced an error npm ERR! gyp ERR! find Python checking if Python is C:\Python37\python.exe npm ERR! gyp ERR! find Python - "C:\Python37\python.exe" could not be run npm ERR! gyp ERR! find Python checking if Python is C:\Python27\python.exe npm ERR! gyp ERR! find Python - "C:\Python27\python.exe" could not be run npm ERR! gyp ERR! find Python checking if the py launcher can be used to find Python npm ERR! gyp ERR! find Python - "py.exe" is not in PATH or produced an error npm ERR! gyp ERR! find Python npm ERR! gyp ERR! find Python ********************************************************** npm ERR! gyp ERR! find Python You need to install the latest version of Python. npm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not, npm ERR! gyp ERR! find Python you can try one of the following options: npm ERR! gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe" npm ERR! gyp ERR! find Python (accepted by both node-gyp and npm) npm ERR! gyp ERR! find Python - Set the environment variable PYTHON npm ERR! gyp ERR! find Python - Set the npm configuration variable python: npm ERR! gyp ERR! find Python npm config set python "C:\Path\To\python.exe" npm ERR! gyp ERR! find Python For more information consult the documentation at: npm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation npm ERR! gyp ERR! find Python ********************************************************** npm ERR! gyp ERR! find Python npm ERR! gyp ERR! configure error npm ERR! gyp ERR! stack Error: Could not find any Python installation to use npm ERR! gyp ERR! stack at PythonFinder.fail (C:\Users\EDZ\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:302:47) npm ERR! gyp ERR! stack at PythonFinder.runChecks (C:\Users\EDZ\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:136:21) npm ERR! gyp ERR! stack at PythonFinder. (C:\Users\EDZ\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:200:18) npm ERR! gyp ERR! stack at PythonFinder.execFileCallback (C:\Users\EDZ\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:266:16) npm ERR! gyp ERR! stack at exithandler (child_process.js:326:5) npm ERR! gyp ERR! stack at ChildProcess.errorhandler (child_process.js:338:5) npm ERR! gyp ERR! stack at ChildProcess.emit (events.js:376:20) npm ERR! gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:275:12) npm ERR! gyp ERR! stack at onErrorNT (internal/child_process.js:467:16) npm ERR! gyp ERR! stack at processTicksAndRejections (internal/process/task_queues.js:82:21) npm ERR! gyp ERR! System Windows_NT 10.0.19041 npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\EDZ\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "rebuild" npm ERR! gyp ERR! cwd E:\crm-static\node_modules\canvas npm ERR! gyp ERR! node -v v14.17.0 npm ERR! gyp ERR! node-gyp -v v7.1.2 npm ERR! gyp ERR! not ok

    npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\EDZ\AppData\Local\npm-cache_logs\2021-07-06T12_33_01_108Z-debug.log `

    opened by terry-guo 5
  • 打包后资源无法独立部署

    打包后资源无法独立部署

    如上,打包后的index.html文件中有一条script, 会导入打包后的js然后执行一些操作,这时候放在微前端里面是能直接打开的。。但是通过 "start": "http-server ./dist -p 7106 --cors" 命令开启的服务,直接访问 http://127.0.0.1:7106, 是不会运行main.js中的

    if (!qiankunWindow.POWERED_BY_QIANKUN) { // 独立运行的 render() } 我这边想到的是,在打包后的html里面插入一条script,判断当前是乾坤运行环境,生成一条 插入到body中

    opened by terry-guo 4
  • 启动后控制台报错 但并不影响使用

    启动后控制台报错 但并不影响使用

    图片

    主应用的依赖:

    {
      "devDependencies": {
        "@types/node": "^17.0.36",
        "@types/webpack": "^5.28.0",
        "@types/webpack-env": "^1.17.0",
        "clean-webpack-plugin": "^4.0.0",
        "html-webpack-plugin": "^5.5.0",
        "ts-loader": "^9.3.0",
        "ts-node": "^10.8.0",
        "typescript": "^4.7.2",
        "webpack": "^5.72.1",
        "webpack-cli": "^4.9.2",
        "webpack-dev-server": "^4.9.0"
      },
      "dependencies": {
        "qiankun": "^2.7.2"
      }
    }
    

    子应用的依赖:

    {
      "dependencies": {
        "vue": "^3.2.33",
        "vue-router": "^4.0.14"
      },
      "devDependencies": {
        "@rushstack/eslint-patch": "^1.1.0",
        "@types/node": "^16.11.27",
        "@vitejs/plugin-vue": "^2.3.1",
        "@vitejs/plugin-vue-jsx": "^1.3.10",
        "@vue/eslint-config-prettier": "^7.0.0",
        "@vue/eslint-config-typescript": "^10.0.0",
        "@vue/tsconfig": "^0.1.3",
        "eslint": "^8.5.0",
        "eslint-plugin-vue": "^8.2.0",
        "prettier": "^2.5.1",
        "typescript": "~4.6.3",
        "vite": "^2.9.5",
        "vite-plugin-qiankun": "^1.0.14",
        "vue-tsc": "^0.34.7"
      }
    }
    

    npm 和 pnpm 都试过了

    ❯ npm -v
    8.10.0
    
    ❯ pnpm -v
    7.1.0
    
    opened by BTBMan 1
  • 修改部分type定义的类型为interface

    修改部分type定义的类型为interface

    将可扩展类型的定义从type改为interface,方便用户扩展类型

    env.d.ts

    import 'vite-plugin-qiankun/dist/helper'
    
    declare module 'vite-plugin-qiankun/dist/helper' {
      interface QiankunWindow {
        test: boolean
      }
    }
    

    main.ts

    import {  qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
    
    qiankunWindow.test = true
    
    opened by HaibaraAiSherry 0
  • Cannot add  vite-plugin-qiankun with yarn

    Cannot add vite-plugin-qiankun with yarn

    Can not install vite-plugin-qiankun with yarn install command line: 截屏2022-11-22 13 41 25

    I try many times and it always stuck on the final few dependencies, dont know why, even if I had use: yarn config set network-timeout 600000 -g to enable long fetch time.

    If there any other soluction to connect qiankun with vite?

    opened by AlanKnightly 0
  • I can't apply this plugin on nuxtjs(Nuxt3) framework.

    I can't apply this plugin on nuxtjs(Nuxt3) framework.

    Dear Mr/Mrs, I have a problem with your plugins, I attach my image(bug) on it so that you can see it. So, how can I fix it? Or any demo with nuxtjs version 3. Thanks. image

    opened by tranthotuong 0
Owner
TMQ
TMQ