How do I share Vuex state management between host and remote using the webpack5 module federation function?

24 Views Asked by At

There is project A, which is the host, and project B, which is remote. (This is a vue-based project)

Each project manages state with Vuex. How should I manage state between projects? After exposing the store management file in project b, when importing and using it in project a, an error occurs as shown below.

Uncaught TypeError: Cannot read properties of undefined (reading 'call') - bootstrap

I am curious as to whether it is correct to simply expose the store file and then import and use it from the file that defines the store in the host.

project b webpack.config.js

new ModuleFederationPlugin({
      name: 'app2',
      filename: 'remoteEntry.js',
      exposes: {
        './template': '@/store/template.js',
      },

template.js

const template = {
  namespaced: true,
  // state
  state: { template: {}, validator: {} },
  // mutations
  mutations: {
    init(state, data) {
      state.template = Object.assign({}, data);
    },
    setValidator(state, object) {
      state.validator = object;
    },
    update(state, data) {
      state.template = Object.assign({}, state.template, data);
    },
    clear(state) {
      state = Object.assign(state, {});
    }
  },
  getters: {
    templateData: state => {
      return state.template;
    }
  },
  // actions
  actions: {
    setTemplate({ commit, state }, templateData) {
      commit('init', templateData);
    },
    setValidator({ commit }, object) {
      commit('setValidator', object);
    },
    update({ state, commit, rootState }, templateData) {
      commit('update', templateData);
    }
  },
  clear({ state, commit, rootState, dispatch }) {
    commit('clear');
  }
};

export default template;

project a wepback.config.js

new ModuleFederationPlugin({
      name: 'app1',
      filename: 'remoteEntry.js',
      remotes: {
        app2: `app2@${devConfig.EA_URL}/remoteEntry.js`,
      },

project a store/index.js

import template from 'app2/template';
export default new Vuex.Store({
  modules: { template },
});
0

There are 0 best solutions below