6

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

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?

2
  • import foo from ... only works if the imported module has a default export. Everything you need to know should be contained in developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . Commented Dec 31, 2015 at 16:28
  • Thank you Felix, you were right! Commented Jan 2, 2016 at 20:29

2 Answers 2

1

I am not no expert but import is similar to require in many ways, but the key difference are:

  • 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.

  • 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, i.e browsers that support ES6, import would work

Example from lukehoban's es6features to re-enforce 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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I know it works like that, but my problem is that I want to use import in lib/math.js (in your example).. I'm using imports in other files, but in other files I've got classes. Here There is a single function which is exported, and I would like to use other modules in that single function. That doesn't work sadly.
1

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

So comment from @Felix King has directed me to the right answer. As Felix suggested, rest module doesn't have default export function so it should be imported like that:

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:

import mime from 'rest/interceptor/mime';

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.