Transforms absolute imports to relative
Transform module resolution paths in compiled output source to conform with
TypeScriptinternal resolution via
tsconfig.jsonsettings (
paths,
rootDirs,
baseUrl)
# NPM npm i -D typescript-transform-pathsYarn
yarn add -D typescript-transform-paths
Add it to plugins in your tsconfig.json
{ "compilerOptions": { "baseUrl": "./", "paths": { "@utils/*": ["utils/*"] }, "plugins": [ // Transform paths in output .js files { "transform": "typescript-transform-paths" },// Transform paths in output .d.ts files (Include this line if you output declarations files) { "transform": "typescript-transform-paths", "afterDeclarations": true } ]
} }
core/index.ts
tsx import { sum } from "@utils/sum"; sum(2, 3);
core/index.js(compiled output)
js // core/index.js var sum_1 = require("../utils/sum"); sum_1.sum(2, 3);
TS allows defining virtual directories via the
rootDirscompiler option.
useRootDirsplugin option.
{ "compilerOptions": { "rootDirs": [ "src", "generated" ], "baseUrl": ".", "paths": { "#root/*": [ "./src/*", "./generated/*" ] }, "plugins": [ { "transform": "typescript-transform-paths", "useRootDirs": true }, { "transform": "typescript-transform-paths", "useRootDirs": true, "afterDeclarations": true } ] } }
- src/ - subdir/ - sub-file.ts - file1.ts - generated/ - file2.ts
src/file1.ts
ts import '#root/file2.ts' // resolves to './file2'
src/subdir/sub-file.ts
ts import '#root/file2.ts' // resolves to '../file2' import '#root/file1.ts' // resolves to '../file1'
You can disable transformation for paths based on the resolved file path. The
excludeoption allows specifying glob patterns to match against resolved file path.
For an example context in which this would be useful, see Issue #83
Example:
jsonc { "compilerOptions": { "paths": { "sub-module1/*": [ "../../node_modules/sub-module1/*" ], "sub-module2/*": [ "../../node_modules/sub-module2/*" ], }, "plugins": [ { "transform": "typescript-transform-paths", "exclude": [ "**/node_modules/**" ] } ] } }
// This path will not be transformed import * as sm1 from 'sub-module1/index'
Use the
@transform-pathtag to explicitly specify the output path for a single statement.
// @transform-path https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js import react from 'react' // Output path will be the url above
Use the
@no-transform-pathtag to explicitly disable transformation for a single statement.
// @no-transform-path import 'normally-transformed' // This will remain 'normally-transformed', even though it has a different value in paths config
yarn(
yarn install)
prettier(
yarn run format)
standard-version(
yarn run release)
Ron S. |
Daniel Perez Alvarez |
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!