12

I have some configuration keys like below:

/config
  /db
    /dev.js
    /index.js
    /prod.js

I import keys like this:

import dbConfig from './config/db'

But in index.js, I use CommonJS syntax to export module conditionally. Is it possible to do it with ES6? If yes, how?

module.exports = process.env.NODE_ENV === 'production'
  ? require('./prod')
  : require('./dev');

I am using webpack ^4.6.0. Tried my luck with babel-plugin-dynamic-import-webpack but it didn't work.

I may not aware of some best practices or plugins that I can use, so I'd appreciate your thoughts.

Mehmet N. Yarar
  • 576
  • 9
  • 17
  • 1
    Possible duplicate of [How can I conditionally import an ES6 module?](https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module) – Liam Apr 19 '18 at 11:51
  • 7
    I'm aware of this post, but it doesn't cover how to export conditionally. Suggested solution returns a promise and webpack yells at me when I export after resolve/dynamic module is imported. – Mehmet N. Yarar Apr 19 '18 at 13:20
  • You can use `require` or `import` (both worked for me), but will need to access the `default` attribute if the module you are importing uses `export default` (i.e. `require('./prod').default`) – TheLandolorien Oct 20 '20 at 01:26

1 Answers1

0

I don't believe you actually need to worry about this. There are tree-trimming algorithms in modern build systems that should ensure you end up with only one version in dev or production.

# mockValue.js
const mockValue = 'mock';

export default mockValue;

# realValue.js
const realValue = 'real';

export default realValue;

# test.js
import mockValue from 'mockValue';
import realValue from 'realValue';

let test;
if (process.env.NODE_ENV === 'production') {
  test = realValue;
} else {
  test = mockValue;
}

export default test;

# index.js
import test from 'test';

console.log(test);

During development, realValue should get trimmed. During a production build, mockValue should get trimmed. To verify this, you could build the test project above and inspect the output for 'mock' (but you're not likely to find it).