Use subpath imports with the imports field
Replace long relative paths with hash-prefixed aliases using the package.json imports field, supported by Node.js since 12.19 with no build tool.
Deep relative paths like ../../../db/index.js break when files move. The imports field defines aliases that must start with #, and Node.js resolves them natively.
{
"name": "app",
"type": "module",
"imports": {
"#db": "./src/db/index.js",
"#utils/*": "./src/utils/*.js"
}
}export const connect = () => "connected";export const slugify = (s) => s.toLowerCase().replaceAll(" ", "-");import { connect } from "#db";
import { slugify } from "#utils/slug";
console.log(connect(), slugify("Hello World"));connected hello-worldOnly the nearest package.json counts, and only this package can use its own # names, so they never leak to consumers. This is different from paths in tsconfig.json, which TypeScript understands but Node.js ignores. See subpath imports.
For TypeScript, set moduleResolution to node16, nodenext or bundler so the compiler reads the same field. Older settings do not know imports and report that the module cannot be found.