最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES6 Modules - 3 ways of importing files - Stack Overflow

programmeradmin10浏览0评论

Hello guys i have a little question about importing files into a single .js file.

Which way is better (best practice), what's the scenario that is used for:

  1. import './file;'

  2. import { something } from './file'

  3. import * as evertything from './file'

Because i see that 2 and 3 are the same thing but different syntax(maybe Syntactic Sugar).

Hello guys i have a little question about importing files into a single .js file.

Which way is better (best practice), what's the scenario that is used for:

  1. import './file;'

  2. import { something } from './file'

  3. import * as evertything from './file'

Because i see that 2 and 3 are the same thing but different syntax(maybe Syntactic Sugar).

Share Improve this question asked Jul 23, 2019 at 10:19 GrecdevGrecdev 9599 silver badges14 bronze badges 1
  • 1 There is no good practice, all of them do different things. In the first case, the whole file is loaded (NOT imported). In the second case, only exports.something is imported. In the third case, everything is imported under evertything, like if that was a namespace, so accessing something would be evertything.something. – briosheje Commented Jul 23, 2019 at 10:29
Add a ment  | 

2 Answers 2

Reset to default 17

All three do different things.

import './file;'

That loads the file, and does not import anything. This is useful if you want to initialize that module (or add some external dependency, e.g. a css file if you use Webpack).

import { something } from './file'

That just imports something from the file, therefore a bundler could optimize all other dependencies away. I'd always try to go with that instead of

import * as evertything from './file'

That imports everything from that module under a namespace, and therefore makes treeshaking more difficult (the bundler cannot optimize it well). I'd only use that if you need everything from that dependency, or if that dependency is loaded externally nevertheless (e.g. import * as React from "react").

I guess the following MDN documentation will make you clear about those things:

import - JavaScript|MDN

As far as I know, 1st method is used when you have only one default export. 2nd is used when you have multiple default exports but you don't want all of them to load and want only few of them. 3rd is the case when you want everything under a single object (which can be used similar to namespace in other programming languages).

发布评论

评论列表(0)

  1. 暂无评论