pika-pack-builders
pika-pack-builders copied to clipboard
Transform tsConfig.compilerOptions.paths when building TypeScript
Hello. Thank you for your project 👍
TypeScript module resolution shortcuts are not transformed into a plain paths.
tsconfig.json
{
"compilerOptions": {
"target": "es2015",
"types": ["node"],
"lib": ["esnext"],
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"declaration": true,
"declarationMap": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@test/*": ["./test/*"]
}
}
}
source
// src/index.ts
import { createServices } from '@/services'
output
// pkg/dist-src/index.js
import { createServices } from '@/services';
expected output
// pkg/dist-src/index.js
import { createServices } from './services';
possible-solution
That's a really interesting feature! I haven't used that personally before, is it supported by TypeScript by default, or is this a feature that only works when tsconfig-paths
is loaded? If there are any official TypeScript docs you can send along, that would be great.
Also, do you have an example repo that you can share so that I can get a better feel for it?
This is typescript feature, the caveat is that tsc
does not compile aliases to real paths during the build.
Resources
Here's the doc https://www.typescriptlang.org/docs/handbook/module-resolution.html
Here's the simpler explanation https://stackoverflow.com/questions/43281741/how-to-use-paths-in-tsconfig-json
Here's the corresponding TypeScript issues https://github.com/Microsoft/TypeScript/issues/16640 https://github.com/Microsoft/TypeScript/issues/10866
Existing solutions in other tools
- Webpack: tsconfig-paths-webpack-plugin
- Babel: babel-plugin-module-resolver
Solution?
tsconfig-paths
is only able to alias paths in runtime (node --register tsconfig-paths/register index.js
). This looks weird and might cause unintended side effects.
Ideally, paths should be transpiled during the build. However, I was not able to find existing solution that would do this. Looks like this is archivable only by using module builder like Webpack or Rollup.
And here's the reproduction https://github.com/stackdumper/pika-pack-tsconfig-paths-repro
I run into the same issue! Basically, it makes it impossible to use it in a project that gets included somewhere.
Would be cool if we got this working.
To get around this issue I'm just running ts-node -r tsconfig-paths/register server.js
instead of node server.js
and it works as expected with the paths not being mapped. This requires ts-node to be installed globally for this to work.
Just for help https://dev.to/larswaechter/path-aliases-with-typescript-in-nodejs-4353