Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use module-alias in node.js

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "how to use module-alias in node.js". The content is simple and clear. I hope it can help you solve your doubts. Let the editor lead you to study and learn this article "how to use module-alias in node.js".

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 function of path aliases in node environments. In general, front-end developers may be familiar with webpack's alias configuration, typescript's paths configuration, and so on, all of which provide army aliases. The path alias is yyds during code development, otherwise you will definitely freak out when you see this.. / xx path.

Webpack, a project packaged with webpack, will handle the conversion process from the configuration of path aliases in the source code to the packaged code. However, if you only use typescript to compile the project, although typescript can normally handle the configuration of path aliases in paths during compilation, it will not change the packaged code. As a result, there is still path alias configuration in the packaged code. See 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

"paths": {"@ / *": ["src/*"]}

You can see that the @ symbol still exists in the typescript-compiled code, but when the code is running, such as allowing in node, require does not properly recognize the symbol in the path, causing the corresponding module to be found and an exception is thrown.

This is also the purpose of the library module-alias.

Module-alias introduction

From the official website, the use of this library only takes two steps, which is really minimalist.

1. Path alias configuration: module-alias supports two path alias configuration methods

Add _ moduleAliases attribute to package.json for configuration

"_ moduleAliases": {"@": ". / src"}

Add configuration through the provided API interfaces addAlias, addAliases, addPath

ModuleAlias.addAliases ({'@': _ _ dirname +'. / src',})

2. When the project starts, you can first import the library: require (module-alias/register). Of course, if you choose to use API, you need to import the corresponding function for processing.

We usually use this library using the configuration path alias in package.json + require (module-alias/register) at the project entrance.

Introduction to the principle of module-alias

Module-alias implements the conversion of path aliases by overriding the method _ resolveFilename on the global object Module. To put it simply, it converts the path aliases by intercepting the native call to the _ resolveFilename method. When the real path of the file is obtained, the _ resolveFilename method of the original sound is called.

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

Var oldResolveFilename = Module._resolveFilenameModule._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, they often step on the hole.

Module-alias stepped on the pit

Generally, we use the module-alias library in node projects, because node projects generally convert from typescript to js code, but often do not package, because node projects generally do not need to be packaged, which is somewhat redundant. That's when you need module-alias to play.

But this project is a bit unusual. We use multi-tier code organization in the project. The outermost layer has a global package.json and the inner layer has its own package.json. To put it simply, it uses the code organization style of monorepo, and the problem arises from this.

Module-alias cannot properly resolve path aliases configured in package.json

At first, I really didn't think it was a problem of multi-tier project organization. The official website has a paragraph on the use of module-alias/register:

But it is true that I did not notice this instruction at that time, otherwise I would not have stepped on this hole. I should be careful next time if I read the instructions for use. However, for such a long period of instruction, I will probably not read it so carefully. After all, it seems that there will be no problem with such a simple method of use.

Module-alias/register process

Now that you have stepped on the pit, it is necessary to understand the cause of the pit and avoid stepping on it again and again. You can learn more about the implementation of the init method in module-alias. In order to save space, some details were omitted.

Function init (options) {/ / omitted some content 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`) / / focus on here! 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}} / / omitted part of content var aliases = npmPackage._moduleAliases | {} for (var alias in aliases) {if (aliases [alias] [0]! = =' /') {aliases [alias] = nodePath.join (base, aliases [alias])}} / / omitted part}}

You can take a look at the key section. If we don't give the base parameter, module-alias will by default look for the package.json file from the.. /.. / directory and the current directory, and.. /.. The priority of the package.json file in the directory is higher than that in the current directory. The priority setting here seems to be a little different from the normal priority logic. Generally, it will make the current directory have a higher priority in order to be more in line with the normal logic, so it will cause the package.json file under the current directory not to be loaded, resulting in an error due to the path alias configuration cannot be found.

It seems that many people have stepped on this point, and some people have mentioned issues, but no one seems to have responded to it for the time being.

Solution.

Register the path alias through API, or manually call the init method, pass in the base parameter, and specify the package.json file.

The above is all the contents of the article "how to use module-alias in node.js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

  • How to prevent JavaScript from being frame

    This article is about how to prevent JavaScript from being frame. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look. Prevent being frame

    © 2024 shulou.com SLNews company. All rights reserved.

    12
    Report