简体   繁体   中英

In VS Code How Can I Automatically Import "assert" in a React Node App?

In Visual Studio Code you can automatically import most things by moving the focus to the imported term, and then using the "quick fix" feature ( CTRL +. for me). You'll then be given an option to have VS Code add an import for the term to the top of your file for you... unless the term is assert .

( NOTE: I believe you need to have "checkJs": true in your jsconfig.js for this to work... or else be using Typescript.)

What's strange is, the "assert" module is available, as part of Node itself! It seems that VS Code just isn't aware that it's available, and I'm not sure how to make it aware.

Is there any way (eg. a VS Code setting, a jsconfig.json option, etc.) that would to make it recognize the existence of the assert module when it comes to automatic imports?

I think it is a bug and it should work for all build in modules.


Long explanation when it works and when not.

It can propose to import assert but in a strange way.

I have a simple JavaScript project with a jsconfig.json file with

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "checkJs": true
  },
  "exclude": ["node_modules"]
}

As you have mention "checkJs": true is essential to get the required CodeAction (QuickFix) options.

Or you can add as a first line in the .js files

//@ts-check

My app.js file is very simple

assert(5 > 7, "Always False");

I get the red squiggles, but no import suggestion in the Quick Fix list.

If I add any require statement for a build in module I get import suggestions in the Quick Fix list ( import 'assert' from module "console" and import 'assert' from module "assert" )

var zlib = require('zlib');
assert(5 > 7, "Always False");

If I choose one of the imports I get

var zlib = require('zlib');
const assert = require('assert');
assert(5 > 7, "Always False");

And running the script in Node.js throws on the assert as expected.

Debugger attached.
Waiting for the debugger to disconnect...
assert.js:374
    throw err;
    ^

AssertionError [ERR_ASSERTION]: Always False
[snip....]
  generatedMessage: false,
  code: 'ERR_ASSERTION',
  actual: false,
  expected: true,
  operator: '=='
}
Process exited with code 1

If I have an app.js with

var gzip = zlib.createGzip();

I can't get a Quick Fix to import zlib.

Adding the import myself makes the script run.

var zlib = require('zlib');
var gzip = zlib.createGzip();

I wonder which modules can generate a Quick Fix suggestion.

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