Version: 5.x

single-spa-vue

single-spa-vue is a helper library that helps implement single-spa registered application lifecycle functions (bootstrap, mount and unmount) for use with Vue.js. Check out the single-spa-vue github.

For a full example, see vue-microfrontends.

https://coexisting-vue-microfrontends.surge.sh

The vue-cli-plugin-single-spa will get everything set up.

  1. vue add single-spa

The CLI Plugin does the following for you:

  1. Modify your webpack config so that your project works as a single-spa application or parcel.
  2. Install single-spa-vue.
  3. Modify your main.js or main.ts file so that your project works as a single-spa application or parcel.
  4. Add a set-public-path.js that will use systemjs-webpack-interop in order to set the public path of your application.
  1. npm install --save single-spa-vue

Alternatively, you can use single-spa-vue by adding <script src="https://unpkg.com/single-spa-vue"></script> to your HTML file and accessing the singleSpaVue global variable.

Install systemjs-webpack-interop if you have not already done so.

npm install systemjs-webpack-interop -S

Create a file at the same level as your main.js/ts called set-public-path.js

  1. import { setPublicPath } from 'systemjs-webpack-interop';
  2. setPublicPath('appName');

Note that if you are using the Vue CLI Plugin, your main.ts or main.js file will be updated with this code automatically and the set-public-path.js file will automatically be created with the app name being your package.json’s name property.

If you want to deal with your Vue instance, you can modify the mount method by following this. mount method will return Promise with Vue instance after v1.6.0.

  1. const vueLifecycles = singleSpaVue({...})
  2. export const mount = props => vueLifecycles.mount(props).then(instance => {
  3. // do what you want with the Vue instance
  4. ...
  5. })

For Vue 2, change your application’s entry file to be the following:

  1. import './set-public-path';
  2. import Vue from 'vue';
  3. import App from './App.vue';
  4. import router from './router';
  5. import singleSpaVue from 'single-spa-vue';
  6. const vueLifecycles = singleSpaVue({
  7. Vue,
  8. appOptions: {
  9. render(h) {
  10. return h(App);
  11. },
  12. router,
  13. },
  14. });
  15. export const bootstrap = vueLifecycles.bootstrap;
  16. export const mount = vueLifecycles.mount;
  17. export const unmount = vueLifecycles.unmount;

⚠️ Vue 3’s router only works properly with single-spa’s urlRerouteOnly set to true! In single-spa@<=5, the default value for urlRerouteOnly is false. So make sure to update your root config to set it to true. Also, upgrade to vue-cli-plugin-single-spa@>=3 in order to ensure standalone mode sets urlRerouteOnly to true. Github discussion

For Vue 3, change your application’s entry file to be the following:

  1. import './set-public-path';
  2. import { h, createApp } from 'vue';
  3. import singleSpaVue from '../lib/single-spa-vue.js';
  4. import router from './router';
  5. import App from './App.vue';
  6. const vueLifecycles = singleSpaVue({
  7. createApp,
  8. appOptions: {
  9. render() {
  10. return h(App, {
  11. // single-spa props are available on the "this" object. Forward them to your component as needed.
  12. // https://single-spa.js.org/docs/building-applications#lifecycle-props
  13. name: this.name,
  14. mountParcel: this.mountParcel,
  15. singleSpa: this.singleSpa,
  16. });
  17. },
  18. },
  19. handleInstance: (app) => {
  20. app.use(router);
  21. }
  22. });
  23. export const bootstrap = vueLifecycles.bootstrap;
  24. export const mount = vueLifecycles.mount;
  25. export const unmount = vueLifecycles.unmount;

Single-spa custom props can be passed to your root component like so:

  1. // main.js
  2. const vueLifecycles = singleSpaVue({
  3. Vue,
  4. appOptions: {
  5. render(h) {
  6. return h(App, {
  7. mountParcel: this.mountParcel,
  8. otherProp: this.otherProp,
  9. });
  10. },
  11. router,
  12. },
  13. });
  1. // App.vue
  2. <template>
  3. <button>{{ otherProp }}</button>
  4. </template>
  5. <script>
  6. export default {
  7. props: ['mountParcel', 'otherProp'],
  8. }
  9. </script>

For performance, it is best to share a single version and instance of Vue, Vue Router, and other large libraries.

To do this, add your shared dependencies as webpack externals. Then you use an in-browser module loader such as systemjs to provide those shared dependencies to each of the single-spa applications. Adding vue and other libraries to your import map. For an example import map that is doing this, checkout coexisting-vue-microfrontends’ index.html file.

Sharing a single instance of Vue and other common libraries is highly recommended. See the recommended setup for single-spa for more details on why.

  1. // vue.config.js
  2. module.exports = {
  3. chainWebpack: config => {
  4. config.externals(['vue', 'vue-router']);
  5. },
  6. };
  1. // webpack.config.js
  2. module.exports = {
  3. externals: ['vue', 'vue-router'],
  4. };

All options are passed to single-spa-vue via the opts parameter when calling singleSpaVue(opts). The following options are available:

  • Vue: (required) The main Vue object, which is generally either exposed onto the window or is available via require('vue') import Vue from 'vue'.
  • appOptions: (required) An object or async function which will be used to instantiate your Vue.js application. appOptions will pass directly through to new Vue(appOptions). Note that if you do not provide an el to appOptions, that a div will be created and appended to the DOM as a default container for your Vue application. When appOptions is an async function, it receives the single-spa props as an argument (as of single-spa-vue@2.4.0).
  • loadRootComponent: (optional and replaces appOptions.render) A promise that resolves with your root component. This is useful for lazy loading.
  • handleInstance: (optional) A method can be used to handle Vue instance. Vue 3 brings new instance API, and you can access the app instance from this, like handleInstance: (app, props) => app.use(router). For Vue 2 users, a Vue instance can be accessed. The handleInstance(app, props) function receives the instance as its first argument, and single-spa props as its second argument. If handleInstance returns a promise, single-spa-vue will wait to resolve the app / parcel’s mount lifecycle until the handleInstance promise resolves.
  • replaceMode: (optional, defaults to false) A boolean that determines whether your root Vue component will entirely replace the container element it’s mounted to. The Vue library always replaces, so to implement replaceMode: false a temporary <div class="single-spa-container"> element is created inside of the container, so that Vue replaces that element rather than the container. Introduced in single-spa-vue@2.3.0.

To configure which dom element the single-spa application is mounted to, use appOptions.el:

  1. const vueLifecycles = singleSpaVue({
  2. Vue,
  3. appOptions: {
  4. render: h => h(App),
  5. el: '#a-special-container',
  6. },
  7. });

To configure options asynchronously return a promise from appOptions function:

  1. const vueLifecycles = singleSpaVue({
  2. Vue,
  3. async appOptions() {
  4. return {
  5. router: await routerFactory(),
  6. render: h => h(App)
  7. }
  8. },
  9. });

single-spa custom props are available in the render() function in your main file. They can be passed as custom props to your App component.

  1. const vueLifecycles = singleSpaVue({
  2. Vue,
  3. appOptions: {
  4. render(h) {
  5. return h(App, {
  6. props: {
  7. // single-spa props are available on the "this" object. Forward them to your component as needed.
  8. // https://single-spa.js.org/docs/building-applications#lifecycle-props
  9. name: this.name,
  10. mountParcel: this.mountParcel,
  11. singleSpa: this.singleSpa,
  12. },
  13. });
  14. },
  15. },
  16. });

A parcel config is an object that represents a component implemented in Vue, React, Angular, or any other framework.

To create a VueJS single-spa parcel config object, simply omit the el option from your appOptions, since the dom element will be specified by the user of the Parcel. Every other option should be provided exactly the same as in the example above.

  1. const parcelConfig = singleSpaVue({...});

To render a parcel config object in Vue, you can use single-spa-vue’s Parcel component:

  1. <template>
  2. <Parcel
  3. v-on:parcelMounted="parcelMounted()"
  4. v-on:parcelUpdated="parcelUpdated()"
  5. :config="parcelConfig"
  6. :mountParcel="mountParcel"
  7. :wrapWith="wrapWith"
  8. :wrapClass="wrapClass"
  9. :wrapStyle="wrapStyle"
  10. :parcelProps="getParcelProps()"
  11. />
  12. </template>
  13. <script>
  14. // For old versions of webpack
  15. import Parcel from 'single-spa-vue/dist/esm/parcel'
  16. // For new versions of webpack
  17. import Parcel from 'single-spa-vue/parcel'
  18. import { mountRootParcel } from 'single-spa'
  19. export default {
  20. components: {
  21. Parcel
  22. },
  23. data() {
  24. return {
  25. /*
  26. parcelConfig (object, required)
  27. The parcelConfig is an object, or a promise that resolves with a parcel config object.
  28. The object can originate from within the current project, or from a different
  29. microfrontend via cross microfrontend imports. It can represent a Vue component,
  30. or a React / Angular component.
  31. https://single-spa.js.org/docs/recommended-setup#cross-microfrontend-imports
  32. Vanilla js object:
  33. parcelConfig: {
  34. async mount(props) {},
  35. async unmount(props) {}
  36. }
  37. // React component
  38. parcelConfig: singleSpaReact({...})
  39. // cross microfrontend import is shown below
  40. */
  41. parcelConfig: System.import('@org/other-microfrontend').then(ns => ns.Widget),
  42. /*
  43. mountParcel (function, required)
  44. The mountParcel function can be either the current Vue application's mountParcel prop or
  45. the globally available mountRootParcel function. More info at
  46. http://localhost:3000/docs/parcels-api#mountparcel
  47. */
  48. mountParcel: mountRootParcel,
  49. /*
  50. wrapWith (string, optional)
  51. The wrapWith string determines what kind of dom element will be provided to the parcel.
  52. Defaults to 'div'
  53. */
  54. wrapWith: 'div'
  55. /*
  56. wrapClass (string, optional)
  57. The wrapClass string is applied to as the CSS class for the dom element that is provided to the parcel
  58. */
  59. wrapClass: "bg-red"
  60. /*
  61. wrapStyle (object, optional)
  62. The wrapStyle object is applied to the dom element container for the parcel as CSS styles
  63. */
  64. wrapStyle: {
  65. outline: '1px solid red'
  66. },
  67. }
  68. },
  69. methods: {
  70. // These are the props passed into the parcel
  71. getParcelProps() {
  72. return {
  73. text: `Hello world`
  74. }
  75. },
  76. // Parcels mount asynchronously, so this will be called once the parcel finishes mounting
  77. parcelMounted() {
  78. console.log("parcel mounted");
  79. },
  80. parcelUpdated() {
  81. console.log("parcel updated");
  82. }
  83. }
  84. }
  85. </script>

vue-cli-plugin-single-spa sets the webpack public path via SystemJSPublicPathWebpackPlugin. By default, the public path is set to match the following output directory structure:

  1. dist/
  2. js/
  3. app.js
  4. css/
  5. main.css

With this directory structure (which is the Vue CLI default), the public path should not include the js folder. This is accomplished by setting rootDirectoryLevel to be 2. If this doesn’t match your directory structure or setup, you can change the rootDirectoryLevel with the following code in your vue.config.js or webpack.config.js:

  1. // vue.config.js
  2. module.exports = {
  3. chainWebpack(config) {
  4. config.plugin('SystemJSPublicPathWebpackPlugin').tap((args) => {
  5. args[0].rootDirectoryLevel = 1;
  6. return args;
  7. });
  8. }
  9. }

Vue - 图1Edit this page