Table of Contents
module-alias introduction
Introduction to the principle of module-alias
module-alias Step on the pit
module-alias/register流程
解决办法
Home Web Front-end JS Tutorial Learn more about module-alias in node.js (share some pitfall methods)

Learn more about module-alias in node.js (share some pitfall methods)

Dec 20, 2021 am 11:05 AM
node.js

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!

Learn more about module-alias in node.js (share some pitfall methods)

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);
Copy after login

Here is the configuration of tsconfig.json Content

"paths": {
  "@/*": [
    "src/*"
  ]
}
Copy after login

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 login
  • through the provided API interface addAlias, addAliases, addPath , add configuration

    moduleAlias.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-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.

The following is its source code, which is basically divided into two parts: path alias conversion native

_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)
}
Copy after login

Behind the seemingly simple, often Step on the pit

module-alias Step on the pit

Generally we will use

module-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

package.json

, and the inner package has its own package.json, simply put, uses the monorepo code organization method, the problem comes from this.

module-alias cannot properly resolve the path alias configured in package.json

I didn’t expect it to be a problem with the multi-layer project organization method at the beginning. The official website
module-alias/register

There is a description of how to use it:

Learn more about module-alias in node.js (share some pitfall methods)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-aliasinit方法的实现。为了节省篇幅,省略了部分细节

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])
    }
  }
  // 省略了部分内容
}
Copy after login

可以看重点部分,如果我们没有给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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

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!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

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

Let's talk about how to choose the best Node.js Docker image? Let's talk about how to choose the best Node.js Docker image? Dec 13, 2022 pm 08:00 PM

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.js 19 is officially released, let's talk about its 6 major features! Node.js 19 is officially released, let's talk about its 6 major features! Nov 16, 2022 pm 08:34 PM

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!

Let's talk in depth about the File module in Node Let's talk in depth about the File module in Node Apr 24, 2023 pm 05:49 PM

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.

Let's talk about the GC (garbage collection) mechanism in Node.js Let's talk about the GC (garbage collection) mechanism in Node.js Nov 29, 2022 pm 08:44 PM

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

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

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!

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

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

See all articles