自动导入路径别名错误

自动导入路径别名错误

问题描述:

在Angular 9应用程序中从带有路径别名的文件夹中自动导入服务/组件时,我遇到一个奇怪的问题.

I'm having strange issue when auto importing services/components from folder provided with path alias within Angular 9 application.

这些是我在 tsconfig.json

"paths": {
  "@core/*": ["app/core/*"],
  "@shared/*": ["app/shared/*"],
  "@state/*": ["app/state/*"]
}

然后在Core文件夹中,我重新导出 index 文件(app/core/index.ts)

Then in Core folder I'm reexporting all services in index file (app/core/index.ts)

export * from './sse/sse.service';
export * from './rack/rack.service';

现在,当我在构造函数中注入服务时,将使用错误的路径导入提供的自动导入选项:

Now when I'm injecting the service in a constructor the provided auto import option gets imported with faulty path:

// Incorrect - auto imported path
import { RackService } from '@core/';

// Correct path after manual fix
import { RackService } from '@core/index';

这只是一个小问题,但同时又很烦人,我不确定这是我一方的错误配置还是VS Code问题.任何的想法?可能是我在使用JEST而不是Jasmine时由JEST引起的,并且它也需要在package.json中定义别名.

It's just a minor issue but quite annoying at the same time and I'm not sure whether it's some incorrect configuration on my side, or VS Code issue. Any idea? Could it be caused by JEST as I'm using it instead of Jasmine and it requires to have aliases defined in package.json also.

  "jest": {
    "preset": "jest-preset-angular",
    "setupFilesAfterEnv": [
      "./src/setup-jest.ts"
    ],
    "moduleNameMapper": {
      "^@core/(.*)$": "<rootDir>/src/app/core/$1",
      "^@shared/(.*)$": "<rootDir>/src/app/shared/$1",
      "^@state/(.*)$": "<rootDir>/src/app/state/$1"
    }
  },

问题似乎是由第一个别名引起的:@core/*如果导出文件直接位于第一个别名上,则无法正确解决该问题等级.我想出了两种解决方法:

Seems like the issue is caused by the first alias: @core/* which can't be then resolved properly in case that the export file is directly on the first level. I came up with two workarounds:

1-将索引文件移动到名为services的文件夹,该文件夹仅包含index.ts. 现在,当自动导入(或TS Hero:组织导入)时,自动导入如下所示:

1 - Move the index file to a folder named services which contains only the index.ts. Now when auto importing (or TS Hero: Organizes imports) the auto import looks like this:

import {someService} from '@core/services'

2-将路径别名添加到tsconfig.*.json文件中,仅用于直接指向重新导出index.ts

2 - Add path alias to the tsconfig.*.json files just for the services pointing directly to re-export index.ts

"paths": {
  "@core/*": ["app/core/*"],
  "@core/services": ["app/core/index.ts"],
  "@shared/*": ["app/shared/*"],
  "@state/*": ["app/state/*"]
}

如果您使用的是Jest框架,则第二个选项还需要在package.json中进行更改.

Second option also requires changes in package.json if you are using Jest framework.

"moduleNameMapper": {
  "^@core/services$": "<rootDir>/src/app/core/index.ts",
  "^@core/(.*)$": "<rootDir>/src/app/core/$1",      
  "^@shared/(.*)$": "<rootDir>/src/app/shared/$1",
  "^@state/(.*)$": "<rootDir>/src/app/state/$1"
}

在这两种情况下,如果您在核心文件夹中有更深的其他重新导出index.ts,它仍将正确使用,例如@core/commons

In both cases, if you have any other re-export index.ts deeper in the core folder it will still be used correctly, e.g. @core/commons