2

Does it change anything in term of weight or optimization between thoose 2 imports in typescript ?

import { initializeApp } from "firebase-admin/app";
import { Messaging } from "firebase-admin/messaging";

and

import { initializeApp, Messaging } from "firebase-admin";
lemonpear
  • 58
  • 5
  • Is it a general import question or specific to firebase? Not sure about firebase but if it's general, then it may or may not have impact on memory, performance and other side effects. It will depend on what else the entry module exports, the co-dependencies between the modules of the imported package, what is being used for building typescript and/or bundling the javascript and how they are configured. – danielv Feb 07 '23 at 12:24

1 Answers1

2

Oh, I followed this question because I wanted to see the answers and none came, so let me try:

The Javascript (and in turn Typescript) environment keeps changing rapidly, so it is hard to guess the shelf life of any answer, but in 2023, it depends on what kind of module you are importing (and subsequently on your bundler).

The process of removing unused code from a library when bundling is referred to as "tree shaking", apparently this was coined by Rollup. Tree shaking is supported by ES2015 modules (esm), but not CommonJS (cjs) modules. Modern bundlers can utilize this capability (i.e. Rollup does it and so does Webpack), meaning that if you import an ESM library, your bundled code will only contain the part of the code you actually use. But if it is a CommonJS module, you always get the whole thing in your bundle.

So: If the imported library is an ES module, it does not matter which import statement you use. If it is a CommonJS module, a selective import will reduce bundle size (if you don't use the whole library).

Detecting which kind of module you are dealing with can be a bit cumbersome. But if you look around, there is a good chance there is a plugin for your IDE that can help you figure it out. At least for Webpack, I know there are tools that let you inspect the bundle and see which libraries are included and how much space they take up, which gives you a good indication.

Note that this applies to Typescript as well, as the imported code is usually Javascript with additional TS bindings.

In the current situation, with several module systems next to each other and several very different and very evolved bundling tools, things change quickly and it is hard to keep an overview. Please let me know if and where I am wrong.

Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
  • Thank you very much for this clear answer. And you are right, after I inspect the package after being zipped by rollup, the code is the same in the 2 cases. Unfortunately, I have to upgrade my common js code into es module. – lemonpear Feb 07 '23 at 23:52