'webpack & ES6 - conditional import and export
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.
Solution 1:[1]
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Brandon Lee Detty |