Skip to content
jshacks.dev
Packages

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.

1 min read
Summarize in AI

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.

package.jsonJSON
{
  "name": "app",
  "type": "module",
  "imports": {
    "#db": "./src/db/index.js",
    "#utils/*": "./src/utils/*.js"
  }
}
src/db/index.jsJavaScript
export const connect = () => "connected";
src/utils/slug.jsJavaScript
export const slugify = (s) => s.toLowerCase().replaceAll(" ", "-");
src/routes/users.jsJavaScript
import { connect } from "#db";
import { slugify } from "#utils/slug";

console.log(connect(), slugify("Hello World"));
Text
connected hello-world

Only 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.

Share

More snippets

Packages

Initialize a package with npm init

Initialize a package.json with npm init, skip the questions with the yes flag, and set your own defaults for author and license in npm config.

1 min read
Packages

Generate a changelog from commits

Turn conventional commit messages into a CHANGELOG.md section with conventional-changelog, grouped by feature and fix. Works with any Git history.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.