【问题标题】:How to import firebase and split its services into multiple split chunks using webpack?如何使用 webpack 导入 firebase 并将其服务拆分为多个拆分块?
【发布时间】:2020-02-17 17:01:52
【问题描述】:

我现在正在做:

firebase.js

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';
import 'firebase/storage';

const config = {
  apiKey: process.env.FIREBASE_APP_API_KEY,
  authDomain: process.env.FIREBASE_APP_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_APP_DATABASE_URL,
  projectId: process.env.FIREBASE_APP_PROJECT_ID,
  storageBucket: process.env.FIREBASE_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_APP_MESSAGING_SENDER_ID,
  appId: process.env.FIREBASE_APP_ID,
};

firebase.initializeApp(config);

export default firebase;

webpack.config.js

optimization: {
  runtimeChunk: 'single',
  splitChunks: {
    chunks: 'all',
    maxInitialRequests: Infinity,
    minSize: 0,
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name(module) {
          const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
          return `npm.${packageName.replace('@', '')}`;
        },
      },
    },
  },
}

我从这篇文章中得到的 webpack 部分:

https://medium.com/hackernoon/the-100-correct-way-to-split-your-chunks-with-webpack-f8a9df5b7758

这导致了这个667kb的小 JS文件(这是生产版本):

问题

我可以通过其他方式导入它,以便最终得到更小的块吗?

例如:

import firebase from 'firebase/app';
import auth from 'firebase/auth';
import firestore from 'firebase/firestore';
import functions from 'firebase/functions';
import storage from 'firebase/storage';

但我不知道我要如何处理这些“额外的对象”,因为我需要和使用的唯一对象是我从 firebase/app 获得的 firebase 对象

另外,如果我像这样导入它们并且不使用对象,Webpack 不会将它们解释为“死代码”并摇树吗?

这样做的正确方法是什么?

【问题讨论】:

    标签: javascript firebase webpack webpack-splitchunks


    【解决方案1】:

    Firebase 将这些导入直接加载到 firebase 对象中,无法从那里对其进行 treeshake。你可以做的是选择性地通过动态导入加载这些,然后 webpack 将负责对这些进行代码分割。如果未导入,这些实例不会添加到 firebase 对象中,因此您可以通过简单的 if 检查来加载它们。

    
    export async function getFirestoreInstance() {
        if (!firebase.firestore) {
            await import('firebase/firestore');
        }
    
        return firebase.firestore();
    }
    
    

    例如,当您需要使用 Firestore 时,只需调用 getFirestoreInstance

    async function doSomethingWithFirestore(){
       try {
          const firestore = await getFirestoreInstance();
          firestore.collection("foo") // do something with firestore
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-05
      • 2016-11-26
      • 2019-10-24
      • 2021-02-26
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多