google / google/closure-compiler
Error in CJS module `variable exports is undeclared` when assigning to `exports`
- Dominant language
- JavaScript
- Stars
- 7.7k
- Forks
- 1.2k
- Avg merge
- 2d 12h
- Merged PRs (30d)
- 6
Description
CJS module support is bugged.
Consider [this library](https://www.npmjs.com/package/merge). This library is in CJS format and the first few lines of its code look like this:
```js
// "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isPlainObject = exports.clone = exports.recursive = exports.merge = exports.main = void 0;
module.exports = exports = main;
function main() { /** ... */ }
```
Notice the `exports = main` part. This is the root of the problem.
Consider a project that imports this library as a CJS module. Something along the lines of:
```js
const merge = require('merge')
```
The compiler raises an error:
```
node_modules/merge/lib/src/index.js:4:17: ERROR - [JSC_UNDEFINED_VARIABLE] variable exports is undeclared
4| module.exports = exports = main;
```
The compiler should not raise this error. [The `exports` variable shortcut should be declared/well-known as per CJS standard in the same way module.exports is declared.](https://nodejs.org/api/modules.html#exports-shortcut)
This issue is not only with the `merge` library. As far as I know, this library is generated with Webpack in a rather standard way. This means a great number of other libraries may be experiencing the same problem, whether they have been generated with Webpack or not. This means potentially a great number of libraries cannot be imported and used.
_Note: Webpack is capable of importing the `merge` library without any problems._
Compiler Version: v20230103
Build command:
```
java -jar ./scripts/closureCompiler.jar \
--entry_point=./src/js/index.js \
--js=./src/**.js \
--dependency_mode=PRUNE \
--process_common_js_modules=true \
--js=node_modules/merge/package.json \
--js=node_modules/merge/**.js \
--hide_warnings_for=node_modules \
--warning_level=VERBOSE \
--js_output_file=./dist/bundle.js \
--module_resolution=NODE \
--compilation_level=ADVANCED;
```
Contributor guide
Assessment
This issue has not been assessed yet.