我正在开发一个角(v12)库和一个小应用程序来测试它的结构如下:
├── projects │ ├── my-app │ │ ├── karma.conf.js │ │ ├── src │ │ ├── tsconfig.app.json │ │ └── tsconfig.spec.json │ └── my-lib │ ├── README.md │ ├── karma.conf.js │ ├── ng-package.json │ ├── node_modules │ ├── package-lock.json │ ├── package.json │ ├── src │ ├── tsconfig.lib.json │ ├── tsconfig.lib.prod.json │ └── tsconfig.spec.json └── tsconfig.json
在根./tsconfig.json中,我声明路径别名(据我理解,VS代码可以识别):
{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "forceConsistentCasingInFileNames": true, "strict": true, "noImplicitOverride": true, "noPropertyAccessFromIndexSignature": true, "noImplicitReturns": true, "noFallthroughCasesInSwitch": true, "sourceMap": true, "paths": { "my-lib": [ "dist/my-lib/my-lib", "dist/my-lib" "@services/*": [ "projects/my-lib/src/lib/services/*" "declaration": false, "downlevelIteration": true, "experimentalDecorators": true, "moduleResolution": "node", "importHelpers": true, "target": "es2017", "module": "es2020", "lib": [ "es2020", "dom" "angularCompilerOptions": { "enableI18nLegacyMessageIdFormat": false, "strictInjectionParameters": true, "strictInputAccessModifiers": true, "strictTemplates": true }
在./project/my-lib/tsconfig.lib.json中,我再次声明路径别名(据我所知,ng-packagr编译器将解释路径别名):
{ "compileOnSave": false, "compilerOptions": { "baseUrl": "./", "outDir": "./dist/out-tsc", "paths": { "@services/*": [ "src/lib/services/*" ], "sourceMap": true, "declaration": false, "module": "es2015", "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "target": "es5", "typeRoots": [ "node_modules/@types" "lib": [ "es2017", "dom" }
./angular.json引用tsconfig.lib.json:
{ "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "projects": { "my-lib": { "projectType": "library", "root": "projects/my-lib", "sourceRoot": "projects/my-lib/src", "prefix": "lib", "architect": { "build": { "builder": "@angular-devkit/build-angular:ng-packagr", "options": { "project": "projects/my-lib/ng-package.json" "configurations": { "production": { "tsConfig": "projects/my-lib/tsconfig.lib.prod.json" "development": { "tsConfig": "projects/my-lib/tsconfig.lib.json" "defaultConfiguration": "production"
图书馆正在编译,没有任何错误。
例如,当我在我的-app中导入库并想导入一个服务时,它不会解析路径别名:
./node_modules/my-lib/fesm2015/my-lib.mjs:11:0-56 - Error: Module not found: Error: Can't resolve '@services/my-lib/my-lib.service' in '/Users/***/projects/ANGULAR/angular-tour-of-heroes/node_modules/my-lib/fesm2015' Error: node_modules/my-lib/lib/custom-page/custom-page.component.d.ts:2:30 - error TS2307: Cannot find module '@services/my-lib/my-lib.service' or its corresponding type declarations.