Import Modules for Side Effects

chantastic - Feb 2 '21 - - Dev Community

Modules — in JavaScript — can be imported strictly for their side effects.

import "./string-utils.mjs";
Enter fullscreen mode Exit fullscreen mode

Notice.
We're not making any local assignments.
We aren't importing functions or constants for later use.
We're simply importing the global effects of the module, as if the code lived in this file.

On the module side, simply write code with effects.

// file: ./string-utils.mjsconsole.info("string-utils loaded.");
Enter fullscreen mode Exit fullscreen mode

Conditional side effects with dynamic imports #

We can load modules with side effects conditionally, with an immediately invoked async function.

(async () => { if (true /* maybe some environment var */) { await import("/modules/my-module.js"); }})();
Enter fullscreen mode Exit fullscreen mode

Here, you can imagine checking an environment variable before importing side effects.

Don't mix side effects and exports #

Modules can contain a mix of exports and effects.

While there may be a good reason to do this, it also make your imports unpredictable.

Here's why I recommend avoiding the mix:

import hype from "./string-utils.mjs";// loads both exports AND side effectsconsole.log(hype("moduuuuuules"));// => string-utils loaded.// => MODUUUUUULES!!!
Enter fullscreen mode Exit fullscreen mode

Module effects always run at import.

In a mixed module, you can import only the effects but you can not import only the exports.

Side effect imports in the wild… #

I see this style of import used with Webpack to import stylesheets.

In this case, Webpack is packaging up CSS as JavaScript and appending it to the browser's CSSOM.

Go pro #

This is part of a course I'm build on modules at lunch.dev.

When live, members get access to this and other courses on React.

Join lunch.dev for videos

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .