美文网首页
vben-admin 当作乾坤子应用开发折腾

vben-admin 当作乾坤子应用开发折腾

作者: 一支桨 | 来源:发表于2023-11-20 14:30 被阅读0次

    1、vite适配乾坤安装插件
    目前为止官方还没有支持vite,直接使用的话只能解决build后的集成,看网上推荐,使用了 vite-plugin-qiankun 插件接入

    # 安装
    npm i vite-plugin-qiankun
    

    2、改造 vite.config.js,接入qiankun
    其他示例

    import { defineConfig } from 'vite'
    import qiankun from 'vite-plugin-qiankun'
    
    export default defineConfig((mode) => {
      return {
        plugins: [
          qiankun('subApp', { // 微应用名字,与主应用注册的微应用名字保持一致
            useDevMode: true,
          }),
        ],
      }
    })
    

    vben项目引用了build/vite/plugin/index.ts下的插件,因此修改此文件夹先的index.js文件

    //引入群困
    import qiankun from "vite-plugin-qiankun";
     // useDevMode 开启时与热更新插件冲突
     const useDevMode = true // 如果是在主应用中加载子应用vite,必须打开这个,否则vite加载不成功, 单独运行没影响
    
    //插件列表最后push近乾坤插件
     vitePlugins.push(qiankun('sub-app', { 
        useDevMode 
      }))
    

    3、改造入口文件main.ts
    改造入口文件,修改渲染以及添加生命周事件

    import 'virtual:windi-base.css'
    import 'virtual:windi-components.css'
    import 'virtual:windi-utilities.css'
    // Register icon sprite
    import 'virtual:svg-icons-register'
    import App from './App.vue'
    import { createApp } from 'vue'
    import { initAppConfigStore } from '/@/logics/initAppConfig'
    import { router, setupRouter } from '/@/router'
    import { setupRouterGuard } from '/@/router/guard'
    import { setupStore } from '/@/store'
    import { setupGlobDirectives } from '/@/directives'
    import { setupI18n } from '/@/locales/setupI18n'
    import { registerGlobComp } from '/@/components/registerGlobComp'
    //main.ts 中引入rem.ts winnie
    import './rem'
    // TODO 测试web worker
    // import './works'
    import { queryFlags } from '/@/enums/workflowEnum'
    window.queryFlags = queryFlags
    
    // 按钮权限
    import btnDirective from '/@/directives/permission/permission'
    // 自定义打印
    import VueUeditorWrap from 'vue-ueditor-wrap'
    
    import { isDevMode } from './utils/env'
    import './assets/font/font.css'
    if (isDevMode()) {
      import('ant-design-vue/es/style')
    }
    import Antd from 'ant-design-vue'
    import 'ant-design-vue/dist/antd.css'
    import '/@/design/index.less'
    import { renderWithQiankun, qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
    
    
    const app = createApp(App)
    async function bootstrap({container}:any) {
      // const app = createApp(App)
    
      // Configure store
      // 配置 store
      setupStore(app)
    
      // Initialize internal system configuration
      // 初始化内部系统配置
      initAppConfigStore()
    
      // Register global components
      // 注册全局组件
      registerGlobComp(app)
    
      // Multilingual configuration
      // 多语言配置
      // Asynchronous case: language files may be obtained from the server side
      // 异步案例:语言文件可能从服务器端获取
      await setupI18n(app)
    
      // Configure routing
      // 配置路由
      setupRouter(app)
    
      // router-guard
      // 路由守卫
      setupRouterGuard(router)
    
      // Register global directive
      // 注册全局指令
      setupGlobDirectives(app)
    
      // 注册全局按钮权限
      app.use(btnDirective).use(VueUeditorWrap)
      // Configure global error handling
    
      // https://next.router.vuejs.org/api/#isready
      // await router.isReady();
      app.use(Antd).mount(
        container ? container.querySelector('#sub-app') : document.getElementById('app')
      )
    }
    
    // bootstrap()
    // 判断是否是乾坤环境下
    if (!qiankunWindow.__POWERED_BY_QIANKUN__) {
      bootstrap({})
      // app.use(Antd).mount('#app')
    } else {
      renderWithQiankun({
        mount(props) {
          console.log('--mount');
          bootstrap(props)
        },
        bootstrap() {
          console.log('--bootstrap');
        },
        update() {
          console.log('--update');
        },
        unmount() {
          console.log('--unmount');
          app?.unmount();
        }
      })
    }
    
    

    4、修改路由地址

    //文件地址  src/router/index.ts
    // app router
    // 创建一个可以被 Vue 应用程序使用的路由实例
    export const router = createRouter({
      // 创建一个 hash 历史记录。
      history: createWebHashHistory(
        qiankunWindow.__POWERED_BY_QIANKUN__ ? '/sub-app' : import.meta.env.VITE_PUBLIC_PATH),
      // 应该添加到路由的初始路由列表。
      routes: basicRoutes as unknown as RouteRecordRaw[],
      // 是否应该禁止尾部斜杠。默认为假
      strict: true,
      scrollBehavior: () => ({ left: 0, top: 0 }),
    })
    

    5、vite.config.js 修改

    import type { UserConfig, ConfigEnv } from 'vite'
    import pkg from './package.json'
    import dayjs from 'dayjs'
    import { loadEnv } from 'vite'
    import { resolve } from 'path'
    import { generateModifyVars } from './build/generate/generateModifyVars'
    import { createProxy } from './build/vite/proxy'
    import { wrapperEnv } from './build/utils'
    import { createVitePlugins } from './build/vite/plugin'
    import { OUTPUT_DIR } from './build/constant'
    
    function pathResolve(dir: string) {
      return resolve(process.cwd(), '.', dir)
    }
    
    const { dependencies, devDependencies, name, version } = pkg
    const __APP_INFO__ = {
      pkg: { dependencies, devDependencies, name, version },
      lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    }
    
    export default ({ command, mode }: ConfigEnv): UserConfig => {
      const root = process.cwd()
    
      const env = loadEnv(mode, root)
    
      // The boolean type read by loadEnv is a string. This function can be converted to boolean type
      const viteEnv = wrapperEnv(env)
    
      const { VITE_PORT, VITE_PUBLIC_PATH, VITE_PROXY, VITE_DROP_CONSOLE } = viteEnv
    
      const isBuild = command === 'build'
    
      return {
        base: VITE_PUBLIC_PATH,
        root,
        resolve: {
          alias: [
            {
              find: 'vue-i18n',
              replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
            },
            // /@/xxxx => src/xxxx
            {
              find: /\/@\//,
              replacement: pathResolve('src') + '/',
            },
            // /#/xxxx => types/xxxx
            {
              find: /\/#\//,
              replacement: pathResolve('types') + '/',
            },
          ],
        },
        server: {
          https: false,
          // Listening on all local IPs
          host: true,
          origin: 'http://localhost:3100',
          headers: { 'Access-Control-Allow-Origin': '*', },// 主应用获取子应用时跨域响应头
          port: VITE_PORT,
          // Load proxy configuration from .env
          proxy: createProxy(VITE_PROXY),
        },
        esbuild: {
          pure: VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
        },
        build: {
          target: 'es2020',
          cssTarget: 'chrome80',
          outDir: OUTPUT_DIR,
          // minify: 'terser',
          /**
           * 当 minify=“minify:'terser'” 解开注释
           * Uncomment when minify="minify:'terser'"
           */
          // terserOptions: {
          //   compress: {
          //     keep_infinity: true,
          //     drop_console: VITE_DROP_CONSOLE,
          //   },
          // },
          // Turning off brotliSize display can slightly reduce packaging time
          brotliSize: false,
          chunkSizeWarningLimit: 2000,
        },
        define: {
          // setting vue-i18-next
          // Suppress warning
          __INTLIFY_PROD_DEVTOOLS__: false,
          __APP_INFO__: JSON.stringify(__APP_INFO__),
          __COLOR_PLUGIN_OUTPUT_FILE_NAME__: undefined,
          __PROD__: true,
          __COLOR_PLUGIN_OPTIONS__: {},
        },
    
        css: {
          preprocessorOptions: {
            less: {
              modifyVars: generateModifyVars(),
              javascriptEnabled: true,
            },
          },
        },
    
        // The vite plugin used by the project. The quantity is large, so it is separately extracted and managed
        plugins: createVitePlugins(viteEnv, isBuild),
    
        optimizeDeps: {
          // @iconify/iconify: The dependency is dynamically and virtually loaded by @purge-icons/generated, so it needs to be specified explicitly
          esbuildOptions: {
            target: 'es2020',
          },
          include: [
            '@vue/runtime-core',
            '@vue/shared',
            '@iconify/iconify',
            'ant-design-vue/es/locale/zh_CN',
            'ant-design-vue/es/locale/en_US',
          ],
        },
      }
    }
    
    

    6、目前运行报错页面

    设想的解决方案:

    • 1、注释掉该插件的引入,发现不报错,但是页面不会跳转了(实际上这个应该进入登录页的)


    相关文章

      网友评论

          本文标题:vben-admin 当作乾坤子应用开发折腾

          本文链接:https://www.haomeiwen.com/subject/xgkmwdtx.html