Skip to content

Support type checking .cjs files #38784

Description

@ExE-Boss

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:

"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

// 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:

// bar.d.ts
declare class Bar {
	constructor();
}
export = Bar;
// bar.cjs
module.exports = class Bar {
	constructor() {
		// do stuff
	}
};

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Related Issues

Activity

  1. frank-dspeed commented on Aug 7, 2020

    @frank-dspeed

    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 -g

    Hit f1 on keyboard open user settings and set

    "typescript.tsdk": "{your_global_npm_path}/vscode-typescript/typescript/lib"

    restart is not needed.

  2. Raynos commented on Feb 1, 2021

    @Raynos

    I would like to use the .cjs & .mjs extensions with typescript as well. All three of these files are JavaScript files.

  3. a-ejs commented on Feb 10, 2021

    @a-ejs

    Agreed, seems odd that this isn't supported (or even planned?) yet.

  4. hariombalhara commented on Apr 30, 2021

    @hariombalhara

    For people coming to this thread, you can add //@ts-check at the top of a .cjs file to enable type checking for it.

  5. ExE-Boss commented on Oct 12, 2021

    @ExE-Boss
    ContributorAuthor

    Fixed in #45884 (TypeScript 4.5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions