Sub topic 11
Side-Effect-Only Imports
This chapter assumes you already know the import forms covered earlier (named, default, namespace, and renamed imports) and that you can run ES modules in Node.js or a browser. To run the Node.js examples, put them in a folder whose package.json contains "type": "module", or rename the files to .mjs.
Every import form you have seen so far brings bindings into scope. A side-effect-only import brings in none. It names a module and tells the engine to load and evaluate it, and that is all it does:
import './polyfills.js';There is no from keyword and no identifier list, so this statement adds no variables to the importing module. You use it when the imported module's value lies in what it does while running, such as patching a global, registering a plugin, or defining a custom element. A module whose job is to change shared state when it evaluates is said to have side effects.
What the statement actually does
A side-effect-only import goes through the same pipeline as any other static import:
- The specifier
'./polyfills.js'is resolved with the same rules as any other specifier. - The module is fetched and parsed, and its own imports are followed.
- The module is evaluated before the importing module's body runs.
- No bindings are created in the importer.
The form import {} from './polyfills.js'; does exactly the same thing. It is legal, but the bare form says what you mean more clearly.
Because modules are singletons per resolved URL, a module that is imported this way from ten places still evaluates only once. The first import triggers evaluation, and later imports reuse the already-evaluated instance.
A worked example: evaluation order
The following three files show two rules: imports are hoisted, and each module runs once.
// log-a.js
console.log('a evaluated');// log-b.js
import './log-a.js';
console.log('b evaluated');// main.js
console.log('main body');
import './log-b.js';
import './log-a.js';Run node main.js and the output is:
a evaluated
b evaluated
main bodyThree details stand out:
main bodyprints last even though its line comes first in the file. Import declarations are processed before any statement in the module body runs, wherever they appear in the source.log-a.jsruns beforelog-b.jsbecauselog-b.jsdepends on it. The engine walks dependencies depth-first and evaluates a module only after its dependencies have run.log-a.jsprints once. By the timemain.jsreaches its second import, the module has already been evaluated.
Common uses
Polyfills and global patches
A polyfill adds a missing standard feature to older environments. It has to run before any code that uses the feature, and it exports nothing, which makes it a natural fit for a side-effect-only import.
// polyfills.js
if (!Array.prototype.at) {
Object.defineProperty(Array.prototype, 'at', {
value: function at(index) {
const i = Math.trunc(index) || 0;
const k = i < 0 ? this.length + i : i;
return k >= 0 && k < this.length ? this[k] : undefined;
},
writable: true,
configurable: true,
});
}// main.js
import './polyfills.js';
import { lastItem } from './utils.js';
console.log(lastItem([1, 2, 3])); // 3// utils.js
export function lastItem(list) {
return list.at(-1);
}Imports are evaluated in source order, so polyfills.js runs before utils.js. That guarantee only covers what main.js controls, though. If utils.js itself calls .at() at its top level, it still works here only because the polyfill import comes earlier in main.js. The more reliable pattern is for utils.js to import the polyfill itself, so it does not depend on its importer's ordering.
Registering plugins
Many systems keep a shared registry that plugins add themselves to when they load:
// registry.js
export const handlers = new Map();
export function register(name, fn) {
handlers.set(name, fn);
}// plugins/greet.js
import { register } from '../registry.js';
register('greet', (who) => `Hello, ${who}`);// main.js
import './plugins/greet.js';
import { handlers } from './registry.js';
console.log(handlers.get('greet')('Ada')); // Hello, Adamain.js never touches anything from greet.js. Importing the plugin is enough to register it, and the registration works because registry.js is a single shared instance.
Custom elements and stylesheets
In the browser, import './components/date-picker.js'; is a common way to run a file that calls customElements.define(...). Bundlers also let you write import './styles.css'; to include a stylesheet. That stylesheet import is a bundler convention, not standard JavaScript. A browser running unbundled modules will reject it unless you use a standardized mechanism such as CSS module scripts with an import attribute, and support for those varies between browsers.
Comparing the forms
| Form | Bindings created | Evaluates the module | Timing |
|---|---|---|---|
| `import './x.js';` | None | Yes, once | Before importer's body |
| `import { a } from './x.js';` | `a` | Yes, once | Before importer's body |
| `import * as x from './x.js';` | Namespace `x` | Yes, once | Before importer's body |
| `await import('./x.js');` | None (returns a promise for the namespace) | Yes, once | When the expression runs |
If you want side effects that happen conditionally or later, use dynamic import('./x.js') and ignore its result. A static side-effect import always runs, before the importer's body.
Gotchas and edge cases
Tree shaking can remove it
Bundlers drop code that nothing uses. A side-effect-only import uses no bindings, so a bundler will keep it only if it believes the module has side effects. Packages can declare "sideEffects": false in package.json to say none of their files have side effects. If that claim is wrong, your polyfill or registration silently disappears from the production build while it still works in development.
{
"name": "my-widgets",
"type": "module",
"sideEffects": ["./src/register.js", "*.css"]
}Listing the files that do have side effects keeps the rest of the package eligible for tree shaking.
Errors propagate
If the imported module throws during evaluation, the importing module never runs its body, and neither does anything that depends on it. A failing polyfill takes the entire import graph above it down with it.
Top-level await delays the importer
If the side-effect module uses top-level await, the importer waits until that promise settles. A slow network call inside a "setup" module therefore blocks everything that imports it.
Different URLs mean different instances
Singleton behavior applies per resolved URL. In the browser, import './setup.js'; and import './setup.js?v=2'; resolve to different URLs, so the setup runs twice. The same thing happens when a file is reachable through two different paths that resolve to different URLs.
No bindings means no live link
A side-effect import cannot read anything back. If you later need a value from that module, switch to a named import. Do not reach for a global the module happened to set.
Exercise
Given // main.js containing console.log('start'); import './a.js'; import './b.js';, where a.js is import './b.js'; console.log('a'); and b.js is console.log('b');, what does node main.js print, in order?
Show answer
It prints b, then a, then start. Imports are hoisted above the body of main.js. a.js depends on b.js, so b.js evaluates first, followed by a.js. The second import of b.js in main.js is skipped because b.js has already been evaluated. The main.js body runs last.
Exercise
A plugin file registers itself with register('chart', ...) and is loaded with import 'my-lib/plugins/chart.js';. It works in development, but in the production bundle the registry has no 'chart' entry. What is the most likely cause, and how do you fix it?
Show answer
The package probably declares "sideEffects": false, so the bundler removed a module whose bindings were never used. Fix it by listing the plugin file (or a pattern that matches it) in the package's sideEffects array, or by using a named import whose value you actually use.
Exercise
You want a module that sets globalThis.API_BASE to run before client.js evaluates. Why does putting globalThis.API_BASE = '/api'; above import './client.js'; in main.js fail, and what works instead?
Show answer
Import declarations are hoisted, so client.js evaluates before any statement in main.js runs. Move the assignment into its own module, config-globals.js, and import it with import './config-globals.js'; before import './client.js';. Better still, have client.js import that module itself, so it does not rely on its importer's ordering.