简体   繁体   English

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

[英]paths is not working in tsconfig.app.json as expected

I am using Angular to develop my website.我正在使用 Angular 来开发我的网站。 And I wanna set a BASE_API for my project depends on prod or dev .我想为我的项目设置一个BASE_API取决于proddev Therefore, I add some code in environment因此,我在environment中添加了一些代码

  export const environment = {
    production: true,
    BASE_API: 'http://localhost:3000/',
  };

And I wanna use import { environment } from '@environments/environment' to import instead of import { environment } from '../../../environments/environment';我想使用import { environment } from '@environments/environment'导入而不是import { environment } from '../../../environments/environment'; So I set tsconfig.app.json just like below所以我像下面一样设置tsconfig.app.json

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

And my project structure as below我的项目结构如下

 src
    app
    environments
            environment.prod.ts
            environment.ts

However, the VSCode shows:但是,VSCode 显示:

ERROR in src/app/user/article/article.service.ts(3,29): error TS2307: Cannot find module '@environments/environment'. src/app/user/article/article.service.ts(3,29) 中的错误:错误 TS2307:找不到模块“@environments/environment”。

How can I fix this problem?我该如何解决这个问题?

I also had issues with this.我也遇到了这个问题。 Some paths were even written out exactly the same, but one path worked, and the other didn't.有些路径甚至写出完全相同,但一条路径有效,而另一条则没有。 Spent a few hours researching and trying all kinds of different stuff, but it seemed that the solution was easier than I thought.花了几个小时研究和尝试各种不同的东西,但似乎解决方案比我想象的要容易。 The only thing I had to do was restart the TypeScript server.我唯一要做的就是重新启动 TypeScript 服务器。

A) If you have an active ng serve, restart the ng serve A) 如果你有一个活跃的 ng serve,重启 ng serve

  1. CTRL + C CTRL + C
  2. ng serve服务

B) If you don't have an active ng serve, do this: B) 如果您没有有效的 ng 发球,请执行以下操作:

  1. Command + Shift + P命令 + Shift + P
  2. Search for " TypeScript: Restart TS Server "搜索“ TypeScript:重启 TS 服务器
  3. Hit enter按回车

This is called alias. 这称为别名。 Aliasing our app and environments folders will enable us to implement clean imports which will be consistent throughout our application. 别名我们的应用程序和环境文件夹将使我们能够实现在整个应用程序中保持一致的干净导入。

To be able to use aliases you have to add baseUrl and paths properties to tsconfig.json file. 为了能够使用别名,您必须将baseUrl和paths属性添加到tsconfig.json文件中。

So here in your code, just change your baseUrl to src 所以在你的代码中,只需将baseUrl更改为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

This is one of top search results in google for this question, so I thought I'd add what worked for me...这是这个问题在谷歌中的顶级搜索结果之一,所以我想我会添加对我有用的东西......

restart 'ng serve'重新启动'ng服务'

Yep, that was it.是的,就是这样。 Turns out changes to 'tsconfig.json' are not picked up dynamically.原来对 'tsconfig.json' 的更改不是动态获取的。 Sometimes we go days changing things and forget that 'ng serve' is dynamically picking things up and recompiling, so it wouldn't be an obvious first choice that this is something it wouldn't pick up.有时我们花了几天时间改变事情并忘记 'ng serve' 是动态地挑选和重新编译的东西,所以这不是一个明显的第一选择,这是它不会挑选的东西。

The solution is to let the vscode recognition tsconfig.app.json解决方法是让vscode识别tsconfig.app.json

Add file tsconfig.json添加文件 tsconfig.json

 app
    src
    tsconfig.json
    tsconfig.app.json

tsconfig.json tsconfig.json

{
    "files": [],
    "references": [
        { "path": "./tsconfig.app.json" },
       
    ]
}

Solution解决方案

If you have tried all of the suggested solutions and none of them worked:如果您已经尝试了所有建议的解决方案,但都没有奏效:

On startup, React cleans up tsconfig.json to only keep the configuration that it expects to be there for it to work properly.在启动时,React 会清理tsconfig.json仅保留它希望在那里正常工作的配置 paths property is one of those that it removes when it starts up. paths属性是它在启动时删除的属性之一。

In order for it to be recognized, we need to do the following:为了让它被识别,我们需要做以下事情:

  1. Create a tsconfig.paths.json file in your root directory.在您的根目录中创建一个tsconfig.paths.json文件。
  2. Put the following code in it, modifying the baseUrl and paths to fit your specific case.将以下代码放入其中,修改baseUrlpaths以适合您的特定情况。
// tsconfig.paths.json
{
    "compilerOptions": {
      "baseUrl": "./",
      "paths": {
        "@angular/*": [
          "../node_modules/@angular/*"
        ],
        "@environments/*": [
          "../src/environments/*"
        ]
      }
    }
}
  1. Extend this file from your tsconfig.json从您的tsconfig.json扩展此文件
// Example tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "types": ["@emotion/react/types/css-prop", "node" ]
  },
  "include": [
    "src"
  ],
  "extends": "./tsconfig.paths.json" // 👈 add this line
}

Edit:编辑:

If you are getting an error when starting your application (eg Module not found: alias path), you need to configure your webpack settings by adding your aliases.如果您在启动应用程序时遇到错误(例如找不到模块:别名路径),您需要通过添加别名来配置 webpack 设置。

alias: {
  ['@your-path']: path.resolve(__dirname, 'src/your-path'),
}

If you cannot directly configure webpack (eg you use cra):如果不能直接配置webpack(比如你用cra):

  1. npm i --save-dev react-app-rewired
  2. Replace your scripts with将您的脚本替换为
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject"
}
  1. Create a config-overrides.js file in your root directory:在您的根目录中创建一个config-overrides.js文件:
const path = require('path');

module.exports = function override(config, env) {
  // Enable path aliases
  config.resolve = {
    ...config.resolve,
    alias: {
      ...config.resolve.alias,
      ['@utils']: path.resolve(__dirname, 'src/utils'),
      ['@utils/test-utils']: path.resolve(__dirname, 'src/utils/test-utils')
    }
  };

  return config;
};

  1. run npm start运行npm start

Note: There are many suggestions of using react-app-rewire-alias , but only the above configuration worked in my case.注意:有很多使用react-app-rewire-alias建议,但只有上述配置适用于我的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM