找不到tsconfig路径

问题描述 投票:0回答:2

我正在使用nodejs应用程序,我想在tsconfig.json中配置路径,但是路径配置存在问题,我一直收到错误Error: Cannot find module '@environment'。可能是什么问题?

tsconfig

  {
    "compilerOptions": {
      "resolveJsonModule" : true,
      "target": "es6",
      "module": "commonjs" ,
      "lib": [
        "dom",
        "es6"
      ],
      "outDir": "build",
      "rootDir": "src",
      "removeComments": true ,
      "strict": true,
      "noImplicitAny": true,
      "baseUrl": "./",
      "paths": {
        "@lime/*": ["src/*"],
        "@environment": ["src/config/environment.ts"],
      },
      "esModuleInterop": true 
    }
  }

项目树:

src - config - environment.ts
    ...
    - index.js
package.json
tsconfig.json
...

environment.ts

import * as dotenv from 'dotenv';

dotenv.config();

interface Environment {
    port: number | string,
    baseUrl: string,
    databaseUri: string,
}

export const environment: Environment = {
    port: process.env.PORT!,
    baseUrl: process.env.BASE_URL!,
    databaseUri: process.env.DATABASE_URI!
}

index.ts中我将environment.ts导入为import { environment } from '@environment';,请问可能是错的吗?

javascript node.js typescript tsconfig
2个回答
0
投票

如果尝试使用nodets-node直接执行此操作,则应注意,默认情况下节点未解析tsconfig路径。如果您正在使用tsc进行构建(而不是使用webpack或类似工具来生成捆绑包),则可以像这样添加到您的依赖项tsconfig-paths中:

tsconfig-paths

然后执行以下代码:

npm install --save tsconfig-paths

如果直接将TS代码与node -r tsconfig-paths/register dist/index.js 一起使用,则可以使用:

ts-node

例如,建议在生产中将源与webpack捆绑在一起,并在捆绑时使用ts-node -r tsconfig-paths/register src/index.ts 之类的插件来解析路径。


0
投票

我不确定,我检查了文档。好像路径应该是目录。请尝试此组合。

tsconfig-paths-webpack-plugin)

并输入类似:

tsconfig-paths-webpack-plugin)

© www.soinside.com 2019 - 2024. All rights reserved.