简体   繁体   English

webpack & ES6 - 有条件的进出口

[英]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.但是在index.js中,我使用 CommonJS 语法有条件地导出模块。 Is it possible to do it with ES6?有可能用 ES6 做到吗? If yes, how?如果是,如何?

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

I am using webpack ^4.6.0 .我正在使用webpack ^4.6.0 Tried my luck with babel-plugin-dynamic-import-webpack but it didn't work.babel-plugin-dynamic-import-webpack我的运气,但它没有用。

I may not aware of some best practices or plugins that I can use, so I'd appreciate your thoughts.我可能不知道我可以使用的一些最佳实践或插件,所以我很感激你的想法。

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.在开发过程中, realValue 应该被修剪。 During a production build, mockValue should get trimmed.在生产构建期间,mockValue 应该被修剪。 To verify this, you could build the test project above and inspect the output for 'mock' (but you're not likely to find it).要验证这一点,您可以构建上面的测试项目并检查 output 中的“模拟”(但您不太可能找到它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM