Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 import absolute path or custom path (typescript 2)

In our angular2 project, we put all our models ts files in a specific folder : /app/common/model/*. I can call them in my components with relatives paths, but it's very laborious. So 2 solutions, best is a custom path: StackOverflow: Relative Paths for SystemJS & ES module imports. But my IDE can not find the path. Here is my tsconfig :

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "built",
    "baseUrl": ".",
    "paths": {
      "mymodel/*": [
        "app/common/model/*"
      ]
    }
  }
}

In my component: import { Address } from 'mymodel/address.model';

IDE: [ts] Cannot find module.... I tried with or without * in path

Second solution : Stackoverflow: Angular 2, imports between different folders

IDE and compilation are ok, with full path in component : import { Address } from 'common/model/address.model';

And the tsconfig:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true,
    "outDir": "built",
    "baseUrl": ".",
    "paths": {
      "*": [
        "app/*",
        "node_modules/*"
      ]
    }
  }
}

But we have 404 on page load for all models. Maybe a config in systemjs file ?

In both cases, I think that "outdir" parameter is the problem, and we are missing something.

Many thanks for help!

Regards,

TypeScript: 2.0.6 Angular: 2.0.0

like image 208
lginlap Avatar asked Oct 31 '16 15:10

lginlap


1 Answers

After struggling by searching over internet n trying to understand what exactly problem and trying different troubleshooting option, I came to know baseUrl and Path how works together

Note: This solution is for Angular Cli 1.x . Not sure about other tool,

If you use baseUrl:"." like below it works in VScode but not while compiling

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": ".",
    "paths": {
      "@myproject/*": ["src/app/*"]
    }    
}

As far my understanding and my working app and checked in angular aio code, I suggest use as baseUrl:""src like below

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "baseUrl": "src",
    "paths": {
      "@myproject/*": ["app/*"],
      "testing/*": ["testing/*"]
    }    
}

By having base URL as source(src directory), compiler properly resolves modules.

I hope this helps to people resolve this kind of issue.

like image 176
Viraj Avatar answered Sep 20 '22 09:09

Viraj