Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node import modules after executing code (or ESM Dynamic import)

i'm writing some code in nodejs and express, i need to execute some code BEFORE continuing to import modules. My whole app has set up and uses modules with import instead of require and I can't change this setting.

In order to get some npm packages to work I have to run them BEFORE continuing with importing modules. Using commonJS and require () works perfectly, but with import I can't.

Even if I reverse the order of the modules or if I call them in different files they are all loaded FIRST and only afterwards my code is executed.

Example start.js

import { mustBeLoadedAfterCode } from './second.js';
// some code here I need to execute first

second.js

import { mustBeLoadedAtTheEnd } from './third.js';
// some code here to execute at the end

In all my test, my code will be executed only AFTER have imported 'second.js' and all it relative imports.

Any idea?

like image 445
crivella Avatar asked Dec 20 '25 12:12

crivella


1 Answers

I've found a solution using dynamic imports:

let module = await import('./module.js');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Dynamic_Imports

https://v8.dev/features/dynamic-import

like image 68
crivella Avatar answered Dec 22 '25 01:12

crivella



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!