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
.