preface

Modularization has become an inevitable trend in front-end development. The benefits of modularization are as follows:

  • 1. Avoid variable pollution and naming conflicts
  • 2. Improve code reuse rate
  • 3. Improve maintainability
  • 4. Dependency management

This article mainly on the Node commonJS specification and ES6 specification of shallow level research, explore node and ES6 modular some unknown secrets.

1. The node modular

Node module follows commonJS specification. Commonjs defines modules as module identification, module export and module reference.

In Node, a file is a module and is handled using exports and require.

Exports are available in two forms: module.exports and exports.

Module.exports = {// exports to.... } // exports of the second type'hello world';
Copy the code

Import form:

const index = require('./index');
Copy the code

1.1. What is module?

So, what exactly is this Module?

Print the moule directly in the file

// index.js
console.log(module)
Copy the code

Then execute index.js

node index.js
Copy the code





  • Id is the current file
  • Exports is the value exported by the current Node file module
  • Parent is the module object called by the parent; if null, the file is not called
  • Filename indicates the current filename
  • Loaded Indicates whether the file is loaded
  • Children introduces the module array with the same format as module
  • Paths Finds paths for the node module node_modules all the way to the root directory

Add the utils. Js module to index.js, print the module object, and see that children contains information about the utils module.

const utils = require("./utils");
Copy the code

Module represents a module that identifies information objects when it runs.

1.2. The module. Exports = = = exports?

Exports represents the exported objects generated by the module runtime.

The Module object also has an exports property.

console.log(exports);
console.log(module.exports);
console.log(exports === module.exports);
Copy the code

Module. exports and exports refer to empty objects and both refer to the same object!!

Now let’s rewrite module.exports and exports, respectively, and import index.js in main.js to see the imported object.

index.js

module.exports = {
  name: "hello world"
};

exports.obj = {
  name: "welcome"
};
Copy the code

main.js

const obj = require("./index");

console.log(obj);
Copy the code

Module. exports exports!!

Since we redefined the modulex.export reference value to import the object referenced by module.exports, we can conclude:

What a module really exports is the value of module.exports, which is just a reference to module.exports.

1.3. The module caches and exports reference data types

Question: 1. If a module is loaded multiple times, do you execute the source module multiple times? 2. When exporting the reference data type, modify the reference attribute value of the exported object, so whether the attribute value in the source module is changed?

We modify the name property of the imported object in main.js, and print the exported object asynchronously in index.js.

index.js

const obj = {
  name: "hello world"
};

setTimeout(() => {
  console.log("index");
  console.log(obj);
}, 500);

module.exports = obj;
Copy the code

main.js

const obj1 = require("./index");
const obj2 = require("./index");

obj1.name = "welcome";

console.log("obj1:");
console.log(obj1);
console.log("obj2:");
console.log(obj2);
Copy the code

As you can see, even though we imported the source module twice, the source module was loaded only once. When we changed the value of the exported module, the value of the source module also changed.

Conclusion:

  • 1. When importing a module, the system caches the imported module, imports the module later, and obtains the imported module from the cache.
  • 2. When exporting reference type data, the exported object points to the same object as the imported object.

1.4. Best practices

Module. exports and exports are best used as follows:

1. Module. exports is used when exporting objects

function add(x, y){
    return x+y;
}
function multiply(x, y){
    return x*y;
}
module.exports = {
    add,
    multiply
}
Copy the code

2. Exports are used when exporting variables or methods

exports.name = 'hello world';
exports.func = function() {
    console.log('hello world');
}
Copy the code

Exports and module.exports should not be used together. Exports should not be reassigned to a new object or the reference will be invalid.

1.5. Node modularization Summary

Modularization for Node CommonJS specification is summarized as follows:

  • 1. Module object is an identification object generated during module running to provide module information;
  • Exports refers to the same object as exports, and require imports from module.exports.
  • 3. There is a module cache after the same module is imported, and the subsequent imports are loaded from the cache.
  • 4. The reference to the source module is the same object as the reference to the imported module.
  • Module. exports and exports should not be used at the same time. Exports should be used for exported objects and exports for exported variables.

2. The es6 modular

Next, let’s look at the ES6 modularity specification. Es6 modularity is handled through export and import.

Common export forms:

export default obj;

export const name = "hello world";
// export{name1 name2,... };Copy the code

Import form:

import obj, { name } from "./exp/exports";
Copy the code

2.1. The export

In ES6, a file represents a module that exposes its interface through export, which is often used to export multiple variables.

Correct way to write:

exportvar name = 1; Var name = 1;exportVar a = 1; var b = 2; var c = 3;export{a, b, c} // Export objectsexport const obj = {
    name: 'hello world'}; // Export the functionexport function fun1() {
    console.log('hello world'); } // Export the import module directlyexport * from './index';
Copy the code

Incorrect writing:

var name = 1;
export name;
Copy the code

When importing modules, the names of imported variables must correspond to those exported by export.

import { a, b, c } from './index';
Copy the code

2.2. The export default

Export Default indicates the default external interface of a module. Each module can have only one Export default.

Export default is the syntactic sugar of export, which means to export a default interface.

const obj = {
  name: "hello world"
};

exportdefault obj; / / equivalent to theexport{ obj as default }; // as exports the interface whose alias is defaultCopy the code

Importing the default export

import obj from './index'; Import {default as obj} from'./index';
Copy the code

2.3. The import * as xx

As stands for aliases and can be used as follows in import and export:

export

export { name as hello };
Copy the code

import

import { hello as name } from './index';
Copy the code

We sometimes see the import * and export * forms. import

import * as obj './index';
Copy the code

For example, index.js exports the obj and name variables. By default, it exports the arr array.

index.js

const obj = {
  name: "hello world"
};

const name = "hello world";

const arr = [1, 2, 3];

export { obj, name };
export default arr;
Copy the code

app.js

import * as module from "./exp/exports";
console.log(module);
console.log(module.default);
console.log(module.name);
console.log(module.obj);
Copy the code

You can see that we have introduced a Module object that describes the information exported by the Module. Where default represents the default export, corresponding array arr, name and obj represent the exported variables name and obj respectively.

2.4. Importing and exporting reference data types multiple times

What happens when you export an object variable multiple times and modify the exported variable object?

index.js

const obj = {
  name: "hello world"
};

console.log("Index.js loaded");
setTimeout(() => {
  console.log("index:");
  console.log(obj);
}, 500);

export default obj;
Copy the code

app.js

import obj1 from "./exp/index";
import obj2 from "./exp/index";

obj1.name = "welcome";
console.log("obj1:");
console.log(obj1);
console.log("obj2:");
console.log(obj2);
Copy the code

View the results

As you can see, the index.js component is imported twice, only loaded once, and the source object obj has changed.

Conclusion:

  • 1. If the same module is imported multiple times, it is executed only once.
  • 2. When exporting reference data types, the exported and imported objects point to the same variable. If you modify the exported variable object, the source object will also change.

2.5. Best practices

1. When exporting a variable, export Default is recommended. For example, export Default is used to export components in react.

// main.jsx

import React from 'react';

 class Main extends React.Component{
  render() {
    return (
      <div>Hello World.</div>
    )
  }
}

export default Main;
Copy the code

2. When exporting multiple variables, export is recommended.

// math.js

function add(a, b) {
  return a + b;
}

function reduce(a, b) {
  return a - b;
}

function multiply(a, b) {
  return a * b;
}

export { add, reduce, multiply };
Copy the code

3. When multiple variables need to be exported by default, you can use export and export default at the same time.

const obj = {
  name: "hello world"
};

const name = "hello world";

export { obj, name };
export default function getName() {
  return obj.name;
}
Copy the code

2.6. Summary of ES6 modularity

Modularization of ES6 specification is summarized as follows:

  • 1. Es6 implements the export and import functions through export and import.
  • 2. Es6 export supports the export of multiple variables. Export default is a syntactic sugar in the form of export, indicating the export of the default interface.
  • 3.import * as xx from 'xx.js'The imported Module object contains the default interface and other variable interfaces.
  • 4. If multiple modules are imported for multiple times, they will be executed only once.
  • 5. When exporting reference data types, the exported and imported objects point to the same variable. If you modify the exported variable object, the source object will also change.
  • 6. You are advised to use Export default to export a single variable and export to export multiple variables.

conclusion

The above is some small knowledge about node and ES6 modularity explored by the blogger. If you feel there is a harvest, you can pay attention to a wave of, like a wave, the code word is not easy, thank you very much.