Typescript [4.8.2] is adding invalid javascript for *.cjs files
See original GitHub issueBug Report
My project is set to emit ESNext modules. I have a variety of TS files, but I also have a single .cjs
file, which needs to remain CommonJS to try and require legacy packages.
My input looks like this:
module.exports = {
tryRequire(modulePath) {
return require(modulePath);
},
};
I expect the output I get from TypeScript 4.7.4:
module.exports = {
tryRequire(modulePath) {
return require(modulePath);
},
};
When I upgrade to TypeScript 4.8.2, it now emits an extra export {}
at the end of the .cjs file:
module.exports = {
tryRequire(modulePath) {
return require(modulePath);
},
};
export {}
This causes Node to fail parsing the .cjs
file because export
does not exist in the .cjs context.
🕗 Version & Regression Information
Worked in 4.7.4, broken in 4.8.2, also broken in current nightly (4.9.0-dev.20220905).
Repro here
Issue Analytics
- State:
- Created a year ago
- Comments:9 (4 by maintainers)
Top Results From Across the Web
Documentation - Migrating from JavaScript - TypeScript
How to migrate from JavaScript to TypeScript. ... During our JS to TS migration, we'll need to separate our input files to prevent...
Read more >Typescript ReferenceError: exports is not defined
Add the following line before other references to JavaScript. ... that I export in that index.js file in a separate type="module" script ...
Read more >Understanding (all) JavaScript module formats and tools
TypeScript module: Transpile to CJS, AMD, ES, System modules ... To use this module file in browser, add a <script> tag and specify...
Read more >Configuring Jest
It is recommended to define the configuration in a dedicated JavaScript, TypeScript or JSON file. The file will be discovered automatically, if it...
Read more >Firebase JavaScript SDK Release Notes - Google
Added types fields to exports object in package.json files for all published ... Changed exports paths to always point to .cjs bundles when...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
I am unblocked here. I do still think it’s not ideal to be emitting invalid cjs but at least I have a workaround. 😃
Yes! That fixed it. I changed to
module: "nodenext"
and addedtype: "module"
to the package.json to achieve the expected output (ESM by default, CJS for cjs files.)