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
.
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 configuration
moduleAlias.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.
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## 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
中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!