【问题标题】:Load a Package inside a Vuex Action only when it is dispatched仅在分派时在 Vuex 操作中加载包
【发布时间】:2019-10-03 20:07:21
【问题描述】:

我想导入一个包以在 Vuex Action 中使用它,但只有在调度 Action 时才能使用它以节省我的入口包大小。

我对解决方案的尝试:

export const actions = {
  async createNewBin(store, bin) {
    const firebase = require('firebase/app');
    require('firebase/firestore');

    const collectionRef = firebase.firestore().collection('bins');

    try {
      const docRef = await collectionRef.add(bin);
      return docRef;
    } catch (e) {
      return e;
    }
  }
}

firebase/firestore 在我的条目文件中,我不希望这样。

【问题讨论】:

  • 为什么不只导入firestore

标签: javascript vue.js vuex nuxt.js


【解决方案1】:

这应该可行。 https://webpack.js.org/guides/code-splitting/#dynamic-imports

export const actions = {
    async createNewBin(store, bin) {
        const { default: firebase } = await import(
            /* webpackChunkName: "firebase" */ 'firebase')

        // You may want code that checks if firebase is already initialized.
        // Unsure if initializing multiple times throws an error.
        firebase.initializeApp({
            // your init options
        });

        const collectionRef = firebase.firestore().collection('bins');

        try {
            const docRef = await collectionRef.add(bin);
            return docRef;
        } catch (e) {
            return e;
        }
    }
  }

【讨论】:

    【解决方案2】:

    您还可以在此处找到有关此方法的更多详细信息

    How and when (not) to use webpack for lazy loading?

    一般来说,解决方案可能像 Eric 用 async/await 回答

    const { default: firebase } = await import(/* webpackChunkName: "firebase" */ 'firebase')
    

    或者像这样使用 Promise

    if(iWantToLoadMyModule){
        import('myModule').then( myModule =>{
            // do something with myModule.default
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多