Faulty auto import with path alias

◇◆丶佛笑我妖孽 提交于 2021-01-27 07:19:52

问题


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

Those are my aliases defined in tsconfig.json

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

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';

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

回答1:


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 - 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 - 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/*"]
}

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

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



来源:https://stackoverflow.com/questions/60522723/faulty-auto-import-with-path-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!