问题
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