DEV Community

Cover image for Import Modules for Side Effects
chantastic
chantastic

Posted on • Originally published at chan.dev on

Import Modules for Side Effects

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay