JavaScript: Differences between import and require

9

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

import Library from 'some-library';

or

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

However, I see that there is no standardization for using import or require .

For example: when I see a Node.js code, it is always used require . In codes related to ES6 or TypeScript almost always use 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.

    
asked by anonymous 20.06.2017 / 04:37

1 answer

16

These tools belong to different generations.

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

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

It is important to note that some browsers do not yet support ES6, so it may need to be compiled before using.

The require uses module.exports , which is the "old" (but still valid) syntax for exporting a module, and that can be whatever we want, an object, a string, etc.

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

Examples:

Exporting file:

// 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};

Importing file:

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

    
20.06.2017 / 09:53