qiankun 主项目和子项目都是 vue2,部署在同一台服务器上,nginx 配置

1、主项目配置

        1.1 micro.vue 组件

<template>
  <div id="container-sub-app"></div>
</template>

<script>
import { loadMicroApp } from 'qiankun';
import actions from '@/utils/actions.js';

export default {
  name: 'microApp',
  mixins: [actions],
  data() {
    return {
      microApp: null
    };
  },
  mounted() {
    const getMicroInfo = this.getMicroInfo();
    this.microApp = loadMicroApp(getMicroInfo, {
      singular: true
    });
  },
  beforeDestroy() {
    console.log('beforeDestroy...');
    this.microApp.unmount();
  },
  methods: {
    // 手动加载微应用
    getMicroInfo() {
      const appIdentifying = this.$route.path.split('/')[1];
      let data = {};
      const href = window.location.host;
      for (let i = 0; i < document.subApps.length; i++) {
        const element = document.subApps[i];
        if (element.activeRule.includes(appIdentifying)) {
          if (typeof element.entry !== 'string') {
            data = {
              ...element,
              entry: element.entry[href]
                ? element.entry[href]
                : Object.values(element.entry)[0]
            };
          } else {
            data = { ...element };
          }
          data.props = {
            token: {
              userInfo: {
                userName: '小明',
                userId: '123',
                date: new Date().toLocaleString()
              }
            }
          };
          data.activeRule = [appIdentifying];
          break;
        }
      }
      return data;
    }
  }
};
</script>

   1.2 index.html 引入配置

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
    />
    <link rel="icon" href="<%= BASE_URL %>favicon.ico" />
    <script src="<%= BASE_URL %>register-apps.js"></script>
    <title><%= webpackConfig.name %></title>
  </head>
  <body>
    <noscript>
      <strong
        >We're sorry but <%= webpackConfig.name %> doesn't work properly without
        JavaScript enabled. Please enable it to continue.</strong
      >
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

        1.3 register-apps.js 配置

document.subApps = [
  {
    name: 'besFront',
    //entry: '//localhost:8086/bes-front/',// 本地调试
    entry: '/bes-front/',// 部署到服务器
    container: '#container-sub-app',
    activeRule: '/bes-front'
  }
];

        1.4 路由配置

import Vue from 'vue';
import Router from 'vue-router';

Vue.use(Router);

import Layout from '@/layout';
import MicroApp from '@/components/microApp';

export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },
  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },
  {
    path: '/dashboard',
    component: Layout,
    redirect: '/dashboard/index',
    children: [
      {
        path: 'index',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/index'),
        meta: { title: 'Dashboard', icon: 'dashboard' }
      }
    ]
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: 'bes-front',
        component: MicroApp// 重点,用于加载子项目
      }
    ]
  }
  // 404 page must be placed at the end !!!
  // { path: '*', redirect: '/404', hidden: true }
];

const createRouter = () =>
  new Router({
    mode: 'history', // require service support
    base: '',
    scrollBehavior: () => ({ y: 0 }),
    routes: constantRoutes
  });

const router = createRouter();

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // reset router
}

export default router;

2、子项目配置

        2.1 main.js 配置

// 动态设置 publicPath
import './public-path';
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.config.productionTip = false;
Vue.use(ElementUI);

let instance = null;
function render(props = {}) {
  console.log('子应用 render props::', props, 'instance====', instance);
  // sessionStorage.setItem('userInfo', JSON.stringify(props.token.userInfo));
  const { container } = props;

  instance = new Vue({
    router,
    store,
    render: (h) => h(App)
  }).$mount(container ? container.querySelector('#app') : '#app');
}

// 独立运行时
/* eslint-disable */
if (!window.__POWERED_BY_QIANKUN__) {
  render();
}

export async function bootstrap() {
  console.log('子应用 bootstrap ===========================');
}

let initialState = null;
export async function mount(props) {
  console.log('子应用 mount props ===============', props);
  sessionStorage.setItem('userInfo', JSON.stringify(props.token.userInfo));
  props.onGlobalStateChange((state, prev) => {
    // state: 变更后的状态; prev 变更前的状态
    console.log('子应用获取共享数据 state::', state, 'prev::', prev);
    // 接收主应用中的共享数据 并将其设置为全局变量
    Vue.prototype.$initialState = state;
  });
  props.setGlobalState({
    initialState:
      '子应用中修改主应用中的全局变量,实现住应用子应用间数据的双向双向通信'
  });

  render(props);
}
export async function unmount() {
  console.log('子应用 unmount==========');
  instance.$destroy();
  instance.$el.innerHTML = '';
  instance = null;
}

        2.2  public-path 文件

if (window.__POWERED_BY_QIANKUN__) {
  /* eslint-disable @typescript-eslint/camelcase */
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}

        2.3 vue.config.js 配置

'use strict';
const path = require('path');
const defaultSettings = require('./src/settings.js');
const proxyTable = require('./proxyTable');

function resolve(dir) {
  return path.join(__dirname, dir);
}

const name = defaultSettings.title || 'vue Admin Template'; // page title

// If your port is set to 80,
    // use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528; // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: '/bes-front/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    headers:{
        "Access-Control-Allow-Origin": "*",
    },
    port: port,
    open: true,
    proxy: proxyTable,
    overlay: {
      warnings: false,
      errors: true
    }
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    name: name,
    output:{
        library: `besFront`,// 主应用
        libraryTarget: "umd",// 把微应用打包成 umd 库格式
        jsonpFunction: `webpackJsonp_besFront`,// webpack5 需要把 jsonpFunction 替换成 chunkLoadingGlobal
    },
    resolve: {
      alias: {
        '@': resolve('src')
      }
    }
  },
  chainWebpack(config) {
    // it can improve the speed of the first screen, it is recommended to turn on preload
    config.plugin('preload').tap(() => [
      {
        rel: 'preload',
        // to ignore runtime.js
        // https://github.com/vuejs/vue-cli/blob/dev/packages/%40vue/cli-service/lib/config/app.js#L171
        fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
        include: 'initial'
      }
    ]);

    // when there are many pages, it will cause too many meaningless requests
    config.plugins.delete('prefetch');

    // set svg-sprite-loader
    config.module.rule('svg').exclude.add(resolve('src/icons')).end();
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end();

    config.when(process.env.NODE_ENV !== 'development', (config) => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end();
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      });
      // https:// webpack.js.org/configuration/optimization/#optimizationruntimechunk
      config.optimization.runtimeChunk('single');
    });
  }
};

3、主项目和子项目部署在同一台服务器上,其中主应用路由使用history模式,子应用路由使用hash模式,nginx 的配置如下:

locatoin / {
    root /opt/parent;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
}

location /bes-front/ {
    root /opt/parent;
    index index.html index.htm;
    try_files $uri $uri. /index.html;
}

注:使用的下面这种部署方式,主应用代码放在parent目录下,子应用代码放在parent目录下面,其他,子应用的目录应该代码中的名称保持一致,在本示例当中,子应用使用的是bes-front

官网参考链接: 入门教程 - qiankun

4、总结

在部署主应用和子应用时,遇到主应用转发到子应用时,静态资源无法访问的问题,重点是查看子应用publicPath这个配置,这个是静态文件的访问前缀,如果部署到服务器上,子应用的静态资源无法访问到,可以看一下服务器访问的静态资源的前缀是否和代码中配置的一致。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/890616.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

python+appium+雷电模拟器安卓自动化及踩坑

一、环境安装 环境&#xff1a;window11 1.1 安装Android SDK AndroidDevTools - Android开发工具 Android SDK下载 Android Studio下载 Gradle下载 SDK Tools下载 这里面任选一个就可以&#xff0c;最终下载完主要要安装操作安卓的工具adb&#xff0c;安装这个步骤的前提是要…

防火墙的三种工作模式:路由模式、透明模式(网桥)、混合模式

防火墙作为网络安全的核心设备之一&#xff0c;扮演着至关重要的角色。它不仅能够有效防御外部网络的攻击&#xff0c;还能保护内部网络的安全。在如今复杂多样的网络环境下&#xff0c;防火墙的部署和工作模式直接影响着网络安全策略的实施效果。防火墙通常可以工作在三种模式…

如何成为 Rust 核心贡献者?Rust 开发的核​​心是什么?Rust 重要技术专家揭秘

10 月 17 - 18日&#xff0c;由 GOSIM 开源创新汇主办、CSDN 承办的 GOSIM CHINA 2024 将在北京盛大启幕。作为 GOSIM 开源年度大会的第三届盛会&#xff0c;本次活动邀请了 60 多位国际开源专家&#xff0c;汇聚了来自全球百余家顶尖科技企业、知名高校及开源社区的技术大咖、…

衡石分析平台系统-分析人员手册

应用创建​ 用户可以通过多种方式创建应用&#xff0c;不同场景下应用创建方法不同。 新建空白应用​ 新建空白应用是新建一个空的应用&#xff0c;应用中没有数据集和仪表盘。 点击应用创作页面右上方的新建应用&#xff0c;新建空白的分析应用和查询应用。 新建的空白应用…

汽车宣传动画渲染怎么做?云渲染加速汽车动画渲染

在汽车行业&#xff0c;宣传动画已成为展示新车型和技术创新的重要工具。高质量的渲染不仅能够吸引观众的眼球&#xff0c;还能有效传达汽车的性能和美学。随着技术的发展&#xff0c;云渲染技术为汽车宣传动画的渲染提供了新的可能性&#xff0c;大大提高了渲染效率和质量。 第…

区块链-智能合约Solidity编程

文章目录 一、ubuntu安装二、FISCO BCOS安装五、 WeBASE安装5.1 WeBASE简介5.2 节点前置服务搭建5.3 调用HelloWorld合约 七、Solidity极简入门7.1. 值类型7.2. 变量数据存储和作用域7.3. 函数7.4 控制流7.5 数组&映射7.6 结构体7.7 修饰符7.8 事件7.9 面向对象7.10 抽象合…

与鸿蒙同行,Java Solon v3.0 正式发布(向下兼容)

与 HarmonyOS NEXT 10月8日公测同行。Solon &#xff08;开放原子开源基金会&#xff0c;孵化项目&#xff09; v3.0 正式发布&#xff0c; 且将在 2025 年启动华为编程语言 “仓颉” 版开发&#xff08;届时会有 Solon-Java 和 Solon-CJ 两大版本&#xff09;。本次大版本更新…

免费送源码:Java+Springboot+MySQL 水环境检测系统的设计与实现 计算机毕业设计原创定制

摘 要 在我国,水源的污染是不可忽视的问题。对于水质监测进行数据的采集工作,目前主要通过人工实现。因此,部分地区的采集工作,实施起来难度很大,比如恶劣环境和偏僻山区等地。所以,目前对于水质监测的研究,主导方向是建立更加高效完善,智能化的水质监测系统。近几年,无线传感器…

【C++贪心 DFS】2673. 使二叉树所有路径值相等的最小代价|1917

本文涉及知识点 C贪心 反证法 决策包容性 CDFS LeetCode2673. 使二叉树所有路径值相等的最小代价 给你一个整数 n 表示一棵 满二叉树 里面节点的数目&#xff0c;节点编号从 1 到 n 。根节点编号为 1 &#xff0c;树中每个非叶子节点 i 都有两个孩子&#xff0c;分别是左孩子…

java数据库操作-cnblog

创建lib目录&#xff0c;填入jar包 选择 libraries添加lib目录 package nb;import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException;public class JDBCtest {private static final String url "jdbc:mysql://localhost:3306/test?c…

SAP学习笔记 - 豆知识12 - 自动批量更新会计期间

网上买的那种SAP学习虚拟机&#xff0c;一般都是古老的会计期间。 要想更新到现在的日期&#xff0c;需要MMRV/MMPV挨月更新&#xff0c;感叹SAP挺会折磨人。 之前也做过多次探索&#xff0c;基本都没太成功。 SAP MM学习笔记 - 豆知识10 - OMSY 初期化会计期间&#xff0c;…

深入探索Spring Cloud Gateway:微服务网关的最佳实践

优质博文&#xff1a;IT-BLOG-CN Spring Cloud Gateway作为Spring Cloud框架的第二代网关&#xff0c;在功能上要比Zuul更加的强大&#xff0c;性能也更好。随着Spring Cloud的版本迭代&#xff0c;Spring Cloud官方有打算弃用Zuul的意思。在笔者调用了Spring Cloud Gateway的…

使用 Visual Studio Installer Projects 打包 C# WinForms 程序的教程

前言 在开发完成一个 C# WinForms 程序后&#xff0c;打包成安装程序是发布和分发软件的重要步骤之一。通过使用 Visual Studio Installer Projects&#xff0c; 可以轻松创建一个 .exe 或 .msi 格式的安装包供用户安装。本文将详细介绍如何使用 Visual Studio Installer Proj…

网络资源模板--Android Studio 实现简易记事本App

目录 一、项目演示 二、项目测试环境 三、项目详情 四、完整的项目源码 一、项目演示 网络资源模板--基于Android studio 实现的简易记事本App 二、项目测试环境 三、项目详情 首页 创建一个空的笔记本列表 mNotebookList。使用该列表和指定的布局资源 item_notebook 创建…

苹果最新论文:LLM只是复杂的模式匹配 而不是真正的逻辑推理

大语言模型真的可以推理吗&#xff1f;LLM 都是“参数匹配大师”&#xff1f;苹果研究员质疑 LLM 推理能力&#xff0c;称其“不堪一击”&#xff01;苹果的研究员 Mehrdad Farajtabar 等人最近发表了一篇论文&#xff0c;对大型语言模型 &#xff08;LLM&#xff09; 的推理能…

2.实现第一个three.js程序

实现第一个three.js程序 1.目标效果 注意一个版本问题&#xff1a;three.js版本并不稳定&#xff0c;几乎每个月都会更新一个小版本&#xff0c;尽可能使用固定版本进行开发&#xff0c;事实上我们入门的话&#xff0c;只掌握其中一个版本即可&#xff0c;如果使用新版本&…

文件与fd

访问文件前&#xff0c;为什么必须要打开文件&#xff1f;/ 打开文件的实质 访问文件前&#xff0c;都必须先打开它&#xff0c; 如fopen 访问文件时&#xff0c;是进程在访问 所以文件必须加载到内存中 我们要访问文件时&#xff0c;一定要通过内存访问 文件没有被打开时&am…

多线程(三):线程等待获取线程引用线程休眠线程状态

目录 1、等待一个线程&#xff1a;join 1.1 join() 1.2 join(long millis)——"超时时间" 1.3 join(long millis&#xff0c;int nanos) 2、获取当前线程的引用&#xff1a;currentThread 3、休眠当前进程&#xff1a;sleep 3.1 实际休眠时间 3.2 sleep的特殊…

SQLI LABS | SQLI LABS 靶场初识

关注这个靶场的其它相关笔记&#xff1a;SQLI LABS —— 靶场笔记合集-CSDN博客 0x01&#xff1a;SQLI LABS 靶场简介 SQLi-Labs 靶场是一个专门用于学习和测试 SQL 注入漏洞的开源靶场&#xff0c;该靶场提供了多个具有不同漏洞类型和难度级别的 Web 应用程序的环境。这些应用…

C++ | Leetcode C++题解之第477题汉明距离总和

题目&#xff1a; 题解&#xff1a; class Solution { public:int totalHammingDistance(vector<int> &nums) {int ans 0, n nums.size();for (int i 0; i < 30; i) {int c 0;for (int val : nums) {c (val >> i) & 1;}ans c * (n - c);}return …