Javascript: Differences between import and require

Asked

Viewed 36,730 times

34

I know that import and require are used in Javascript to import functions or objects from third parties. Code snippets like:

import Library from 'some-library';

or

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

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

For example: when I see a code Node.js is always used require. ES6 or Typescript related codes are almost always used import.

My point is: what is the difference between these two approaches? When should I (or may) use each of these approaches?

Thanks for the help.

  • Little bibliography about https://cursos.alura.com.br/forum/topico-require-vs-import-39026

1 answer

55


These tools belong to different generations.

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

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

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

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

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

Examples:

File that exports:

// 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 matters:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.