javascriptnode.jsnode-moduleses6-modulesesmodules

NodeJS - How do I call separate imports based on 'if' condition for ES Modules?


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')
> }

Solution

  • 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