0

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?

1
  • I've been looking into this some months back and it was possible by making node module that exports stuff (kinda like you import from '@angular'). I found this: github.com/Microsoft/TypeScript/issues/5039, and it seams some options have been added to tsconfig. I'll have to look into it too (; Commented Oct 19, 2016 at 8:30

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yea, I just changed it in one file, the rest are still with ../../
Try without paths, I just used baseUrl.
Ah, sick bro. This will help me out a ton! Wish I could upvote you x100 :D

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.