Webpack resolve.root and TypeScript loader
Asked Answered
E

1

9

Our project is using the webpack resolve.root option to import modules with absolute paths. (avoiding something like ../../../module)
In its current state the project is using babel-loader which works perfectly fine.
My task is to migrate the app to Angular 2.
Therefor I am currently in the process of transitioning to TypeScript.
Somehow it seems like the ts-loader does not work in combination with the resolve.root option of the webpack config.

Example of the webpack.config.js

resolve: {
    root: [
        path.resolve('./node_modules'),
        path.resolve('./app'),
        path.resolve('./app/lib'),
    ]
},

Example of a module import
import AbstractListState from 'states/abstract_list_state';

The states directory is inside the app/lib directory.

Error when executing webpack

ERROR in ./app/mainViews/panel/panel.controller.ts
Module not found: Error: Cannot resolve module 'states/abstract_list_state' in C:\Users\...\Project\app\mainViews\panel
 @ ./app/mainViews/panel/panel.controller.ts 4:28-65
Exasperate answered 1/7, 2016 at 8:56 Comment(1)
See: github.com/Microsoft/TypeScript/issues/5039. A way to do this with tsconfig.json file will be implemented in TypeScript 2. Apparently, you can already test it today with typescript@next.Robbierobbin
N
2

Pre version 2.0 TypeScript will try to load modules with an absolute path from the node_modules directory. This is because TypeScript's module resultion is per default set to "node". Which means it works like node's require method. So, even if you're using webpack to build your app, TypeScript (and its compiler) will still want to load the files.

In order to let webpack import your modules with absolute path you have to go back and use the require method. This way TypeScript will let webpack import stuff. But of course you will not get any type-inference, autocomplete, ...

Or, you update to the TypeScript 2.0 beta and give this a try: https://github.com/Microsoft/TypeScript/wiki/What%27s-new-in-TypeScript#module-resolution-enhancements-baseurl-path-mapping-rootdirs-and-tracing

Nutter answered 12/8, 2016 at 10:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.