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 webpackwebpack 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.jsonAdd the_moduleAliasesattribute to configure"_moduleAliases": { "@": "./src" } -
through the provided API interface
addAlias,addAliases,addPath, add configurationmoduleAlias.addAliases({ '@' : __dirname + './src', });
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-aliasBy 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!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software







