google / google/closure-compiler

CommonJS compatibility does not work as expected

Open
#3,360 15 comments 0 reactions 1 assignee Claimed by @ChadKillingsworth View on GitHub
internal-issue-created triage-done
Dominant language
JavaScript
Stars
7.7k
Forks
1.2k
Avg merge
2d 12h
Merged PRs (30d)
6

Description

The compiler puts each commonJs module into `default` property of the imported object.
```js
// ecma
import commonJs from './common-js'

console.log('requiring a common js from ecma:')
console.log(commonJs)
```

CommonJS From ECMACommonJS From CommonJS

```js
// 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)
```

```js
// common-js2.js
module.exports = () => {
console.log('default common js '
+ 'export2')
}
module.exports['named'] = () => {
console.log('named common js '
+ 'export2')
}
```

Run the compiler
```fs
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

```js
'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
```jsx
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 https://github.com/google/closure-compiler/issues/3308. When it comes to Babel-compiled modules, it's a nightmare. Babel exports { default: code } itself, so the currently closure-compatible code becomes

```js
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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.