Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

193
Views
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
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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
over 4 years ago · Santiago Trujillo Report

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!