PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 25, 2022

[FIXED] How to run several code before import syntax in Javascript?

 November 25, 2022     ecmascript-6, import, javascript, module, node.js     No comments   

Issue

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

Solution

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


Answered By - Laode Muhammad Al Fatih
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing