简体   繁体   中英

import * vs import { specificName } in Typescript/ES6?

Declaration

declare module "MyModule" {

export function Foo() {...}
export function Bar() {...}

}

I just need Foo somewhere, how should I import it ?

import * as MyModule from "MyModule";

MyModule.Foo();

or

import {Foo} from "MyModule";
Foo()

Which one is better than another ? Are there any performance implications of importing all the exports in the first way?

Some references which I read before posting questions:

https://www.exratione.com/2015/12/es6-use-of-import-property-from-module-is-not-a-great-plan/

Importing only what is necessary to your code is, of course, good practice . Say someone writes some thousand-line code importing everything, and then you try to analyze it. Do you think you would easily know which functions used in your code are imported or which is not? Obviously it is dubious and bad practice .

With regards performance, I suppose not much affected.

The import {} from ... syntax makes stubbing and spying on functions very difficult and normally requires additional libraries such as rewire.js. The caveat is tree shaking doesn't work as well. I'm inclined to keep my util modules small and maybe only include 2-3 functions per module. That way I can use the import * as ... syntax for my modules and import {} ... when possible for third party modules. Thus minimising the need for tree shaking.

If you need to use only Foo , I think it's better to import just Foo . This makes your code clearer, because by looking at that import you can tell which elements of MyModule that code is using.

It doesn't affect performance, because either way you have to read/download the whole file.

Also, it doesn't matter which option you choose when using a bundler like Rollup.js―even if you import everything from MyModule , the bundle will include only things that you actually use in your code.

In case anyone is still looking for answers, i have shared my thoughts on this.

  • Let say you have a JSON file and you want to import the entire module as a variable then go with import * .
  • If you have a module with multiple exported methods (That can be 3rd party packages), then you should go with import {} approach.
  • Any default export should be imported as "import any name ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM