Chrillewoodz
Chrillewoodz

Reputation: 28368

Angular 2 can you import something from the project root instead of having to go back using ../

I've found that I'm slowly digging my own grave, because the deeper my folder structure gets, the further back I must go each time I need to import a module from my root component:

import {ComponentsModule, SharedModule} from '../../../../../../shared';

Since that view also have child views then it will become even longer.

I looked at this question which suggests that this is not possible with Angular 2 as of now. Yet it seems so odd to me that there wouldn't be a way to achieve something like this instead:

import {ComponentsModule, SharedModule} from 'src/app/shared';

Is this a feature that will come in the future or is this already possible somehow?

EDIT: As per @Sasxa's suggestion I did this:

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

But now when I try to start Angular CLI I get a whole bunch of errors, main ones being these: ERROR in Entry module not found: Error: Recursion in resolving and ERROR in multi main Module not found: Error: Recursion in resolving.

Is something missing?

Upvotes: 0

Views: 368

Answers (1)

Sasxa
Sasxa

Reputation: 41314

It seems this could be done with paths and baseUrl compiler options from tsconfig.json. https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

Here's an example from docs:

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "*": [
                    "*",
                    "generated/*"
                ]
            }
    }
}

This tells the compiler for any module import that matches the pattern "*" (i.e. all values), to look in two locations:

  • "*": meaning the same name unchanged, so map => \
  • "generated*" meaning the module name with an appended prefix “generated”, so map => \generated\

Should be available in TypeScript 1.9+


Update:

I just tried it: adding "baseUrl": "." allows me to import {...} from 'app/shared' anywhere in my app (my tsconfig.json is in the src\ folder). Compiles without any errors and works with Angular CLI.

Upvotes: 2

Related Questions