【问题标题】:Why do npm modules, like material-ui, export es6 and es5 files?为什么 npm 模块(如 material-ui)会导出 es6 和 es5 文件?
【发布时间】:2018-10-18 08:23:04
【问题描述】:

在我最近安装的许多 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. 在什么情况下应该使用variant 3 / es6导出文件?

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

【问题讨论】:

    标签: javascript material-ui


    【解决方案1】:

    有两种导出方式:

    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

    【讨论】:

    • 在你的第一个例子中我不会做export { myFunction };,虽然它是正确的,但它接缝有点令人困惑;你正在导出一个包含函数的对象。相反,export function myFunction() {...} 你不认为这更清楚吗?
    【解决方案2】:

    主要区别在于该库如何导出模块。

    当您执行import AppBar from '@material-ui/core/AppBar/AppBar' 时,这意味着@material-ui/core/AppBar/AppBar 正在导出单个objectexport default AppBar

    您应该像以前一样导入。但是,您不限于从模块中导出单个默认导出。

    例如,React 公开了具有您可能想要使用的所有属性的主对象(即再次作为默认导出的React)。但是使用 ES6 的导入语法,您可以从该模块导入特定的属性/函数(例如,import { Component } from 'react'; 导出为 export class Component...

    我希望这很清楚!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 2015-03-18
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多