简体   繁体   English

如何在ecmascript-6中导入模块?

[英]How to import modules in ecmascript-6?

I want to import different module to my module in ecma script 6. For example: 我想将其他模块导入ecma脚本6中的模块。例如:

import rest from 'rest';

export function client() {

    // some logic

}

If I will change the import statement to classic: 如果我将导入语句更改为经典:

var rest = require('rest');

everything is working fine. 一切正常。 Any ideas? 有任何想法吗?

I am not no expert but import is similar to require in many ways, but the key difference are: 我不是专家,但是import在很多方面都类似于require ,但是主要区别是:

  • you can import selective items using import ( guess this is close to python), but with require , you export only a single module as a namespace, everything else is it's sub-modules. 您可以使用import导入选择性项目(猜想这与python差不多),但是使用require ,您只能将单个模块导出为名称空间,其他所有内容都是子模块。

  • second is, require is more of of node.js thingy(though you can bring it into browser using browserify ),, but import is now a native feature of ES6, ie browsers that support ES6, import would work 第二个是, require更多的node.js东西(尽管您可以使用browserify将它带入浏览器),但是import现在是ES6的本机功能,即支持ES6的浏览器可以进行import

Example from lukehoban's es6features to re-enforce my first point: 来自lukehoban的es6features的例子来重申我的第一点:

// lib/math.js
export function sum(x, y) {
  return x + y;
}
export var pi = 3.141593;

// app.js
import * as math from "lib/math";
alert("2π = " + math.sum(math.pi, math.pi));

// otherApp.js
import {sum, pi} from "lib/math";
alert("2π = " + sum(pi, pi));

//Some additional features include export default and export *:

// lib/mathplusplus.js
export * from "lib/math";
export var e = 2.71828182846;
export default function(x) {
    return Math.log(x);
}

// app.js
import ln, {pi, e} from "lib/mathplusplus";
alert("2π = " + ln(e)*pi*2);

This is an answer for my question, but if you want to know how to import other files please refer to the answer given by user @mido or for example check this page: http://www.2ality.com/2014/09/es6-modules-final.html 这是我的问题的答案,但是如果您想知道如何导入其他文件,请参考用户@mido给出的答案,例如,请检查此页面: http ://www.2ality.com/2014/09/ es6-modules-final.html

So comment from @Felix King has directed me to the right answer. 因此,@ Felix King的评论已将我引向正确的答案。 As Felix suggested, rest module doesn't have default export function so it should be imported like that: 正如Felix所建议的,rest模块没有默认的导出功能,因此应该这样导入:

import * as rest from 'rest';

So it depends from a module, how it is written. 因此,它取决于模块的编写方式。 For example "mime" interceptor module which is included in rest can be included by: 例如,包含在rest中的“ mime”拦截器模块可以包含在:

import mime from 'rest/interceptor/mime';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM