An interpretation of exports and module Exports and export, export default

Posted by maneetpuri on Sun, 26 Dec 2021 20:00:31 +0100

For front-end beginners, exports and module Exports, export and export default are easy to misunderstand. The author writes an article to interpret them.

Part I: exports and module exports

To make node JS files can call each other, node JS provides a simple module system. The module is node The basic components of JS application, files and modules are one-to-one correspondence. In other words, a node JS file is a module. This file may be JavaScript code, JSON or compiled C/C + + extensions.

1. exports

1.1 export module

The exports object is created by the module system. When we write the module ourselves, we need to write the module interface at the end of the module and declare what the module exposes to the outside world. Exports provides a method to expose the interface. The following code example:

//hello.js
var sayHello = function () {
    console.log('hello')
}
var sos = 110;
var app = {
    name: 'testApp',
    version: '1.0.0',
    help: function () {
        console.log('what can i do for you?')
    }
}
//Export a method
exports.sayHello = sayHello;
//Export a variable
exports.sos = sos;
//Export a JSON object
exports.app = app;

Or in the following form:

//hello.js
exports.sayHello = function () {
    console.log('hello')
}
exports.sos = 110;
exports.app = {
    name: 'testApp',
    version: '1.0.0',
    help: function () {
        console.log('what can i do for you?')
    }
}

In the above example, hello js uses sayHello as the module's access interface through the exports object, loads the module in other modules (or js files) through require('. / Hello'), and then you can directly access hello The member function of the exports object in js.

1.2 introduction module

On node JS, it is very simple to introduce a module. As follows, we create a main JS file and introduce the hello module. The code is as follows:

//main.js
var hello = require('./hello');
//Call the method in the module hello
hello.sayHello();
//Call variables in module hello
console.log(hello.sos)
console.log(hello.app.version)
//Call the JSON object attribute in the module hello
hello.app.help()

Execute the command (node main.js) to run main.js, and the results are as follows:

hello
110
1.0.0
what can i do for you?

In the above example, the code require('. / Hello') introduces hello in the current directory JS file (. / is the current directory, and the default suffix of node.js is JS).

Node.js provides two objects: exports and require. Exports is the interface exposed by the module. Require is used to obtain the interface of a module from the outside, that is, the exports object of the obtained module.

2. module.exports

2.1 export module

Sometimes we want to encapsulate an object into a module. The format is as follows:

//hello.js 
function Hello() {
    var name;
    var sos = '110';
    this.setName = function (thyName) {
        name = thyName;
    };
    this.sayHello = function () {
        console.log('Hello ' + name);
    };
    this.app = {
        name: 'testApp',
        version: '1.0.0',
        help: function () {
            console.log('what can i do for you?')
        }
    };
};
// Encapsulate variables, methods, JSON objects, etc. and export them together
module.exports = Hello;

2.2 introduction module

//main.js
var Hello = require('./hello')
//Through the new keyword, instantiate an object of the hello module. Only through this object can the methods related to the hello module be called.
hello = new Hello();

hello.setName("zhangSan")
hello.sayHello()

console.log(hello.app.version)
hello.app.help()

Execute the command and run main JS, the results are as follows:

Hello zhangSan
1.0.0
what can i do for you?

3. exports and module What is the difference between exports?

As you can see from the above two sections: compared with exports, the only change in the module interface is to use module Exports = Hello instead of exports sayHello = function(){},exports.sos,exports.app. When the module is referenced externally, its interface object is the Hello object itself to be output, not the original exports.

In order to intuitively show the similarities and differences between the two, let's take a look at two examples:

3.1 similarities and differences between the two under exports mode

//hello.js
var sayHello = function () {
    console.log('hello')
}
var sos = 110;
var app = {
    name: 'testApp',
    version: '1.0.0',
    help: function () {
        console.log('what can i do for you?')
    }
}
exports.sayHello = sayHello;
exports.sos = sos;
exports.app = app;
//Print exports and module Contents of exports
console.log(exports);
console.log(module.exports);
console.log(exports === module.exports);

Run the following main JS code:

//main.js
var Hello = require('./exports_mode')

Hello.sayHello()

The operation results are as follows:

{
  sayHello: [Function: sayHello],
  sos: 110,
  app: { name: 'testApp', version: '1.0.0', help: [Function: help] }
}
{
  sayHello: [Function: sayHello],
  sos: 110,
  app: { name: 'testApp', version: '1.0.0', help: [Function: help] }
}
true

Obviously!!! Exports and module The content of exports is exactly the same, in other words: exports points to module exports.

3.2 module. Similarities and differences between the two in exports mode

//hello.js
function Hello() {
    var name;
    this.setName = function (thyName) {
        name = thyName;
    };
    this.sayHello = function () {
        console.log('Hello ' + name);
    };
    this.app = {
        name: 'testApp',
        version: '1.0.0',
        help: function () {
            console.log('what can i do for you?')
        }
    };
};

// Encapsulate variables, methods, JSON objects, etc. and export them together
module.exports = Hello;
//Print exports and module Contents of exports
console.log(exports);
console.log(module.exports);
console.log(exports === module.exports);

Run main JS is as follows:

var Hello = require('./exports_mode')
hello = new Hello();

hello.setName("zhangSan")
hello.sayHello()

The operation results are as follows:

{}
[Function: Hello]
false
Hello zhangSan

Obviously!!! module. In exports mode, module The contents of exports and exports are completely different, module Exports exports the module (hello.js) object itself (Java category, which can be understood as exporting a class rather than an instantiated object). In this scenario, exports is empty (compared with Java, it is understood as an empty object, and it is null if there is no instantiation).

3.3 summary

Based on the above example, we can see that the output module The content of the exports object is a [Function], which is a class in javascript. The advantage of using this method is that exports can only expose a single Function, but module Exports can expose a class.

Part II: export and export default

exports and module exports is node JS, while export and export default are the keywords of ES6 module system. Obviously, the two belong to two systems:

Require: both node and es6 support the introduction of
export / import: only es6 supports export import
module.exports / exports: only node supported exports

1.export

Export is used to export the variables of this module (a file can be understood as a module). import is used to load another module containing the export interface in one module. That is, after the external interface of the module is defined with the export command, other JS files can load this module (file) through the import command. These are ES6 syntax.

Example 1:

//app.js
export var name="ZhangSan";

Example 2:

//app.js
var name1="ZhangSan";
var name2="LiSi";
export { name1 ,name2 }

2.import

import is used to load another module with export interface in one module. See the following example for details.

For example 1 above, the introduction method is:

//main.js
import { name } from "./app.js" //The path shall be filled in according to the actual situation

For example 2 above, the introduction method is:

//main.js
import { name1 , name2 } from "./app.js" //The path shall be filled in according to the actual situation

3.export and export default

Through the above examples, readers must know how to use export and import. If they still don't understand, they can try it by themselves. Export and import are mentioned above, but what is the difference between export and export default? As follows:

  1. Both export and export default can be used to export constants, functions, files, modules, etc;
  2. You can import it in other files or modules by means of import + (constant | function | file | module) name, so that it can be used;
  3. In a file or module, there can be multiple exports and import s, and only one export default;
  4. When exporting through export, {} should be added during import, and export default is not required

In fact, many times, export and export default can achieve the same purpose, but there are some differences in usage. Note that in Article 4, {} should be added during import when exporting through export, and export default is not required. Use the export default command to specify the default output for the module, so you don't need to know the variable name of the module to be loaded.

Part III: CommonJS and ES6

1. CommonJS

The module system in Node follows the CommonJS specification. The question comes again. What is the CommonJS specification? Because js used to be confused, each wrote its own code, and there was no concept of a module. In fact, this specification is a definition of a module.

The modules defined by CommonJS are divided into:

Module ID (module), module definitions (exports), module reference (require)

1.1 exports and module exports

When a node executes a file, it will generate an exports and module object in the file, and the module has an exports attribute. The relationship between them is shown in the figure below, pointing to a {} memory area.

exports = module.exports = {};

In fact, the content exported by require is module The contents of the memory block pointed to by exports are not those of exports. In short, the difference between them is that exports is only module Exports to assist the latter in adding content.

1.2 precautions

In practical application, in order to avoid confusion, try to use module Exports, and then import with require.

2. ES6

ES6, fully known as ECMAScript 6.0, is the next version standard of JavaScript, which was released in June 2015. ES6 is mainly to solve the inherent shortcomings of ES5. For example, there is no concept of class in JavaScript, but the JavaScript of browsers is ES5 version. Most high-level browsers also support ES6, but only realize some features and functions of ES6.

Before ES6, RequireJS or seaJS were used to realize modularization (respectively the modular Library Based on AMD specification and the modular Library Based on CMD specification). ES6 introduced modularization, and its design idea is to determine the dependency of the module and the input and output variables at compile time.

The modularization of ES6 is divided into two modules: export and import.

2.1 characteristics of ES6

  • The module of ES6 automatically turns on the strict mode, whether you add use strict to the module head or not;
  • The module can import and export various types of variables, such as functions, objects, strings, numbers, Boolean values, classes, etc.
  • Each module has its own context. The variables declared in each module are local variables and will not pollute the global scope.
  • Each module is loaded only once (it is a single instance). If you load the same file in the same directory, you can read it directly from memory.

2.2 basic usage

  • The module imports and exports various types of variables, such as string, value, function and class.
  • The exported function declaration and class declaration must have a name (the export default command is considered separately).
  • You can export not only declarations but also references (such as functions).
  • The export command can appear anywhere in the module, but it must be at the top level of the module.
  • The import command will be promoted to the head of the whole module and executed first.

reference

  1. https://segmentfault.com/a/1190000010426778;
  2. https://www.runoob.com/nodejs/nodejs-module-system.html;
  3. https://www.runoob.com/w3cnote/es6-module.html

Topics: Javascript ECMAScript import