Read more articles in the series at myMaking a blog, please visit the sample codeHere,.

Nodejs defines the module

Because Nodejs modularity is older, it follows the CommonJS specification rather than the ES6 modularity.

Module objects, exports, and require methods are the most commonly used in Nodejs modularization.

Module and exports are used to export modules, and require is used to reference modules.

A simple module example

Sample code: /lesson10/module1.js, / Lesson10 /require.js

Create a new module1.js file with the following code:

module.exports.a = 1
module.exports.b = 2

let c = 3
Copy the code

In require.js, introduce the module and print:

const module1 = require('./module1')

console.log(module1)
Copy the code

You can see the print: {a: 1, b: 2}.

This code means the following:

  1. Module1. js exports module.exports as an object with a and b attributes.
  2. The variable c is defined in module1.js, but it exists only in the module module1.js and is not accessible from the outside.
  3. To reference module1.js in require.js, you must use a relative or absolute path.
  4. If you use the module name instead of the path, the module will be referenced in the node_modules folder in the project directory by default. For example:
const module2 = require('module2')

console.log(module2)  // { a: 1, b: 2 }
Copy the code

If there is a module2.js file in the node_modules folder in the project directory, it will be referenced.

If it does not, it will look for module2 in the node_modules folder of the system, that is, the globally installed modules.

If the module does not already exist, an error is reported.

Modules imported via require can be arbitrarily named, so const a = require(‘module2’) is also acceptable.

module.exports

Exports. a = 1; exports.a = 1; exports.a = 1; exports.a = 1; exports.b = 1; . .

But exports are used directly, and only this method is supported.

exports = {
  a: 1,
  b: 2
}

Copy the code

Exports only support exports.a = 1; Syntax like this.

If you want to directly define the entire module as an object, function, variable, class, then you need to use module.exports = 123.

As follows:

Example code: /lesson10/module3.js

module.exports = {
  a: 1,
  b: 2
}

module.exports = 123

module.exports = {
  a: 1,
  b: 2,
  c: 3
}

module.exports = function () {
  console.log('test')
}

module.exports = class {
  constructor(name) {
    this.name = name
  }

  show() {
    console.log(`Show ${this.name}`)}}Copy the code

Module. exports can let modules be assigned to any type, but it is important to note that module.exports act like a global variable within a module.

For repeated assignments, only the last value is valid, and the previous value is directly overwritten.

In this example, the Module3.js module is eventually exported as a class.

For this reason, it is generally recommended to use module.exports to avoid errors.