当前位置:网站首页>Distinguish between the export of ES6 and the module.exports of nodejs
Distinguish between the export of ES6 and the module.exports of nodejs
2022-07-28 17:37:00 【Mr_ Bobcp】
Catalog
Preface
Recently, with Vue.js To encapsulate the request method , Reuse node.js When building a simple service test request, I feel module.exports / exports、require、export / import How to write something 、 The effect is similar but different , I don't feel clear about the specific difference , So I studied the standard again , Record the article for reference .
require: node and es6 All supported introductions (CommonJS standard )
export / import : Only es6 Supported export import
module.exports / exports: Only node Supported exports (CommonJS standard )
CommonJS The module specification
Node Application consists of modules , use CommonJS The module specification .
According to this specification , Each file is a module , Has its own scope . Variables defined in a file 、 function 、 class , It's all private , Not visible to other files .
CommonJS Specifications stipulated , Inside each module ,module Variable represents the current module . This variable is an object , its exports attribute ( namely module.exports) It's an external interface . Load a module , In fact, the module is loaded module.exports attribute .
exports And module.exports
var x = 5;
var addX = function (value) {
return value + x;
};
module.exports.x = x;
module.exports.addX = addX;
The above code passes module.exports Output variables x And the function addX.
require Method for loading modules .
var example = require('./example.js');
console.log(example.x); // 5
console.log(example.addX(1)); // 6
For convenience ,Node One for each module exports Variable , Point to module.exports. This is the same as each module head , There's a line like this .
var exports = module.exports;
So we can directly exports Add method on object , Interface for external output , As in module.exports Add the same on . Be careful , Can't directly exports Variable points to a value , Because it's cut off exports And module.exports The connection of .
ES6 The module specification
differ CommonJS,ES6 Use export and import To export 、 The import module .
// profile.js
var firstName = 'Michael';
var lastName = 'Jackson';
var year = 1958;
export {
firstName, lastName, year};
Here's the thing to watch out for ,export The order specifies an external interface , One to one correspondence must be established with the variables inside the module .
import command
Use export After the command defines the external interface of the module , other JS The file can be passed import Command to load this module .
// main.js
import {
firstName, lastName, year} from './profile';
function setName(element) {
element.textContent = firstName + ' ' + lastName;
}
Code above import command , Used for loading profile.js file , And enter variables from it .import Command to accept a pair of braces , It specifies the variable name to be imported from other modules . Variable names in braces , Must be associated with the imported module (profile.js) The name of the external interface is the same .
If you want to rename the input variable ,import Command to use as keyword , Rename the input variable .
import {
lastName as surname } from './profile';
import hinder from Specify the location of the module file , Can be a relative path , It could be an absolute path ,.js The path can be omitted . If it's just the module name , No path , Then there must be a configuration file , tell JavaScript Engine location of this module .
// Writing a
export var m = 1;
// Write two
var m = 1;
export {
m};
// Write three
var n = 1;
export {
n as m};
export default command
Use export default command , Specify the default output for the module .
// export-default.js
export default function () {
console.log('foo');
}
The code above is a module file export-default.js, Its default output is a function .
When other modules load this module ,import The command can specify any name for the anonymous function .
// import-default.js
import customName from './export-default';
customName(); // 'foo'
Code above import command , You can point to... By any name export-default.js Output method , In this case, you do not need to know the function name of the original module output . It should be noted that , At this time import Command behind , Don't use braces .
export default The command is used before non anonymous functions , It's OK, too .
// export-default.js
export default function foo() {
console.log('foo');
}
// Or written
function foo() {
console.log('foo');
}
export default foo;
In the above code ,foo The function name of the function foo, It's not valid outside the module . When loading , As anonymous function loading .
Let's compare the default output with the normal output .
// The first group
export default function crc32() {
// Output
// ...
}
import crc32 from 'crc32'; // Input
// The second group
export function crc32() {
// Output
// ...
};
import {
crc32} from 'crc32'; // Input
Two sets of writing methods of the above code , The first group is to use export default when , Corresponding import Statements do not require braces ; The second group is not to use export default when , Corresponding import Statements need to use braces .
export default The command is used to specify the default output of the module . obviously , A module can only have one default output , therefore export default The command can only be used once . therefore ,import You don't need parentheses after the command , Because there can only be one method .
Essentially ,export default Is to output a called default Variable or method of , Then the system allows you to give it any name . therefore , The following formulation is valid .
// modules.js
function add(x, y) {
return x * y;
}
export {
add as default};
// Equate to
// export default add;
// app.js
import {
default as xxx } from 'modules';
// Equate to
// import xxx from 'modules';
Precisely because export default The command is actually just an output called default The variable of , So it can't be followed by a variable declaration statement .
// correct
export var a = 1;
// correct
var a = 1;
export default a;
// error
export default var a = 1;
In the above code ,export default a It means to change the variable a The value of is assigned to the variable default. therefore , The last way of writing will report a mistake .
With export default command , Input module is very intuitive , To input lodash Module as an example .
import _ from 'lodash';
If you want to be in one import In the sentence , Enter the default method and other variables at the same time , It can be written as follows .
import _, {
each } from 'lodash';
Corresponding to the code above export The statement is as follows .
export default function (obj) {
// ···
}
export function each(obj, iterator, context) {
// ···
}
export {
each as forEach };
The last line of the above code means , Exposed forEach Interface , The default point to each Interface , namely forEach and each Point to the same method .
If you want to output the default value , Just follow the value with export default After that .
export default 42;
export default It can also be used to output classes .
// MyClass.js
export default class {
... }
// main.js
import MyClass from 'MyClass';
let o = new MyClass();
export And import The compound writing of
If in a module , First input and then output the same module ,import Sentences can be compared with export The sentences are written together .
export {
foo, bar } from 'my_module';
// Equate to
import {
foo, bar } from 'my_module';
export {
foo, boo};
In the above code ,export and import Statements can be combined , Write in a line .
Module interface renaming and overall output , It can also be written in this way .
// Interface renaming
export {
foo as myFoo } from 'my_module';
// Overall output
export * from 'my_module';
The default interface is written as follows .
export {
default } from 'foo';
The way to change the named interface to the default interface is as follows .
export {
es6 as default } from './someModule';
// Equate to
import {
es6 } from './someModule';
export default es6;
similarly , The default interface can also be renamed as named interface .
export {
default as es6 } from './someModule';
in addition ,ES7 There is a proposal , Simplify the writing of input before output , Remove the curly braces when outputting .
// Current writing
export {
v} from 'mod';
// How to write the proposal
export v from 'mod';
Reference link :
http://javascript.ruanyifeng.com/nodejs/module.html
http://caibaojian.com/es6/module.html
边栏推荐
- 培训软件测试能不能就业
- 医学公共数据库
- Gray code and binary conversion and typical examples (4bits gray code counter)
- Wechat applet cash red packet returns the error "the IP address is not the available IP address you set on the merchant platform". The ultimate solution
- [ansible] the ansible shell encountered the problem of $symbol in awk when executing remote commands
- 【无标题】
- Selection of resistance in high speed circuit
- Management of third-party technical services in product development
- 将input type='file' 类型的图片文件转成base64
- 2021 年全国大学生数据统计与分析竞赛
猜你喜欢

MySQL detailed learning tutorial (recommended Collection)

MySQL implements sorting according to custom (specified order)

Embedded development learning path
![[CDH] configure CDH components through clouderamanager and collect JMX information with Prometheus monitoring](/img/6a/bbc1ab0cfae9139308da4ded1376a8.png)
[CDH] configure CDH components through clouderamanager and collect JMX information with Prometheus monitoring

Verilog daily question (vl4 shift operation and multiplication)

AMQP protocol details

With a total data volume of more than trillions of lines, Yuxi cigarette factory can easily deal with it by correctly selecting the timing database

简单易用的APP专项测试工具iTest4.7.0发布啦

ionic 中遇到的一些东西

一文掌握 JVM 面试要点
随机推荐
【sqoop】sqoop1.4.7 安装集成CDH5.13
ggplot2地图
Application system log structure of elastic stack
Redis源码剖析,狠狠地拿捏了,赶紧码住
一文掌握 JVM 面试要点
[ansible] the ansible shell encountered the problem of $symbol in awk when executing remote commands
【ansible】ansible shell 执行远程命令遇到awk 中$符号的问题
【impala】【报错解决】 Impala cannot read or execute the parent directory of dfs.domain.socket.path的解决方法
In some cases, error: (XX, XX) failed to resolve: XXXXXX.
Selection and application of capacitor in high speed circuit -- detailed explanation
Flat data to tree
ionic 中遇到的一些东西
R语言 sub()用法
Convert multidimensional object array to one-dimensional array
在PDF中插入文本水印
产品研发中第三方技术服务的管理
Mysql database development specification
C # basic interview questions (with answers)
Using OCR to reverse recognize text content in airtest
Redis source code analysis, hold it hard, and code it quickly