跳转至

Introduction

ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements.

The following example of an ES module exports a function:

1
2
3
4
5
6
// addTwo.mjs
function addTwo(num) {
  return num + 2;
}

export { addTwo };

The following example of an ES module imports the function from addTwo.mjs:

1
2
3
4
5
// app.mjs
import { addTwo } from './addTwo.mjs';

// Prints: 6
console.log(addTwo(4));

Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.