Home > front end >  Not able to understand Order of execution for Imports (ES6) modules or something else?
Not able to understand Order of execution for Imports (ES6) modules or something else?

Time:01-13

I am refactoring a NodeJs project I built with CommonJS at the time of learning NodeJS and facing some difficulties with the order of imports (not guranteed if that is the case).

Node starts running from server.js and it import app.js:

import dotenv from 'dotenv'

// Dot Env Initialization
dotenv.config({ path: './.env' });

console.log('NODE_ENV from Server: '   process.env.NODE_ENV);  // THIS PRINTS AFTER CONSOLE IN APP.JS

// Local Imports
import app from './app.js';

const PORT = process.env.PORT || 3300;

app.listen(PORT, () => {
  console.log(`App running on PORT: ${PORT}`);
})

Code of app.js

// Module Imports (3rd)
import express from 'express';
import morgan from 'morgan';

// Local Imports
import routerLogic from './src/routes/routerLogic.js'

// Module Initializations
const app = express();

// Middleware
console.log('NODE_ENV from App.js: '   process.env.NODE_ENV); // THIS IS PRINTING BEFORE ONE 

if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}
app.use(express.json());

// Routes and Logics
app.use('/', routerLogic);

export default app;

This is what is printing in Terminal:

$ node server.js
NODE_ENV from App.js: undefined
NODE_ENV from Server.js: development
App running on PORT: 3300

Looked into multiple places some says import is async, some says it is not.

CodePudding user response:

Regardless of import order, note that all imports are evaluated before the module that imports them is evaluated.

This means that dotenv.config({ path: './.env' }); is being executed only after the imported app module was evaluated. So the app module is evaluated before dotenv was configured, and the NODE_ENV environment variable is not yet loaded.

If you want to understand better the import order I can recommend reading Execution order of JavaScript modules by Marian Čaikovski

  • Related