Typescript 路径在 Express 项目中不起作用

Typescript paths not working in an Express project

我正在尝试使用 TypeScript 的路径功能,这样我就不需要再使用相对导入了。

这是我的 tsconfig.json 文件:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "outDir": "./dist",
    "rootDir": ".",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "baseUrl": ".",
    "allowJs": true,
    "paths": {
      "*": ["node_modules/*", "src/*"],
      "@config/*": ["src/config/*"],
      "@controllers/*": ["src/controllers/*"],
      "@middlewares/*": ["src/middlewares/*"],
      "@models/*": ["src/models/*"],
      "@routes/*": ["src/routes/*"],
      "@types/*": ["src/types/*"],
      "@utils/*": ["src/utils/*"]
    }
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "firebase-config.json", "webpack.config.js"]
}

这是我的 package.json 文件:

{
  "name": "express-ts-boilerplate",
  "version": "0.1.0",
  "description": "Express Typescript Boilerplate",
  "main": "src/server.js",
  "author": "Sriram R",
  "scripts": {
    "start": "NODE_ENV=production node dist/src/app.js",
    "dev": "nodemon src/app.ts",
    "build": "tsc -p .",
    "test": "mocha --exit -r ts-node/register src/tests/*.spec.ts"
  },
  "dependencies": {
    // Dependencies here
  },
  "devDependencies": {
    // Dependencies here
  },
}

所以现在在我的一个文件中,我尝试 @config/typeConfig 但我只是得到 cannot find module 错误。

可能是因为 nodemon 但它对 ts-node 也不起作用。 我怎样才能让它工作?

注意:对于 nodemon 的工作示例,请跳至我的回答的第二部分。

如果您的意思是一旦编译了文件和 运行 应用程序,就找不到模块,那么请查看此线程:Module path maps are not resolved in emitted code

"paths" is designed for use with loaders that allow remapping

假设我的 tsconfig.json:

中有这条路径
"paths": {
      "@config/*": ["src/config/*"]
    }

我需要一个在文件中使用该路径的文件

import test from '@config/test';

查看编译后的文件,我得到

var test_1 = __importDefault(require("@config/test"));

如你所见,路径没有解析,还是@config/test。使用 nodemonts-node.

测试您的应用程序时也会发生同样的事情

此外,您需要使用 Typescript 路径别名解析器,例如tspath

The TypeScript compiler will be able to resolve the paths so this will compile without problems, however the JavaScript output will not be possible to execute by Node nor a Web Browser, why? the reason is simple!

The JavaScript engine does not know anything about the compile time TypeScript configuration.

In order to run your JavaScript code, the path aliases now needs to be made into relative paths again, here is when TSPath comes into play.


话虽这么说,如果你想让 nodemon 工作,下面的配置就可以了。事先,确保你安装了 tsconfig-paths.

npm i tsconfig-paths

Use this to load modules whose location is specified in the paths section of tsconfig.json. Both loading at run-time and via API are supported. (...) If you require this package's tsconfig-paths/register module it will read the paths from tsconfig.json and convert node's module loading calls into to physcial file paths that node can load.

完美,我们将执行node-r tsconfig-paths/register将路径转换为物理文件路径,-r ts-node/register动态执行ts文件,nodemon 将在更改后重新启动应用程序。

在你的package.json中,你需要添加这个(根据需要修改):

    "nodemonConfig": {
          "ignore":
            [
              "**/*.test.ts",
              "**/*.spec.ts",
              ".git",
              "node_modules"
            ],
          "watch": [
            "src"
          ],
          "exec": "node -r tsconfig-paths/register -r ts-node/register ./src/server.ts",
          "ext": "ts, js"
        },
    "scripts": {
          "dev": "nodemon"
        }

注意为 nodemon 添加的配置。

最后

npm run dev

事情应该会 运行 顺利进行。

完全正确。

但如果您想要 one-line 解决方案:

nodemon -e ts,js --exec ts-node -r tsconfig-paths/register ./src/server.ts

只需记得安装tsconfig-paths/register:

npm i -D tsconfig-paths

发展

npm i -save-dev tsconfig-paths/register

tsconfig.json

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

package.json

"scripts": {
  dev: "ts-node -r tsconfig-paths/register src/index.ts"
}

建造

npm i -save-d ttypescript @zerollup/ts-transform-paths

tsconfig.json

{
 "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@src/*": ["src/*"],
    },   
  }
 "plugins": [
      {
          "transform": "@zerollup/ts-transform-paths",
      }
  ],
}

package.json

"scripts": {
  build: "ttsc -P ./tsconfig.json"
}

在我的特殊情况下使用“tsc-alias”这些是我的步骤:

  1. 安装包npm install --save-dev tsc-alias
  2. 将我在package.json中编译的命令更改为"build": "tsc && tsc-alias"
  3. 修改我的 tsconfig.json 因为我没有 outDir,所以它看起来像这样:
{
   "compilerOptions": {
      "outDir": "miniprogram",
      "baseUrl": "miniprogram",
      "paths": {
       "lib / *": ["./lib/*"]
     },
...
}

注意: 如果我不添加 outDir 它会给我以下错误:"compilerOptions.outDir 未设置

然后在导入时我会这样做: import {Util} from "lib/my/path/util";

TL;DR: 删除所有 .js 文件

对于那些没有使用上述正确解决方案进行管理的人:

在我的项目中,我在每个 .ts 文件下创建了 'leftover' 个 .js 文件(在过去的某个时候)。 运行 nodemon(反过来应该使用 tsc)没有覆盖这些文件,我不断收到与 Cannot resolve module.

相同的 require stack 错误

删除所有 .js 文件为我修复了它。

有关如何以安全(大概)的方式实际执行此操作的更多信息,请参阅此答案:Find (and delete) all files with a specified extension。请确保您在删除文件之前确实查看了文件列表。