


Learn more about module-alias in node.js (share some pitfall methods)
This article will take you to understand module-alias in node.js, introduce the principle of module-alias, and a common problem (pit) of module-alias. I hope it will be helpful to everyone!
First of all, it is necessary to introduce what module-alias
is. Here is its official website link (official website address https://github.com/ilearnio/ module-alias).
To put it simply, module-alias
provides the path alias function in the node
environment. Generally, front-end developers may be familiar with alias
configuration of webpack
, paths
configuration of typescript
, etc. These all provide army aliases. Function. The path alias is yyds during the code development process, otherwise you will definitely go crazy when you see this ../../../../xx
path.
Projects packaged using webpack
webpack
itself will handle the conversion process from the configuration of the path alias in the source code to the packaged code, but if you simply use typescript
Compiled projects, although typescript
can handle the configuration of path aliases in paths
normally during the compilation process, it will not change the packaged code, causing There is still a path alias configuration in the packaged code. Look at a code compiled by typescript
:
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); require("./module-alias-register"); var commands_1 = require("@/commands"); var package_json_1 = require("../package.json"); (0, commands_1.run)(package_json_1.version);
Here is the configuration of tsconfig.json
Content
"paths": { "@/*": [ "src/*" ] }
You can see that in the code compiled by typescript
, the @ symbol still exists. However, when the code is running, for example, it is allowed in node
, require
cannot properly recognize this symbol in the path, causing the corresponding module to be found and an exception to be thrown.
This is also the purpose of module-alias
.
module-alias introduction
From the official website, the method of using this library only requires two steps, and it is really extremely simple.
1. Path alias configuration: module-alias
Supports two path alias configuration methods
in
package.json
Add the_moduleAliases
attribute to configure"_moduleAliases": { "@": "./src" }
Copy after loginthrough the provided API interface
addAlias
,addAliases
,addPath
, add configurationmoduleAlias.addAliases({ '@' : __dirname + './src', });
Copy after login
2. First import the library when the project starts: require(module-alias/register)
, of course choose to use The API method needs to import the corresponding function for processing
Generally we use package.json
to configure the path alias project entryrequire(module-alias/register)
To use this library.
Introduction to the principle of module-alias
module-alias
By overriding the methods on the global object Module
_resolveFilename
realizes the conversion of path aliases. Simply put, it intercepts the native _resolveFilename
method call and converts the path alias. When the real path of the file is obtained, the original # is called. ##_resolveFilename method.
_resolveFilenamecall
var oldResolveFilename = Module._resolveFilename Module._resolveFilename = function (request, parentModule, isMain, options) { for (var i = moduleAliasNames.length; i-- > 0;) { var alias = moduleAliasNames[i] if (isPathMatchesAlias(request, alias)) { var aliasTarget = moduleAliases[alias] // Custom function handler if (typeof moduleAliases[alias] === 'function') { var fromPath = parentModule.filename aliasTarget = moduleAliases[alias](fromPath, request, alias) if (!aliasTarget || typeof aliasTarget !== 'string') { throw new Error('[module-alias] Expecting custom handler function to return path.') } } request = nodePath.join(aliasTarget, request.substr(alias.length)) // Only use the first match break } } return oldResolveFilename.call(this, request, parentModule, isMain, options) }
Behind the seemingly simple, often Step on the pit
module-alias Step on the pit
Generally we will usemodule-alias## in the node
project #Library, because node
projects are generally converted from typescript
to js
code, but are often not packaged because node
There is generally no need for packaging in projects, which seems a bit redundant. This is when module-alias
comes into play. But this project is a bit unusual. We use a multi-layer code organization method in the project. The outermost layer has the global
, and the inner package has its own package.json
, simply put, uses the monorepo
code organization method, the problem comes from this
.
I didn’t expect it to be a problem with the multi-layer project organization method at the beginning. The official websitemodule-alias/register
There is a description of how to use it:
But I really didn’t pay attention to this description at the time, otherwise I wouldn’t have stepped into this trap. , you should read the instructions carefully next time, but for such a long instruction manual, there is a high probability that you will not read it so carefully. . . After all, it seems that there will be no problems with such a simple method of use, right
module-alias/register流程
既然踩坑了,就有必要了解一下踩坑的原因,避免反复踩坑才好。可以详细了解下module-alias
中init
方法的实现。为了节省篇幅,省略了部分细节
function init (options) { // 省略了部分内容 var candidatePackagePaths if (options.base) { candidatePackagePaths = [nodePath.resolve(options.base.replace(/\/package\.json$/, ''))] } else { // There is probably 99% chance that the project root directory in located // above the node_modules directory, // Or that package.json is in the node process' current working directory (when // running a package manager script, e.g. `yarn start` / `npm run start`) // 重点看这里!!! candidatePackagePaths = [nodePath.join(__dirname, '../..'), process.cwd()] } var npmPackage, base for (var i in candidatePackagePaths) { try { base = candidatePackagePaths[i] npmPackage = require(nodePath.join(base, 'package.json')) break } catch (e) { // noop } } // 省略了部分内容 var aliases = npmPackage._moduleAliases || {} for (var alias in aliases) { if (aliases[alias][0] !== '/') { aliases[alias] = nodePath.join(base, aliases[alias]) } } // 省略了部分内容 }
可以看重点部分,如果我们没有给base参数,module-alias
默认会从../../
目录和当前目录下找寻package.json
文件,而且../..
目录下的package.json
文件的优先级比当前目录下的优先级还要高,这里的优先级设置似乎和正常的优先级逻辑有点差别,一般都会让当前目录的优先级比较高才比较符合正常逻辑,所以会导致加载的不是当前目录下的package.json
文件,而导致找不到路径别名配置而出错。
关于这点似乎有不少人踩坑了,还有人提了issues,但是似乎暂时并没有人回应。
解决办法
通过API方式注册路径别名,或者手动调用init
方法,传入base参数,指定package.json
文件.
似乎只有踩坑了,才会更深入的了解
更多node相关知识,请访问:nodejs 教程!!
The above is the detailed content of Learn more about module-alias in node.js (share some pitfall methods). For more information, please follow other related articles on the PHP Chinese website!

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.

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

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!

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package
