Absolute module path resolution in TypeScript files in Visual Studio Code

To be able to use absolute paths from import in TypeScript using Visual Studio Code you should be using next version of TypeScript – typescript@next which is TypeScript v2. For that do the following:

  1. Install typescript@next via npm. For installing TypeScript v2.x

    npm i typescript@next -D

  2. In Visual Studio Code

    i) Go to menu FilePreferencesWorkspace Settings (This generates the .vscode directory at the project root and initializes the settings.json file.)

    ii) Put the following key:value pair in settings.json file

    "typescript.tsdk": "node_modules/typescript/lib"

  3. In tsconfig.json add following key:value pair to 'compilerOptions'

{
  "compilerOptions" : {
    "baseUrl": "./",
    "paths" : {
      "src/*": ["./src/*"]
    }
  }
}
  1. Reload Visual Studio Code

If you have the following directory structure:

+ node_modules
+ src
| + app
| |  + shared
| |  |  -service.ts
| |  -main.ts
+ typings
- tsconfig.json
- webpack.config.json
- package.json
- index.html

Then to import /src/app/shared/service.ts from main.ts you could now import {} from 'src/app/shared/service;

If you are using webpack and ts-loader for transpiling the .ts files, you should add following to the resolve section of webpack.config.js configuration file.

resolve: {
    extensions: ['', '.js', '.ts'],
    alias: {
      "src": path.resolve('./src')
    }
  }

Please refer to this for absolute module resolution.

Leave a Comment