## Search Terms - cjs - cjs extension - cjs files ## Suggestion Treat files with the `.cjs` file extension the same as the `.js` file extension, but disallowing **ES Module** syntax within them. ## Use Cases In packages with: ```json "type": "module", ``` in `package.json`, **Node** loads all `.js` files as ES modules. To load a file as a **CommonJS** module, one has to use the `.cjs` file extension. ## Examples ```js // foo.cjs // $ExpectType typeof Bar const Bar = require("./bar.cjs"); ``` > 📝 **Note:** In order to currently have typed `.cjs` imports, this file has to be named `bar.cjs.d.ts`: ```ts // bar.d.ts declare class Bar { constructor(); } export = Bar; ``` ```js // bar.cjs module.exports = class Bar { constructor() { // do stuff } }; ``` ## Checklist My suggestion meets these guidelines: * [x] This wouldn't be a breaking change in existing TypeScript/JavaScript code * [x] This wouldn't change the runtime behavior of existing JavaScript code * [x] This could be implemented without emitting different JS based on the types of the expressions * [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.) * [x] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals). ## Related Issues - <https://github.com/microsoft/TypeScript/issues/27957>
Activity
frank-dspeed commentedon Aug 7, 2020
If some one does want to test #39840 https://github.com/stealify/typescript
npm i -g vscode-typescript@https://github.com/stealify/typescript # Getting global path npm root -gHit f1 on keyboard open user settings and set
restart is not needed.
Raynos commentedon Feb 1, 2021
I would like to use the
.cjs&.mjsextensions with typescript as well. All three of these files are JavaScript files.a-ejs commentedon Feb 10, 2021
Agreed, seems odd that this isn't supported (or even planned?) yet.
hariombalhara commentedon Apr 30, 2021
For people coming to this thread, you can add
//@ts-checkat the top of a .cjs file to enable type checking for it.ExE-Boss commentedon Oct 12, 2021
Fixed in #45884 (TypeScript 4.5)