Input
index.js
if(process.env.NODE_ENV==='production'){require('./prod.js');}prod.js
console.log('side effect');exportdefault'production';Output
varsrc={};console.log('side effect');if(process.env.NODE_ENV==='production');export{srcasdefault};Expected Behavior
For the console.log('side effect'); to be delayed until the if-condition passes.
Note, this only happens because prod.js is an ESM file. If the export ... is removed for it to be interpreted as a CJS file, it will compile expectedly:
varsrc={};varprod={};varhasRequiredProd;functionrequireProd(){if(hasRequiredProd)returnprod;hasRequiredProd=1;console.log('side effect');// export default 'production';returnprod;}if(process.env.NODE_ENV==='production'){requireProd();}export{srcasdefault};Actual Behavior
The side effects of the ESM file are hoisted up and executed even if the if-condition doesn't pass.
Additional Information
Input
index.js
prod.js
Output
Expected Behavior
For the
console.log('side effect');to be delayed until the if-condition passes.Note, this only happens because prod.js is an ESM file. If the
export ...is removed for it to be interpreted as a CJS file, it will compile expectedly:Actual Behavior
The side effects of the ESM file are hoisted up and executed even if the if-condition doesn't pass.
Additional Information