【问题标题】:Typescript paths not working in an Express project打字稿路径在 Express 项目中不起作用
【发布时间】:2020-01-30 21:11:34
【问题描述】:

我正在尝试使用 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。 我怎样才能让它工作?

【问题讨论】:

  • “所以现在在我的一个文件中”。哪个文件?它位于哪里?
  • 它位于 src 文件夹下。我要导入配置变量的服务器文件。
  • 很奇怪。我试图复制你的问题,它在这里工作正常。你怎么会有nodemon src/app.ts?
  • 因为我在开发过程中使用nodemon运行。这就是我怀疑问题所在。
  • 不应该是nodemon dist/src/app.js吗?

标签: typescript nodemon ts-node


【解决方案1】:

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

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

在我的项目中,我在每个 .ts 文件下(在过去的某个时间点)创建了“剩余的”.js 文件。 运行nodemon(它应该使用tsc)并没有覆盖这些文件,并且我不断收到与Cannot resolve module相同的要求堆栈错误。

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

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

【讨论】:

    【解决方案2】:

    jperl's answer 完全正确。

    但如果您想要一个单行解决方案:

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

    只需记住安装tsconfig-paths/register

    npm i -D tsconfig-paths
    

    【讨论】:

    • 感谢您的回答,但您最好提到我们必须安装tsconfig-paths
    • 感谢您的反馈。我将编辑我的答案
    • 应该说:npm i -D tsconfig-paths 而不是 npm i -D tsconfig-paths/register ?
    • 绝对正确!我会解决的。
    【解决方案3】:

    在我的特殊情况下使用“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 is not set"

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

    【讨论】:

      【解决方案4】:

      发展

      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"
      }
      

      【讨论】:

        【解决方案5】:

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

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

        “路径”设计用于允许重新映射的加载器

        假设我的 tsconfig.json 中有这条路径:

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

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

        import test from '@config/test';
        

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

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

        如您所见,路径尚未解析,它仍然是@config/test。使用 nodemonts-node 测试您的应用时也会发生同样的事情。

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

        TypeScript 编译器将能够解析路径,因此这将毫无问题地编译,但是 JavaScript 输出将无法由 Node 或 Web 浏览器执行,为什么?原因很简单!

        JavaScript 引擎对编译时 TypeScript 配置一无所知。

        为了运行你的 JavaScript 代码,路径别名现在需要再次变成相对路径,这就是 TSPath 发挥作用的时候。


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

        npm i tsconfig-paths
        

        使用它来加载位置在 tsconfig.json 的路径部分中指定的模块。支持在运行时加载和通过 API 加载。 (...) 如果您需要此包的 tsconfig-paths/register 模块,它将从 tsconfig.json 读取路径并 将节点的模块加载调用转换为物理文件路径 该节点可以加载。

        完美,我们将执行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
        

        一切都应该顺利进行。

        【讨论】:

        • 很难找到这个。我真的很安全
        猜你喜欢
        • 1970-01-01
        • 2021-08-05
        • 2019-06-14
        • 2021-09-11
        • 2021-10-28
        • 2020-08-12
        • 2016-06-16
        • 2018-12-25
        • 1970-01-01
        相关资源
        最近更新 更多