Package exports and imports
Prerequisite: node-performance-regression-tests. Objective: Test explicit public subpaths. Tested locally on Node.js 22.16.0 Linux. Each example is independent. Use a fresh disposable working directory, save as main.mjs, then run node main.mjs. The harness uses a five-second timeout and synthetic environment. These are static code blocks, not ByteMind interactive execution.
How it works
Set type explicitly for .js files; .mjs and .cjs retain their module modes. Map . to the main public entry, and ./feature to an intended subpath. When exports is present, unlisted subpaths are not available through package-name resolution; this is API encapsulation, not a security boundary. Conditional exports select the first matching condition in object order. Keep explicit file extensions in relative ESM imports. The fixtures create a tiny package in a disposable working directory, then run its self-reference or internal alias; no dependency install occurs.
Self-reference and deny an unexported subpath
import {writeFileSync} from 'node:fs';import assert from 'node:assert/strict';writeFileSync('package.json',JSON.stringify({name:'bm-fixture',type:'module',exports:{'.':'./public.js'}}));writeFileSync('public.js','export const count=3;');writeFileSync('private.js','export const internal=7;');assert.equal((await import('bm-fixture')).count,3);await assert.rejects(import('bm-fixture/private.js'),{code:'ERR_PACKAGE_PATH_NOT_EXPORTED'});console.log('public allowed; private subpath denied');Expected output:
public allowed; private subpath deniedThe package name resolves its own exports. Direct filesystem access is a separate matter.
Resolve an internal package alias
import {writeFileSync} from 'node:fs';writeFileSync('package.json',JSON.stringify({type:'module',imports:{'#price':'./price.js'}}));writeFileSync('price.js','export const price=7;');console.log((await import('#price')).price);Expected output:
7The hash-prefixed alias belongs to this package scope.
Common mistakes
An exports map does not make files confidential. Do not package private material or treat unexported subpaths as a permission system.
Practice
Add a public ./format subpath and show that a third internal file remains unexported by name.
Reference candidate: node-package-exports-and-imports-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/packages.html (opened).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Package exports and imports — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
What does an unlisted subpath under exports normally cause?
Which is a valid internal imports key?
If multiple conditions match, what matters?