How to import modules in ecmascript-6?

I want to import another module into my module in ecma script 6. For example:

import rest from 'rest'; export function client() { // some logic } 

If I changed the import statement to classic:

 var rest = require('rest'); 

everything is working fine. Any ideas?

+6
source share
2 answers

This is the answer to my question, but if you want to learn how to import other files, refer to the answer provided by @mido or, for example, check this page: http://www.2ality.com/2014/09/es6-modules -final.html

So, a comment from @Felix King sent me the correct answer. As Felix suggested, the rest module does not have a default export function, so you need to import it as follows:

 import * as rest from 'rest'; 

So it depends on the module as it is written. For example, the "mime" interceptor module, which is included in the rest, can be included:

 import mime from 'rest/interceptor/mime'; 
+1
source

I'm not an expert, but import is a lot like require , but the key difference is:

  • you can import custom elements with import (suppose it's close to python), but with require you only export one module as a namespace, the rest is submodules.

  • second, require more from node.js thingy (although you can bring it to the browser using a browser), but import now a native function of ES6, that is, browsers that support ES6, import will work

An example from lukehoban es6features to reapply my first point:

 // 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); 
+1
source

All Articles