5

我正在使用v3.6.4带有以下tsconfig.json代码段的打字稿:


  "compilerOptions": {
    "moduleResolution": "node",
    "baseUrl": "./src",
    "paths": {
      "@config/*": ["config/*"],
      "@config": ["config"],
    }
  }

package.json 中的模块别名:

  "_moduleAliases": {
    "@config": "dist/config"
  }

我有以下文件夹结构:

src
 |-config
     |-index.ts
 |-app
     |index.ts
     |logic.ts
 |-dist

现在在 app/index.ts 中,如果我这样做:

import 'module-alias/register';
import config from '@config';

我的npm start命令是:

"start": "node -r ts-node/register ./src/app/index.ts",

tsc将编译成功,但npm start会报错:

Error: Cannot find module '@config' in src/app/logic.ts

解决这个问题的唯一方法是添加

import 'module-alias/register';

src/app/logic.ts

似乎我必须import 'module-alias/register'在我做别名的每个文件中添加?这是一种配置方法吗?

4

2 回答 2

3

@2021

对我来说,我遇到了完全相同的问题:打字稿只允许我在每个模块都import 'module-alias/register';具有这样的模块别名时才使用模块别名。

花了将近一整天后,我明白了:

tsc不会帮助编译这些装饰器。因此,您必须确保 js 编译代码的每个使用者都已确认并知道如何使用别名处理这些模块导入。

IE:

node index.js
=>
node -r module-alias/register index.js

///

mocha .
=>
mocha -r module-alias/register .
于 2021-06-24T14:08:49.970 回答
1

The solution to this is quite simple:

in the root file, like app/index.ts, put the import 'module-alias/register'; to the end of all the other imports and you won't need to put it in every file. It didn't work for me because I put that import before all other imports, not after.

For example:

import express from 'express';
import corsFilter from 'cors';
...
import 'module-alias/register'; // This has to be after all other imports
于 2020-11-12T18:34:53.813 回答