简体   繁体   中英

What is the best way to import es6 module?

In my mind i think this way is better and more performatic:

import stuff from 'library/stuff'

so i am not importing the whole library, i am importing just the module which should be faster

but when i am doing this with react-router-dom for example i get warning saying that i should do this instead:

import {Link } from 'react-router-dom'

otherwise i will get that warning

Warning: Please use `require("react-router-dom").Link` instead of `require("react-router-dom/Link")`. Support for the latter will be removed in the next major release.

which is counter-intuitive, so what is the better way to import es6 module the first or the second method??

import { Link } from 'react-router-dom' 

is the right way to do it. I don't think there will be much difference in the performance.

An import always loads the whole module, creates all the exported values, and resolves the imported bindings. It doesn't matter whether only one or all the exported bindings are used. It doesn't matter what syntax the import declaration is using.

for the more details you can check this link: https://alligator.io/js/modules-es6/

It depends on your environment,

// Import all from utils
import utilities from "utils";


// Import only com1 of the utilities
import { com1 } from "utils";
import com1 from "utils/com1";

In production builds

It's Tree Shaking ,Tree shaking is a term commonly used in the JavaScript context for dead-code elimination. In production builds, we can configure webpack to "shake" off exports from ES6 modules that weren't explicitly imported, making those production bundles smaller.

If you're using a bundler that supports tree-shaking you can safely use named imports and still get an optimised bundle size automatically but...

In development environment

files can contain the full library which can lead to slower startup times. then this one is faster:

//Faster
import com1 from "utils/com1";

than

import { com1 } from "utils";

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