为什么npm模块(例如material-ui)会导出es6和es5文件?

时间:2018-10-18 08:23:05

标签: javascript material-ui

在我最近安装的许多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'
  1. 在哪种情况下我应该使用变体3 / es6导出的文件?

  2. 如果tree-shaking / dead code elimination在webpack和npm模块中有效。我应该使用变量1(命名为import)而不是变量2(默认导出)吗?

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...的形式导出)

我希望这很清楚!