简体   繁体   中英

How to enable type checking of mjs files in VS Code

I have a project with js files, where I enabled type checking across multiple modules (highlighting wrong parameters etc of function imported from different module) in VS Code by creating this jsconfig.json:

{
  "compilerOptions": {
    "checkJs": true
  }
}

Now, I read that typescript 4.5 supports mjs files https://github.com/microsoft/TypeScript/issues/27957

So I installed typescript 4.5 beta, node 17, and modified jsconfig.json to this:

{
  "compilerOptions": {
    "module": "node12",
    "moduleResolution": "node",
    "checkJs": true
  }
}

but it still doesn't work for mjs files, and I also get this error in jsconfig.json:

Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'esnext'

Any idea how to enable type checking for mjs files across multiple modules?

Consider using these tsconfig.json options:

{
  "compilerOptions": {
    "module": "NodeNext",
    "target": "ESNext",
    "moduleResolution": "NodeNext"
  },
  "include": ["**/*.mjs"]
}

=======

Here's ALL the changes I did along with adding.mjs support. I don't think they are all strictly necessary, but I want to share for completeness:

Modified my package.json type-check script:

"type-check": "tsc --pretty --noEmit && tsc --pretty --noEmit --project tsconfig.mjs.json",

Here's my tsconfig.mjs.json file:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "NodeNext",
    "target": "ESNext",
    "moduleResolution": "NodeNext"
  },
  "include": ["**/*.mjs"]
}

Run:

yarn add @typescript-eslint/eslint-plugin @typescript-eslint/parser --dev
yarn remove typescript
yarn add typescript # use latest

Likely, you will get an error that you need to use typescript nightly build to actually type-check mjs files. Run:

yarn remove typescript
yarn add typescript@next --dev

I know that you were asking for a solution to typecheck all .mjs files automatically, but maybe the following might be interesting for others:

As long as you only have a few .mjs files that you want to typecheck with TypeScript, you can just add //@ts-check in the first line of each .mjs file.

Check the Typescript docs for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM