node.js - 路径在 tsconfig.app.json 中没有按预期工作

标签 node.js angular typescript

我正在使用 Angular 开发我的网站。我想为我的项目设置一个 BASE_API 取决于 proddev。因此,我在 environment

中添加了一些代码
  export const environment = {
    production: true,
    BASE_API: 'http://localhost:3000/',
  };

我想使用 import { environment } from '@environments/environment' 来导入而不是 import { environment } from '../../../environments/environment '; 所以我设置 tsconfig.app.json 如下所示

  {
    "extends": "../tsconfig.json",
    "compilerOptions": {
      "outDir": "../out-tsc/app",
      "module": "es2015",
      "baseUrl": "./",
      "paths": {
        "@angular/*": [
          "../node_modules/@angular/*"
        ],
        "@environments/*": [
          "../src/environments/*"
        ]
      }
    },
  }

我的项目结构如下

 src
    app
    environments
            environment.prod.ts
            environment.ts

但是,VSCode 显示:

ERROR in src/app/user/article/article.service.ts(3,29): error TS2307: Cannot find module '@environments/environment'.

我该如何解决这个问题?

最佳答案

这称为别名。为我们的应用程序和环境文件夹添加别名将使我们能够实现干净的导入,这将在我们的整个应用程序中保持一致。

要能够使用别名,您必须将 baseUrl 和路径属性添加到 tsconfig.json 文件。

So here in your code, just change your baseUrl to src

 {
    "extends": "../tsconfig.json",
    "compilerOptions": {
      "outDir": "../out-tsc/app",
      "module": "es2015",
      "baseUrl": "src",
      "paths": {
         "@app/*": ["app/*"],
         "@environments/*": ["environments/*"]
       }
    }
  }

Now you can import environment file like:

import { environment } from '@environments/environment

关于node.js - 路径在 tsconfig.app.json 中没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214681/

相关文章:

javascript - MongoDB -- client.open() 返回 "undefined in not a function"

Angular 2 AuthGuard + Firebase 身份验证

javascript - NPM 递归未满足的对等依赖关系

javascript - 我如何确定在 Angular Material 对话框中单击了哪个按钮

reactjs - 在 TextField 中使用日期类型时如何显示值?

typescript - 指定泛型类型之间的关系

json - Nodejs、Cloud Firestore 上传任务 - 身份验证错误 :Error: socket hang up

node.js - 如何在 Node+Typescript+VSCode 中查找缺少的 Await on Async 函数调用?

css - Bootstrap 模式弹出窗口使屏幕变暗,但屏幕的少数部分仍显示在同一级别并且不会变暗

javascript - 为什么console.log有时会打印出已导出的变量未定义?