CommonJS compatibility does not work as expected · Issue #3360 · google/closure-compiler (original) (raw)
The compiler puts each commonJs module into default
property of the imported object.
// ecma import commonJs from './common-js'
console.log('requiring a common js from ecma:') console.log(commonJs)
CommonJS From ECMA | CommonJS From CommonJS |
---|---|
// common-js.js const commonJs2 = require('./common-js2') module.exports = () => { console.log('default common js export') } module.exports['named'] = () => { console.log('named common js export') } console.log('requiring a ' + 'common js from common js:') console.log(commonJs2) | // common-js2.js module.exports = () => { console.log('default common js ' + 'export2') } module.exports['named'] = () => { console.log('named common js ' + 'export2') } |
Run the compiler
java -jar /Users/zavr/node_modules/google-closure-compiler-java/compiler.jar
--compilation_level ADVANCED --language_out ECMASCRIPT_2017 --formatting PRETTY_PRINT
--process_common_js_modules --entry_point
example/commonjs/index.js --module_resolution NODE --js
example/commonjs/index.js example/commonjs/common-js.js example/commonjs/common-js2.js
Get the output
'use strict'; var a = () => { console.log("default common js export2"); }; a.named = () => { console.log("named common js export2"); }; var b = {default:() => { console.log("default common js export"); }}; b.default.named = () => { console.log("named common js export"); }; console.log("requiring a common js from common js:"); console.log(a); console.log("requiring a common js from ecma:"); console.log(b);
Execute the output
requiring a common js from common js: { [Function: a] named: [Function] } requiring a common js from ecma: { default: { [Function: default] named: [Function] } }
This does not make sense. I shouldn't write .default
as confirmed here #3308. When it comes to Babel-compiled modules, it's a nightmare. Babel exports { default: code } itself, so the currently closure-compatible code becomes
import erte from '@a-la/fixture-babel'
console.log(erte.default.default()) console.log(erte.default.c()) console.log(erte.default.b())
And if you actually try to execute in with babel, you get
console.log(_.default.default.default());
^
TypeError: Cannot read property 'default' of undefined
Developers developers developers developers
Babel Babel Babel Babel
Default Default Default Default