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
.
Little bibliography about https://cursos.alura.com.br/forum/topico-require-vs-import-39026
– user60252