Encapsulation method of common modules in Node.js_node.js
Module loading and execution are packaged in Node.js so that the variables in the module file are in a closure and will not pollute global variables or conflict with others.
For front-end modules, our developers usually place the module code in a closure to avoid conflicts with others.
How to encapsulate modules common to Node.js and front-end, we can refer to Underscore.js implementation, which is a functional function module common to Node.js and front-end, view the code:
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we 're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined' ) {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
Determines whether the exports exist to determine whether the local variable _ is assigned to the exports. It is backward compatible with the old require() API. If in the browser , as a global object through a string identifier "_"; the complete closure is as follows:
(function() {
// Baseline setup
// --------------
/ / Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
}).call(this);
A closure is constructed through the function definition. call(this) is the function Called under this object to avoid internal variables from contaminating the global scope. In the browser, this points to the global object (window object), and the "_" variable is assigned to the global object "root._" for external calls.
Lo-Dash, which is similar to Underscore.js, also uses a similar solution, but is compatible with AMD module loading:
;(function() {
/**ES5 이전 환경에서 '정의되지 않음'에 대한 안전한 참조로 사용됨*/
var undefine;
/**값이 언어 유형 객체인지 확인하는 데 사용됩니다.*/
var objectTypes = {
'부울': false,
'함수': true,
'객체': true,
'번호': false,
'문자열': false,
'정의되지 않음 ': false
};
/**전역 개체에 대한 참조로 사용됩니다.*/
var root = (objectTypes[typeof window] && window) || this;
/**자유 변수 '내보내기' 감지 */
var freeExports = objectTypes[수출 유형] && 수출 && !exports.nodeType && 수출;
/**자유 변수 '모듈' 감지*/
var freeModule = objectTypes[모듈 유형] && 모듈 && !module.nodeType && module;
/**인기 있는 CommonJS 확장 `module.exports` 감지*/
var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/*-- ------------------------------------- -------*/
// Lo-Dash 노출
var _ = runInContext();
// r.js와 같은 일부 AMD 빌드 최적화 프로그램은 다음과 같은 조건 패턴을 확인합니다.
if (typeof 정의 == 'function' && typeof 정의.amd == 'object' && 정의.amd) {
// AMD 로더가 있는 경우에도 Lo-Dash를 전역 개체에 노출합니다.
// Lo-Dash가 타사 스크립트에 의해 삽입되었으며 의도되지 않은 경우
// 다음과 같이 로드되었습니다. 모듈. 전역 할당은 Lo-Dash
// `noContric()` 메서드를 통해 모듈에서 되돌릴 수 있습니다.
root._ = _;
// 익명 모듈로 정의하므로, 경로 매핑을 통해
// "밑줄" 모듈로 참조
정의(function() {
return _;
});
}
// 확인 for 빌드 최적화 프로그램이 `exports` 객체를 추가하는 경우 `define` 뒤 `exports`
else if (freeExports && freeModule) {
// Node.js 또는 RingoJS
if (moduleExports) {
(freeModule.exports = _)._ = _;
}
// Narwhal 또는 Rhino에서 -require
else {
freeExports._ = _;
}
}
else {
// 브라우저 또는 Rhino에서
root._ = _;
}
}.call(this));
再来看看Moment .js의 封装闭包主要代码:
(function (undefined) {
var moment;
// check for nodeJS
var hasModule = (typeof module !== 'undefined' && module.exports);
/************************************
Exposing Moment
************************************/
function makeGlobal(deprecate) {
var warned = false, local_moment = moment;
/*global ender:false */
if (typeof ender !== 'undefined') {
return;
}
// here, `this` means `window` in the browser, or `global` on the server
// add `moment` as a global object via a string identifier,
// for Closure Compiler "advanced" mode
if (deprecate) {
this.moment = function () {
if (!warned && console && console.warn) {
warned = true;
console.warn(
"Accessing Moment through the global scope is "
"deprecated, and will be removed in an upcoming "
"release.");
}
return local_moment.apply(null, arguments);
};
} else {
this['moment'] = moment;
}
}
// CommonJS module is defined
if (hasModule) {
module.exports = moment;
makeGlobal(true);
} else if (typeof define === "function" && define.amd) {
define("moment", function (require, exports, module) {
if (module.config().noGlobal !== true) {
// If user provided noGlobal, he is aware of global
makeGlobal(module.config().noGlobal === undefined);
}
return moment;
});
} else {
makeGlobal();
}
}).call(this);
从上面的几个例子可以看出,在封装Node.js和前端通用的模块时,可以使用以下逻辑:
if (typeof exports !== "undefined") {
exports.** = **;
} else {
this.** = **;
}
即,如果exports对象存在,则将局部变量装载在exports对象上,如果不存在,则装载在全局对象上。如果加上ADM规范的兼容性,那么多加一句判断:

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

Choosing a Docker image for Node may seem like a trivial matter, but the size and potential vulnerabilities of the image can have a significant impact on your CI/CD process and security. So how do we choose the best Node.js Docker image?

Node 19 has been officially released. This article will give you a detailed explanation of the 6 major features of Node.js 19. I hope it will be helpful to you!

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

How does Node.js do GC (garbage collection)? The following article will take you through it.

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!
