exporting React component class with one name, importing it with another name, still working. Why?

隐身守侯 提交于 2019-12-11 14:18:13

问题


here is one file (clock.js) for my React app

class Clock extends Component { ...
...}
export default Clock;

here's another where I'm importing the Clock component

import Clock_1 from './clock/clock';
...
<Route exact path="/clock" component={Clock_1} />

as you can see, I exported it with name Clock and imported it with name Clock_1, still it is compiling and running successfully. Why?

PS: Apologies beforehand if this question sounds lame/ too simple/ stupid. I'm a beginner.


回答1:


[ES6 Feature] First of all default keyword with export allows us to set Anonymous Name we want to set when we import it.

If you export it with

export const Clock,

then you have to import it strictly(ES6 way - using object destructuring syntax for named exports) with

import { Clock } from './Clock

or also can use import * as Clocks from './Clock' if you want to import all constants/variables(i.e. all named exports jammed into one object). This will make Clocks as an object with all exported variables/anything within it.

Like Clocks = { Clock : Clock \\ import {Clock} from './Clock', .... }

Named exports are useful to export several values. During the import, it is mandatory to use the same name of the module as it was defined in source file.

But a default export can be imported with any name for example:

export default k = 12; // in file test.js

import m from './test' // note that we got the freedom to use import m instead of import k, because k was default export

console.log(m);        // will log 12



回答2:


Because you use export default. Which means that you export only that class so the name is not that relevant. Anyway, that's why TSLint(a set of rules) says that it's forbidden to use export default.




回答3:


its es6 feature, its just like giving an alias name or assigning one variable reference to another with some other name

behind the curtain it is like this when you import with some other name:

Clock_1 = Clock



来源:https://stackoverflow.com/questions/48441771/exporting-react-component-class-with-one-name-importing-it-with-another-name-s

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