Marc Marc - 3 months ago 47
TypeScript Question

Webpack resolve.root and TypeScript loader

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

Answer

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