typescript-transform-paths

Transforms absolute imports to relative from paths in your tsconfig.json
Install
npm:
npm i -D typescript-transform-paths
yarn:
yarn add -D typescript-transform-paths
Add it to plugins in your tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@utils/*": ["utils/*"]
},
"plugins": [{ "transform": "typescript-transform-paths" }]
}
}
Transforming declaration paths
If you want to generate declaration (.d.ts) files with transformed paths you have to
modify your tsconfig.json file:
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@utils/*": ["utils/*"]
},
"declaration": true,
"plugins": [
{ "transform": "typescript-transform-paths" },
{ "transform": "typescript-transform-paths", "afterDeclarations": true }
]
}
See issue4 for more information.
Virtual Directory Support
TS allows defining
virtual directories
via the rootDirs compiler option. To enable virtual directory mapping, use the useRootDirs plugin option.
{
"compilerOptions": {
"rootDirs": [ "src", "generated" ],
"baseUrl": ".",
"paths": {
"#root/*": [ "./src/*", "./generated/*" ]
},
"plugins": [
{ "transform": "typescript-transform-paths", useRootDirs: true },
]
}
}
Example output
- src/
- subdir/
- sub-file.ts
- file1.ts
- generated/
- file2.ts
src/file1.ts
import '#root/file2.ts'
src/subdir/sub-file.ts
import '#root/file2.ts'
import '#root/file1.ts'
Example Config
// tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@utils/*": ["utils/*"]
}
}
}
import { sum } from "@utils/sum";
sum(2, 3);
Gets compiled to:
var sum_1 = require("../utils/sum");
sum_1.sum(2, 3);
Articles
Contributting
- make sure to format code with prettier:
npm install --global prettier
prettier --write src/index.ts
Contributors
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors
specification. Contributions of any kind welcome!