w3resource

Import JavaScript Modules for Side Effects


Importing Without Using:

Write a JavaScript program to import a module for its side effects without directly using any exports.

Importing a module for its side effects means executing the module's code without accessing any of its exported values. This is useful when a module modifies global variables, registers event listeners, or performs initialization tasks.

Solution 1: Importing a Module for Logging Side Effects

Code:

File: logger.js

This file contains a module with a side effect of logging a message.

// logger.js
// Logging a message as a side effect
console.log('Logger module has been loaded!');

File: main.js

This file imports the module for its side effects.

//main.js
// Importing the logger module for its side effects
import './logger.js';

// The module's side effect is executed when imported
console.log('Main script executed.');

Output:

Logger module has been loaded!
Main script executed.

Explanation:

  • logger.js contains a side effect: logging a message to the console.
  • In main.js, the module is imported without accessing any exports.
  • Importing the module executes its code, logging the side effect.

Solution-2: Importing a Module to Register Global Functions

Code:

File: globalSetup.js

This file contains a module that defines a global function as a side effect.

// globalSetup.js
// Defining a global function as a side effect
globalThis.sayHello = function (name) {
  console.log('Hello, ${name}!');
};

File: main.js

This file imports the module for its side effects.

//main.js
// Importing the globalSetup module for its side effects
import './globalSetup.js';

// Using the global function defined as a side effect
sayHello('Spock'); 

Output:

Hello, Spock!

Explanation:

  • globalSetup.js defines a global function (sayHello) as a side effect.
  • In main.js, the module is imported without using exports.
  • Importing the module makes the global function available, which is then used in the script.

For more Practice: Solve these Related Problems:

  • Write a JavaScript program that imports a module solely for its side effects (e.g., modifying the DOM) without using any exported values.
  • Write a JavaScript program that triggers a module's initialization code by importing it without capturing any exports.
  • Write a JavaScript program that logs a message from a module on import and demonstrates that no exports are used.
  • Write a JavaScript program that conditionally imports a module for side effects based on a runtime flag.

Improve this sample solution and post your code through Disqus

Previous: Export JavaScript Functions Inline for Modular Code.
Next: Learn to Dynamically Override JavaScript Module Exports.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.