This repository shows how to use TypeScript paths with Node.js without any additional bundling/transformation step.
$ git clone git@github.com:fox1t/ts-paths-node-native.git
$ npm i
$ npm run build
$ npm start
If you use a Node.js version that doesn't support the subpath-patterns feature, you will get this error:
internal/modules/cjs/loader.js:969
throw err;
^
Error: Cannot find module '#subpath/index'
Before version v12.20.0 and v14.13.0, in order to use TS path-mapping in Node.js, a bundling/transformation step was mandatory. In fact, TypeScript itself doesn't "convert" the mapped paths to the real paths. That's it if you write:
import { foo } from "#subpath/foo";
it will be compiled to
const foo_1 = require("#subpath/foo");
Possible ways of making it work were to use babel to transform the code during the build or add a dependency at runtime using the -r
flag. Neither of two was an ideal one:
- Using another tool in conjunction with
tsc
adds complexity to the configuration: in this case,tsc
was used just to check types and the compilation was usually handled by babel - Adding a runtime dependency has two significant drawbacks:
- slower startup time of the process;
- there are still no "mature" projects that work in every scenario.
Version 12.20.0 and 14.13.0 Node.js supports native path remapping during require/import thanks to two features:
Adding these lines to the package.json file
"imports": {
"#subpath/*": {
"require": "./dist/subpath/*.js"
}
},
makes Node.js understand what to do when it finds const foo_1 = require("#subpath/foo");
in the code.
On the tsconfig.json side, things remain the same as before.
{
"compilerOptions": {
"outDir": "dist",
"baseUrl": "./src",
"paths": {
"#subpath/*": ["subpath/*"]
}
}
}
Entries in the imports field must always start with #
to ensure they are disambiguated from package specifiers. So no more @
.
Since Node.js' subpath imports
just add .js
extension to the path you provide, you need to use the index
file when importing a folder.
That's it,
import * as config from "#subpath/module/index";
instead of
import * as config from "#subpath/module";
In fact, the latest one will be resloved as
`const module = require("./dist/module.js")`
instead of
`const module = require("./dist/module/index.js")`
and Node.js will not find the file to import at runtime.
Today, importing .json files in TypeScript using the flag resolveJsonModule
isn't supported since Node.js matches files without extension. So writing
import * as config from "#subpath/config.json";
Will resolve to this path.
./src/subpath/config.json.js
Use the full path instead of the alias.