Search code examples
angularwebpack-2

Absolute path doesn't work in webpack 2


I have been trying to get absolute paths work with webpack 2 in my angular 2 project. I used this as my boilerplate code. And to make it work with absolute path I tried the following in webpack.config.ts:

config.resolve = {
    extensions: ['.ts', '.js', '.json'],
    modules: [path.resolve('./src'), 'node_modules']
  };

And in webpack.d.ts:

resolve?: {
    extensions?: Array<string>;
    modules?: Array<string>;
  };

But when I try import {AppComponent} from 'app/app.component' it doesn't work, it errors out with Cannot find module 'app/app.component'... I can't figure out what is causing this. Please help.

P.S. I also tried the solution suggested here. But couldn't get it to work.

EDIT 1

Please find my try to make this work here, https://github.com/dsasidhar/angular-webpack2-starter


Solution

  • Webpack Typescript loader resolves module paths considering the tsconfig. So you have to add this line to your tsconfig.json file:

    "baseUrl": "./src" // Or whatever is your root
    

    If you have a tsconfig.app.json inside the src folder, you should also specify a baseUrl there. I suggest not having more than one tsconfig file as tool support for that is not very well.

    More information on Typescript module resolution here. Check out Base URL and Path Mapping sections.