在我最近安装的许多npm模块中(例如@ material-ui / 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'
在哪种情况下我应该使用变体3 / es6导出的文件?
如果tree-shaking
/ dead code elimination
在webpack和npm模块中有效。我应该使用变量1(命名为import)而不是变量2(默认导出)吗?
答案 0 :(得分:0)
有两种导出类型:
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
答案 1 :(得分:0)
主要区别在于该库如何导出模块。
当您执行import AppBar from '@material-ui/core/AppBar/AppBar'
时,这意味着@material-ui/core/AppBar/AppBar
正在使用object
导出单个export default AppBar
。
您应该像以前一样导入。但是,您不限于从模块中导出单个默认导出。
例如,使用React
会公开具有您可能要使用的所有属性的主对象(即React
,该对象将再次默认导出)。但是使用ES6中的导入语法,您可以从该模块中导入特定的属性/函数(例如,import { Component } from 'react';
会以export class Component...
的形式导出)
我希望这很清楚!