Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run several code before import syntax in Javascript?

I want to run several code before the code inside import syntax gets executed.

Example

file-1.js

console.log('Inside File 1')

import './file-2.js'

file-2.js

console.log('Inside File 2')

Output

Inside File 2
Inside File 1

The output I expected

Inside File 1
Inside File 2

Environment

Node JS v12.19.0 with Module configuration


Real Case

file-1.js

process.env.SHARED_DATA = 'Hello world'

import './file-2.js'

file-2.js

console.log(process.env.SHARED_DATA)

Output

undefined
like image 995
Laode Muhammad Al Fatih Avatar asked Feb 25 '26 02:02

Laode Muhammad Al Fatih


2 Answers

You can define the env data in separate file. The import syntax will run in the order against the other imports as @loganfsmyth says.

Example

main.js

console.log('Inside main.js file')

import './set-env.js'
import './file.js'

set-env.js

console.log('Inside set-env.js file')

process.env.SHARED_DATA = 'Hello world'

file.js

console.log(process.env.SHARED_DATA)

Output

Inside set-env.js file
Hello world
Inside main.js file
like image 192
Laode Muhammad Al Fatih Avatar answered Feb 27 '26 14:02

Laode Muhammad Al Fatih


The best way I find is to use top-level await with dynamic import.

process.env.SHARED_DATA = 'Hello world';
await import('../index.js');
like image 39
Bruno Oliveira Avatar answered Feb 27 '26 14:02

Bruno Oliveira



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!