How to run several code before import syntax in Javascript?
Asked Answered
H

3

11

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
Hearthside answered 10/1, 2021 at 17:12 Comment(3)
The way import is implemented forbids such actions. Effectively import happens before anything else happens and then when imports are completed then code is executed normalyGoltz
It's hard to judge without a more real example, but you can do `import "log-inside-file1.js"; import "file-2.js"; since the imports themselves will run in order. It can't be anything in the same file though.Toxemia
In your real case example, you could export from file-2.js only a function. Then, you import that function (but no code has run yet) and then after setting up the environment, you call the function you imported and file-2.js finishes initializing itself. Or, you just pass the relevant info directly to the function when you call it rather than setting it into the environment. In either case, file-1.js gets to run code before it calls the file-2.js initialization function. This is a design pattern often called "module constructor" and is used to pass initialization parameters.Denna
H
12

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
Hearthside answered 10/1, 2021 at 22:9 Comment(0)
U
1

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

process.env.SHARED_DATA = 'Hello world';
await import('../index.js');
Unlock answered 19/9, 2022 at 14:43 Comment(0)
P
-3

In JavaScript the lines don't necesarily wait for the line before to end. One way to solve this issue of yours is to put the file-1.js into a async function:

 async function f() {
process.env.SHARED_DATA = "Hello world";
return Promise.resolve(1);
}

f().then(() => {import "./file-2.js"});

By calling this function you can make sure the import waits for the f function to end! Then running the arrow function. Hope this helped if you want to read more about this topic here you go. https://javascript.info/async-await

Penick answered 10/1, 2021 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.