JavaScript: differences between import and require

I know that import and require are used in JavaScript to import functions or third-party objects. It is common code snippets like:

import Library from 'some-library';

Or

const Library = require('some-library');

However, I see that there is no standardization as to the use of import or require.

For example: when I see a node code.js is always used require. In codes related to ES6 or TypeScript is almost always used import.

My question is: What is the difference between these two approaches? When should I (or can I) use each of these approaches?

Thanks for the help.

Author: Bruno Peres, 2017-06-20

1 answers

These tools belong to different generations.

The require exists only in CommonJS (the way the Node.js created to import and export modules within an application), and the import is ES6, i.e. a new tool that both browser JavaScript and server JavaScript (Node.js) can use.

In addition to this historical difference there are differences in use, where import is more flexible, modern and powerful than require.

It is important however to have in note that some browsers do not yet support ES6, so you may need to compile before using.

Require uses module.exports, which is the "old" (but still valid) syntax to export a module, and which can be anything we want, an object, a string, etc.

import uses both, i.e. you can use module.exports and export, and allows you to export multiple pieces of code more or less like module.export did. One of the advantages of import is that it can only import parts of what was exported:

Examples:

File exporting:

// ficheiro A.js

// sintaxe CommonJS
module.exports = {
    foo: function(){ return 'bar';},
    baz: 123
}

// sintaxe ES6
export function foo(){ return 'bar';}
export const baz = 123;

// ou

function foo(){ return 'bar';}
const baz = 123;

export default {foo, baz};

File that imports:

// ficheiro B.js

// sintaxe CommonJS
const A = require('./A.js');
const foo = A.foo;
const baz = A.baz;

// sintaxe ES6
import * as A from './A.js';
const foo = A.foo;
const baz = A.baz;

// ou somente
import {foo, baz} from './A.js';

When you use export default (ES6 syntax) it implies that you only export one thing per file. If it is an object import can import only pieces, but if it is a function for example then you can use only import foo from './A.js'; without needing {} or * as foo.

 50
Author: Sergio, 2017-06-20 07:53:06