Side effects in module import
Show how importing a module can run the module's global code, causing side effects even without using any imports.
// sideEffectsModule.js
console.log('This will run at import, causing a side effect');
let counter = 0;
function incrementCounter() {
counter++;
}
incrementCounter();
module.exports = { counter };
This is the sideEffectsModule.js file. The console.log statement and incrementCounter function call will execute immediately upon import of this module, creating side effects.
// main.js
const { counter } = require('./sideEffectsModule.js');
console.log(`Counter value after import: ${counter}`);
This is the main.js file importing sideEffectsModule.js. The counter value is logged to the console, which will show the side effect of the counter incrementing due to the module import.