Node.js module loading with resolution, caching, and exports

Troubleshoot missing modules from their import paths and understand why modules usually initialize only once.

🎯 Introduction

By the end of this article, you will be able to troubleshoot missing modules from their import paths and understand why modules usually initialize only once.


🧱 Identify what you are importing

Module loading resolves an import specifier to a file or built-in capability and executes its initialization code. When a module cannot be found, first distinguish these three sources:

  • node:path starts with node: and identifies a built-in Node.js module. No installation is required.
  • ./greet.mjs starts with a relative path and looks for a file next to the current module.
  • Package names such as dayjs generally resolve through node_modules, searching from the current module's directory up through its parent directories.

For example, importing ./greet.mjs from src/main.mjs targets src/greet.mjs, not greet.mjs in the terminal's current directory. This explains why imports can still work when you start a script from another directory.

Local ESM imports should include the full extension, such as ./greet.mjs. For a file inside a directory, explicitly use ./tools/greet.mjs. CJS supports some filename completion, but those rules do not carry over to ESM.


🛠 Caching: a module usually initializes only once

The module cache retains loaded module results so that multiple importers can reuse the same functionality. Create settings.mjs:

settings.mjs
console.log('Initializing settings')
export const settings = { theme: 'light' }

Create main.mjs in the same directory and run node main.mjs:

main.mjs
import { settings as first } from './settings.mjs'
import { settings as second } from './settings.mjs'
console.log(first === second)

It prints Initializing settings once, followed by true. Both imported variables refer to the same object; the second import does not recreate the settings.

To observe shared state, append this to main.mjs:

first.theme = 'dark'
console.log(second.theme)

The additional output is dark. Changes to a shared module object are visible to other importers. If each caller needs independent settings, replace settings.mjs with:

settings.mjs
export const createSettings = () => ({ theme: 'light' })

Then replace main.mjs with:

main.mjs
import { createSettings } from './settings.mjs'
const first = createSettings()
const second = createSettings()
first.theme = 'dark'
console.log(second.theme)

This prints light. The module is still cached, but every function call creates independent settings, so one caller's changes do not affect another.

Caching uses the resolved module identity: typically a filename for CJS and a module URL for ESM. During development, restart the program to load changed code rather than expecting repeated imports to refresh it.


🧰 exports: package authors choose the public entry points

The exports field in package.json declares the entry points a package exposes to consumers. Stable entry points let authors change internal files without requiring every consumer to update paths.

Use a local practice package to observe this rule, with no publishing or third-party installation required. Create package.json in a new directory:

package.json
{
    "name": "demo-tools",
    "type": "module",
    "exports": {
        ".": "./greet.mjs"
    }
}

name is the package name, . represents its main entry point, and ./greet.mjs is the file it targets. As covered earlier, type makes the package's .js files use ESM; .mjs already specifies ESM explicitly.

Create the file containing the public functionality:

greet.mjs
export const greet = name => `Hello, ${name}`

Create a consumer file and run node use-package.mjs:

use-package.mjs
import { greet } from 'demo-tools'
console.log(greet('Alex'))

The result is Hello, Alex. Node.js allows a package with a name and exports to reference itself by its own name internally, so you do not need to install demo-tools here.

Changing the import to 'demo-tools/greet.mjs' produces ERR_PACKAGE_PATH_NOT_EXPORTED. The file exists, but only the main entry point is exposed, not this subpath. External consumers should follow the package documentation and use demo-tools rather than guessing internal paths.

To expose another entry point, add "./greet": "./greet.mjs" to exports. Consumers can then use demo-tools/greet. The left side is the public name; the right side is the actual file.

❓ Questions and answers

Q1: Are relative imports based on the terminal directory?

No. In a module, ./ is relative to the current module file, not the terminal's current directory.

Q2: Does changing a file refresh the cache automatically?

Regular execution does not automatically rerun loaded modules. Restart the program during development.

Q3: Why can a file inside a package fail to import?

It may be restricted by exports, or the path or module format may be wrong. Check the error type first.


🧪 Exercise

Run the caching example, then add a field to settings and check whether both imported variables see the same change.

// Write your code here

🎉 Try these techniques with your own examples!