在许多npm模块中,我最近安装了(例如。@material/core)有三种方法可以导入相同的React组件:
import { AppBar } from '@material-ui/core'
import AppBar from '@material-ui/core/AppBar/AppBar'
import AppBar from '@material-ui/core/es/AppBar/AppBar'tree-shaking / dead code elimination在webpack和npm模块中工作。我应该使用变式1(命名导入)而不是变式2(默认导出)吗?发布于 2018-10-18 08:35:09
有两类出口:
1)名为导出,即您导出的内容如下:
// exports a function declared earlier
export { myFunction };
// exports a constant
export const FOO = "foo";如果您想导入这些文件,那么语法如下所示:
import {FOO, myFunction} from './file';2)默认导出--即导出如下内容:
export default function() {}您可以在导入时将函数、类重命名为任何您想要的名称,其语法如下:
import myFunction from './file';注意:您可以在单个文件中有多个命名导出,但不能在单个文件中有多个默认导出。
有关更多细节,请查看以下链接:https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
发布于 2018-10-18 08:38:32
主要区别在于该库是如何导出模块的。
当您执行import AppBar from '@material-ui/core/AppBar/AppBar'时,这意味着@material-ui/core/AppBar/AppBar正在导出一个带有export default AppBar的object。
你应该像以前一样进口。但是,您并不局限于从模块导出单个默认导出。
例如,对于React,公开主对象(即再次导出为默认的React ),该对象具有您可能想要使用的所有属性。但是使用来自ES6的导入语法,您可以从该模块导入特定的属性/函数(例如,导出为export class Component...的import { Component } from 'react'; )。
我希望这是清楚的!
https://stackoverflow.com/questions/52869862
复制相似问题