Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs with ES6 import

Tags:

node.js

Here is my index.js:

import dotenv from 'dotenv'
dotenv.config();
import "./WebScrapingProject/DBConnect";

If I ran the code above I get this error:

The `uri` parameter to `openUri()` must be a string, got "undefined".

But if I changed imports to ES5:

import dotenv from 'dotenv'
dotenv.config();
require("./WebScrapingProject/DBConnect");

it works but why? and how can I use ES6 imports in this case?

Here is the DBConnect file:

import {default as mongo} from "mongoose";

mongo.connect(process.env.DB_HOST, {useNewUrlParser: true}).then(() => {console.log('DB connected!')});
mongo.set('useFindAndModify', false);
like image 717
Kadiem Alqazzaz Avatar asked Apr 27 '26 02:04

Kadiem Alqazzaz


2 Answers

There are two different choices on which module system we can be use:

Importing modules using require also CommonJS Importing modules using ES6 import.

The behaviour of both modules system are different when you do require Loading is synchronous. That means if you have multiple requires, they are loaded and processed one by one.

and when import can be asynchronous (and in current ES6 Module Loader, it in fact is) and can perform a little better.

In your case mongoose did not get configuraiton settings thats why it throws error, due to which config file was not loaded yet

The problem is the import happens before dotenv has loaded your env config file.

solution is to put the env config in a separate file and import it first or change the order

// index.js
import './loadEnv';
import './WebScrapingProject/DBConnect';

// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()
like image 98
Wasiq Muhammad Avatar answered Apr 28 '26 19:04

Wasiq Muhammad


The problem is the import happens before dotenv has loaded your env config file. This is because all the imports are loaded before the other code in the file is run.

One way of fixing it is to put the env config in a separate file and import it first.

e.g.

// index.js
import './loadEnv';
import './WebScrapingProject/DBConnect';
// loadEnv.js
import dotenv from 'dotenv';
dotenv.config()
like image 29
braza Avatar answered Apr 28 '26 20:04

braza