0

Followed a tutorial that uses CommonJS to export/require different keys based on the environment. How do I get it to work with ES Modules import/export?

This was the code he used:

if (process.env.NODE_ENV === "production") {
module.exports = require('./prod')
else {
module.exports = require('./dev')
> }
Meaetin
  • 3
  • 1

3 Answers3

2

First of all, you have to import the functions/components.

import Production from "./prod"
import Development from "./dev"

Then you can check the condition, and assign the specific function/component to a variable. Finally, you can export it.

let defaultExport

if (process.env.NODE_ENV === "production") {
  defaultExport = Production
} else {
  defaultExport = Development
}

export default defaultExport

The full code will look like this

import Production from "./prod"
import Development from "./dev"

let defaultExport

if (process.env.NODE_ENV === "production") {
  defaultExport = Production
} else {
  defaultExport = Development
}

export default defaultExport
Musab
  • 149
  • 1
  • 8
1

Not sure what you are trying to do but you can try ternary operator

module.export = process.env.NODE_ENV === "production" ? require(./prod) : require(./dev)
geeky01adarsh
  • 312
  • 3
  • 14
-1

If you are exporting components as default export

import Production from './prod';
import Development from './dev';

let FinalProduct;

if (process.env.NODE_ENV === "production") {
    finalProduct = Production
else {
    finalProduct = Development
}

export default FinalProduct