typescript-transform-paths
Transforms absolute imports to relative from paths in your tsconfig.json
Install
npm:
npm i -D typescript-transform-pathsyarn:
yarn add -D typescript-transform-pathsUsage with ttypescript or ts-patch
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' // resolves to './file2'src/subdir/sub-file.ts
import '#root/file2.ts' // resolves to '../file2'
import '#root/file1.ts' // resolves to '../file1'Example Config
// tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"paths": {
"@utils/*": ["utils/*"]
}
}
}// core/index.ts
import { sum } from "@utils/sum";
sum(2, 3);Gets compiled to:
// core/index.js
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.tsContributors
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!