Why not have `import module-name.export1` in javascript?

。_饼干妹妹 提交于 2021-02-08 12:11:17

问题


What is the design limitation behind the ES6 import statement syntax?

import { export1 } from "module-name";

as shown here.

Why not have

import module-name.export1

If somehow having the 'import' keyword in the first place is so important, why not use it like that?

For comparison consider several other popular languages:

  • Java : import package.subpackage.ClassName;
  • Python : from module import SomeClass
  • C#: using System.Text;

From left to right: broadScope -> module -> particularItem.
While in ES6, it goes backwards: particularItem <- module

How is it better to first write the export1, then the module-name? How is that more optimal than import module-name.export?


回答1:


I am not one of them - maintainers. But, here's a straightforward answer:

You know how linking to a folder work?

'./project/dir'

We use similar when linking to image, etc. It's a standard of HTML. And the ES6 is also a part of HTML5 (HTML, JavaScript, CSS). And thus, it follows to import modules from the folders specifying the path.

import defaultExport from '../path'
import { namedExport } from '../node_modules/package'

Like we define a variable to use:

// define myVar at first hand and declare it's value at second hand
const myVar = 10
console.log(myVar)
// But not
// 10 = const myVar
// console.log(10) // myVar

Following the approach, we have the import statements:

import myVar from 'module' // value is extracted from module
import { myKeyVar } from 'package'
console.log(myVar, myKeyVar)

So, I cannot urge to have definition like:

from 'module' import myVar

And finally, there's no alternative way for this. So, we cannot say that this is the best approach or the worst approach. It's just a standard they follow to implement it.



来源:https://stackoverflow.com/questions/63520227/why-not-have-import-module-name-export1-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!