0

I am new to nodejs REST api creation. I am using ES6 format. I have decided to create an environment based configurations and stored in different files.

So the issue I came across was

const myUrl = path.resolve(`lib/${process.env.NODE_ENV}.js`);
import { myVar } from myUrl;

I try importing files like shown above, but it doesnt work. I understand it can be easily solved by using

const myVar = require(myUrl)

But I want to know if there is any way to continue using import itself instead of require?

MDN has all ways of importing, but i could not find a way on how to import from a constructed url like above

sam
  • 2,277
  • 4
  • 18
  • 25
  • Does this answer your question? [How can I use an ES6 import in Node.js?](https://stackoverflow.com/questions/45854169/how-can-i-use-an-es6-import-in-node-js) – Grant Herman Oct 30 '20 at 19:03

1 Answers1

0

The ES6 import format only allows imports from static string literals, as it is being evaluated at load time (before executing any code).

If you really want to load the module dynamically based on your environment, use the dynamic form of import (not require):

var promise = import("module-name");

However, maybe you would like to use the more standard way: store your environment configurations in .env files, use the dotenv library to load the configuration dynamically from the correct location - while the code that loads it is static and is the same for all environments, in a dedicated module, and then it can be statically imported by your app code.

aminits
  • 174
  • 4