TypeScript Import Path Alias
So after reading your comment, I realized I misunderstood your question! If you want to control the paths from an imported package's perspective, just use set the main
property of your package.json
to a file that properly represents the object graph of your module.
{
"main": "common-utils/dist/es2015/index.js"
}
If you're attempting to control the import paths from a project's perspective, what you're looking for is TypeScript 2's new path mapping feature for module resolution. You can enable path mapping by configuring your tsconfig.json
as follows:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"angular2/*": ["../path/to/angular2/*"],
"local/*": ["../path/to/local/modules/*"]
}
}
}
Then, in your TypeScript files, you can import the modules like this:
import { bootstrap } from 'angular2/bootstrap';
import { module } from 'local/module';
For more details about the Path Mapping feature in TypeScript 2 see this Github issue.
In your case, I think the following configuration should work:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"common-utils/utils/*": ["./node_modules/common-utils/dist/es2015/utils/*"]
}
}
}
If you are using paths, you will need to change back absolute paths to relative paths for it to work after compiling typescript into plain javascript using tsc
.
Most popular solution for this has been tsconfig-paths so far.
I've tried it, but it did not work for me for my complicated setup. Also, it resolves paths in run-time, meaning overhead in terms of your package size and resolve performance.
So, I wrote a solution myself, tscpaths.
I'd say it's better overall because it replaces paths at compile-time. It means there is no runtime dependency or any performance overhead. It's pretty simple to use. You just need to add a line to your build scripts in package.json
.
The project is pretty young, so there could be some issues if your setup is very complicated. It works flawlessly for my setup, though my setup is fairly complex.