First, we need to understand that the CommonJS module specification is a different concept from the ES module specification

1. CommonJs

1.1 concept

  • Node applications are composed of modules that follow the CommonJS module specification.
    1. According to the specification, each file is a module with its own scope. Defining variables, functions, classes, etc. in one file is private and not visible to other files.
    2. According to the specification, within each module, the module white energy represents the current module. This variable is an object whose exports property (module.exports) is the interface to the outside world.
    3. Module. exports is used to export file definition content, and require is used to load modules.

1.2 instance

1.2.1 the module exports
// example.js
let x = 5;
let addX = (value) = > {
    return x + value;
}
module.exports.x = x;
module.exports.addX = addX;
Copy the code
1.2.2 the require
let requireTest = require(./example.js);
let x = requireTest.x;
let addX = requireTest.addX(3);
console.log(x); / / 5
console.log(addx); / / 8
Copy the code

1.3 exports and the module exports

  • Node provides an exports variable for each module, pointing to module.exports. This is like adding the following code to the header of each module:
let exports = module.exports;
Copy the code
  • Module. exports is the real interface, exports is just an accessory. Module. exports is returned to the call instead of exports. All exports collected properties and methods are assigned to module. exports.

2. ES6 module specification

2.1 concept

  • Unlike CommonJS,ES6 uses export and import to export and import modules.
  • The export command specifies the external interface and must establish a corresponding relationship with the variables inside the module.

2.2 instance

2.2.1 export
let firstName = "Chengwu";
let lastName = "Du";
export { firstName, lastName }
Copy the code
2.2.2 Export Meaning Example
// one
export const PI = "3.1415926";

// two
let name = "Robin";
export { name }

// three
let n = "Robin";
export { n as name }
Copy the code
2.2.3 the import
import { firstName, lastName } from "./export.js";
let name = firstName + lastName;
console.log(name); // Chengwu Du
Copy the code

2.3 the export default

export defalut function() {
    return "Robin";
}
Copy the code
2.3.1 Export default is different from export
  • There can be more than one export and import in a file or module, but export Default has only one.
  • Export it in export mode. When importing it again, add {} and load it as required. However, export Default is not required.
  • Export Default is used for a single module and export is used for multiple modules.
  • Don’t use both.