简体   繁体   中英

Specify path in tsconfig.json instead of using relative path : ERROR in src/app/app.module.ts: error TS2307: Cannot find module '@…'

I am trying to resolve the relative path imports for component using the path property of tsconfig.json . But, it gives the below error. Not sure, why it giving this error. May it due to that src/components folder is not inside the src/app folder ?

Actual Error :

ERROR in src/app/app.module.ts(12,33): error TS2307: Cannot find module '@advent/components'.

1) This is my folder structure :

src
  - app 
      - app.module.ts
      - app.component.ts
      - app.component.html
      - app.component.css
  - components
      - modals
          - modals.component.ts
          - modals.component.html
          - modals.component.css 
      - index.ts
tsconfig.json

2) tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./src",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "@advent/components/*": [
        "components/*"
      ]
    }
  }
}

3) index.ts

export * from './modals/modals.component';

4) modals.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'modals',
  templateUrl: './modals.component.html',
  styleUrls: ['./modals.component.scss']
})
export class ModalsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

5) app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';

// Importing Components
import { AppComponent } from './app.component';
import { ModalsComponent } from '@advent/components';


@NgModule({
  declarations: [
    AppComponent,
    ModalsComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Update below line in tsconfig.json

  1. If tsconfig.json file is located in src folder and baseUrl = "."
"@advent/components/*": [ "./components/*" ]
  1. If tsconfig.json file is located outside src folder and baseUrl = "."
"@advent/components/*": [ "./src/components/*" ]
  1. If tsconfig.json file is located outside src folder and baseUrl = "./src"
"@advent/components/*": [ "./components/*" ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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