Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I configure Angular 5 to support module aliases?

I would like to alias some folders throughout my project to simplify imports (and actually test my own library before publishing).

So instead of:

import { MyClass } from '../mylib/src/somefolder';

I want to achieve this:

import { MyClass } from '@mylib';

I have configured my tsconfig.json as follows:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@mylib": ["../mylib/src/"],
    }
    ...
  }
}

I have an index.ts file in my library's src folder as follows:

export { MyClass } from "./MyClass";

I am using a new project generated with ng new XX and ejected with ng eject.

I have tried the tsconfig-paths-webpack-plugin and the awesome-typescript-loader's equivalent, but I am unable to get any combination to work no matter how closely I follow the instructions provided for each - I always get:

ERROR in src/app/app.component.ts(3,40): error TS2307: Cannot find module '@mylib'.

What am I missing?

like image 833
joshcomley Avatar asked Feb 11 '18 16:02

joshcomley


1 Answers

After much investigation I solved it through trial and error.

The baseUrl must be ./src for this to work (where src is the root app source code folder in an ejected Angular 5 app), and the paths must be changed to traverse up one more level:

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@mylib": [
        "../../mylib/src"
      ]
    },
    ...
}

Anything higher in the directory structure than that fails. I am sure someone will be able to explain why this is at some point!

like image 121
joshcomley Avatar answered Nov 02 '22 22:11

joshcomley