ES6 Conditional Import and Export: Leveraging the Power of Conditional

Looking to implement a nested if else statement for importing and exporting in ES6? In this scenario, we have 2 files - production.js and development.js which contain keys for development and production code respectively. Additionally, there is another file called keys.js that imports and exports these keys based on the requirements. All 3 files are located within the same directory.

Keep in mind that package.json specifies type as "module".

production.js

const keys = {
    GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
    GOOGLE_CLIENT_SECRET: process.env.GOOGLE_CLIENT_SECRET,
    mongoURI: process.env.MONGO_URI,
    cookieKey: process.env.COOKIE_KEY
}

export default keys;

development.js

const keys = {
    GOOGLE_CLIENT_ID: 'something.something',
    GOOGLE_CLIENT_SECRET: 'itisasecret',
    mongoURI: 'database',
    cookieKey: 'blabla',
}

export default keys;

keys.js

if (process.env.NODE_ENV === 'production') {
    
    /*This section throws error*/
    
    import keys from './production.js'
    export default keys
}
else{

    /*This section also throws error*/

    import keys from './development.js'
    export default keys
}

Answer №1

Importing a module dynamically does not require writing nested if/else statements, but rather utilizing the dynamic import syntax. This is necessary because the standard import statement can only accept a single or double quoted string as the path to the module. By using import(), which resembles a function but operates differently, you can leverage a string template literal within the parentheses to bring in the required file.

The drawback of using import() is that it returns a Promise object that needs to be managed, although this process is not overly complicated.

Below is the solution:

index.js

import keys from './keys.js';
console.log(keys);

production.js

const keys = { stuff: 'production' }
export default keys;

development.js

const keys = { stuff: 'development' }
export default keys;

keys.js

process.env.NODE_ENV = 'production';
let keys;
(async ()=>{
  try {
    keys = import( `./${process.env.NODE_ENV}.js`);
  } catch(err) {
    console.log(err);
  }
})();
export default await keys;

It's important to note the async code used here to handle the Promise object. Additionally, the try/catch block should consistently encompass an await statement for proper Promise rejection handling.

By following this method, there is no need for conditional if/else logic.

For a live demonstration of this approach, you can access the provided working example link.

Answer №2

It's important to note that the process is not as straightforward as you may think. What you're outlining resembles a concept known as dynamic import.

You should start by importing key sets from both files.
Create an object that links keys with corresponding NODE_ENV values.
After selecting the keys, export them.

import productionKeys from './production.js'
import developmentKeys from './development.js'

const keys = {
  'production': productionKeys,
  'development': developmentKeys
};

const selectedKeys = keys[process.env.NODE_ENV];

export default selectedKeys;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React.js: The specified element type is not valid:

I am currently working on a sample project using react.js in Visual Studio 2019 Here is my Index.js file: import 'bootstrap/dist/css/bootstrap.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provi ...

"Troubleshooting IE-specific problem: Loading dropdown options dynamically with AJAX on change

Struggling with a particular issue lately. I'm attempting to populate a second dropdown menu based on the selection made in the first one using jquery ajax. Surprisingly, it works flawlessly on all browsers except for IE 11. Below is the ajax functio ...

The JavaScript slideshow fails to display an image during one rotation

The slideshow displays a sequence of images from pic1.jpg to pic8.jpg, followed by a 4-second pause with no image, and then repeats starting again at pic1.jpg. I am looking to have it loop back to pic1.jpg immediately after displaying pic8.jpg. Below is t ...

Generating a default template for an Angular ag-Grid cell with a custom field name - how to do it?

I am currently working with ag-grid and have specific templates for many columns. However, some of the data I am inputting into the table are just plain text. I want to enhance the default case: <ng-template #defaultRecord let-record> ADDITIONAL E ...

struggling to send JSON data to PHP using AJAX

Here is the code snippet I am currently using. Javascript <script type="text/javascript"> var items = new Object(); items[0] = {'id':'0','value':'no','type':'img','filenam ...

Saving file with HTML download button results in only HTML document being saved

I am attempting to include a "download file" button on my gatsby website as shown below: <a href="../../images/project-logos/placeholder-company-logo.png" download="test" className="responsive-square project-logo" > <img sr ...

"Proper Installation of Angular Project Dependencies: A Step-by-Step

Whenever I clone an Angular project with older versions that are missing the node_modules folder, and then run npm install to install all necessary dependencies, I end up receiving numerous warnings and errors related to version mismatches. Here are some ...

What is the method to retrieve the base host in AngularJS?

I need assistance with the following URL: https://192.168.0.10/users/#!/user-profile/20 When I use $location.host, it returns 192.168.0.10 However, I only want to extract https://192.168.0.10 What is the best way to achieve this? ...

Retrieve the heading from a pop-up box

This jQuery tooltip allows for popups from another HTML page to be created. UPDATE: I have provided an example HERE The issue arises when trying to retrieve the title from the popup. Currently, using document.title displays the title of the current page ...

Multiple components are returned with switch case

I am trying to iterate over an object and display a result based on Object.entries. However, the loop currently stops at the first return statement. Is there a way for me to capture and display all components returned simultaneously, perhaps using a vari ...

Error: EsLint detected that the classname is not a valid Tailwind CSS class

I am encountering an EsLint error indicating that "className is not a TailwindCSS class" after incorporating custom classes like colors into my tailwind.config.js file. Despite this, I am unsure about how to resolve this issue. Shouldn't EsLint recogn ...

Obtaining a value from an input field in Vue.js

Just starting out with Vue and could use a hand extracting a value from an input field: Here's what I have in my form: <input type="hidden" id="groupId" value="1"> If I were using jQuery, I would do the following: ...

The placement of the FirebaseAuth.onAuthStateChanged call in an Angular application is a common concern for developers

Where is the best place to add a global listener initialization call in an Angular app? Take a look at this code snippet: export class AuthService { constructor( private store: Store<fromAuth.State>, private afAuth: AngularFireAuth ) { ...

What is the best way to apply three unique classes to multiple div elements using jQuery?

Utilizing jQuery to assign three different classes to my div elements with the same name. Here is the HTML: <div class="main-class"> <div class="myclass"></div> <div class="myclass"></div> <div class="myclass"></div& ...

Router DOM in conjunction with Next.js

I am attempting to extract the output of the code in navigation, but unfortunately it is generating a dreadful error: Unhandled Runtime Error Error: You cannot render a <Router> inside another <Router>. You should never have more than one in ...

Exploring VueJS Router History Mode with NGinx web server

After conducting research, I discovered several issues similar to the one I am facing. Currently, I have a docker-compose setup on Digital Ocean with NGinx, VueJS, and a Static Landing Page. Everything was working fine until I added a new route with a fo ...

The UseEffect function ceases to function properly upon refreshing the website

I'm currently using ReactJS for a project. I have a form that is intended to serve as the configuration for another form. The structure of this specific form is as follows: const [startingDate, setStartingDate] = useState(); const [endingDate, set ...

Closing a dropdown on outside click in NEXT.JS can be done by adding an event

Currently, I am in the process of developing an ecommerce platform that features a search input with results displayed in a dropdown. The search functionality is working as intended, but now I would like to implement a feature where the dropdown closes whe ...

Error encountered while attempting to load configuration "plugin:vue/no-layout-rules" for extension

Whenever I attempt to build or serve the vuejs build, I keep encountering an error with the title "no-layout-rules". I'm unsure what this error is referring to. The only information I could find related to it was on the eslint repository located here: ...

Send the ID of the checkbox to a PHP file using AJAX

Is it possible to generate a network graph by selecting checkboxes? When I choose one or more checkboxes and click the button, I expect to see a network graph with the selected checkboxes. It almost works, but when I select multiple checkboxes, only one ...