Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'require' operates differently from 'import' es6?

I am encountering a behaviour that I can't explain. Depending on using import or require, this test successes (import) or fails (require).

In case of fail, I have the following error:

PhantomJS 2.1.1 (Windows 7 0.0.0) immutability a number is immutable FAILED undefined is not a constructor (evaluating 'expect((0, _immutable.List)([1])).toEqualImmutable((0, _immutable.List)([1]))')

Here is the code :

import { Map, List } from 'immutable';
const expect = require("expect");
// import expectImmutable from "expect-immutable";
const expectImmutable = require("expect-immutable");

expect.extend(expectImmutable);

describe("immutability", () => {
    describe("a number", () => {
        function increment(currentState) {
            return currentState + 1;
        }
        it("is immutable", () => {
            expect(List([1])).toEqualImmutable(List([1]));
            expect(Map({ a: 1 })).toEqualImmutable(Map({ a: 1 }));
            let state = 42;
            let nextState = increment(state);

            expect(List([nextState])).toEqualImmutable(List([43]));
            expect(List([state])).toEqualImmutable(List([42]));
        });
    });
});

Does anyone have an explanation of what is happening behind the scene?

like image 499
Kevin Coulibaly Avatar asked Apr 05 '16 08:04

Kevin Coulibaly


People also ask

Are require and import interchangeable?

The major difference between require and import , is that require will automatically scan node_modules to find modules, but import , which comes from ES6, won't. Most people use babel to compile import and export , which makes import act the same as require .

Is it OK to mix require and import?

Yes, this is acceptable in TypeScript.


1 Answers

Thanks @zerkms and @maioman your advices have really helped. You were right @maioman, It was due to the export syntax used by the library.

es6 :

export default foo;

require :

module.exports = foo;

So when needed to require an es6 written export, we should handle the default keyword.

require("foo").default;
like image 132
Kevin Coulibaly Avatar answered Nov 15 '22 00:11

Kevin Coulibaly