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" }
-
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-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!

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.


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

ZendStudio 13.5.1 Mac
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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
