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:
-
Install typescript@next via npm. For installing TypeScript v2.x
npm i typescript@next -D
-
In Visual Studio Code
i) Go to menu File → Preferences → Workspace Settings (This generates the
.vscode
directory at the project root and initializes thesettings.json
file.)ii) Put the following
key:value
pair insettings.json
file"typescript.tsdk": "node_modules/typescript/lib"
-
In
tsconfig.json
add following key:value pair to'compilerOptions'
{
"compilerOptions" : {
"baseUrl": "./",
"paths" : {
"src/*": ["./src/*"]
}
}
}
- 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.