A TypeScript transformer which enables compilation of absolute imports (using baseUrl
or paths
) so they can be required as modules from Javascript or TypeScript, without additional configuration or path mapping.
Read more about why this exists and what problem it solves
Thankfully since releasing this module, other solutions have become which offer more features and do a better job. I recommend you check out @zerollup/ts-transform-paths
— it works in the same way (as a typescript plugin / with ttypescript) but reliably covers more import/export types.
If you're using the TypeScript compiler and using TypeScript's native "absolute imports" mapping (specifying baseUrl
or paths
in your config), you've found none of the compiled code is usable in Javascript or unconfigured TypeScript.
First, install ttypescript
:
npm install --save-dev ttypescript
See examples/ttypescript for detail, and ttypescript's README for how to set up in your project.
Now, specify ts-transfomer-imports
in your tsconfig.json
:
{
"compilerOptions": {
// ...
"plugins": [
{ "transform": "ts-transformer-imports" }
]
},
}
See ttypescript's README for usage information with other compilers. It should work!
You probably won't need this. See test for more detail.
const ts = require('typescript');
const importsTransformer = require('ts-transformer-imports').default;
const program = ts.createProgram([/* your files to compile */], {
strict: true,
noEmitOnError: true,
target: ts.ScriptTarget.ES5
});
const transformers = {
before: [importsTransformer(program)]
};
const { emitSkipped, diagnostics } = program.emit(undefined, undefined, undefined, false, transformers);
I don't want to write:
// within a deep directory, this can be tedious on large projects
import isTruthy from '../../utils/isTruthy'
import AppView from '../views/app'
so TypeScript allows me write:
import isTruthy from 'utils/isTruthy'
import AppView from 'views/app'
when tsconfig.json
looks like this:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"utils": ["./utils"],
"views": ["./components/views"],
}
}
}
but tsc
compiles it to:
const isTruthy = require('utils/isTruthy')
// At runtime, node will try to resolve the "utils" module dependency from within node_modules and fail
So ts-transformer-import
transforms the emitted javascript this at typescript compile time:
const isTruthy = require('../../utils/isTruthy')
const AppView = require('../views/app')
TypeScript 2.4 and up
MIT
- Massive thanks to everyone who has contributed with pull requests and other submissions to this project.
- https://gist.github.com/rifler/39fdcd92e78505bbc94dc5b9f845292b
- https://github.com/kimamula/ts-transformer-keys
- https://github.com/dsherret/ts-simple-ast