簡體   English   中英

如何使用 webpack 導入 firebase 並將其服務拆分為多個拆分塊?

[英]How to import firebase and split its services into multiple split chunks using webpack?

現在我正在做:

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 不會將它們解釋為“死代碼”並搖晃它們嗎?

這樣做的正確方法是什么?

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
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM