Movatterモバイル変換


[0]ホーム

URL:


Tryagent mode in VS Code!

Dismiss this update

Working with JavaScript

This topic describes some of the advanced JavaScript features supported by Visual Studio Code. Using the TypeScript language service, VS Code can provide smart completions (IntelliSense) as well as type checking for JavaScript.

IntelliSense

Visual Studio Code's JavaScriptIntelliSense provides intelligent code completion, parameter info, references search, and many other advanced language features. Our JavaScript IntelliSense is powered by theJavaScript language service developed by the TypeScript team. While IntelliSense should just work for most JavaScript projects without any configuration, you can make IntelliSense even more useful withJSDoc or by configuring ajsconfig.json project.

For the details of how JavaScript IntelliSense works, including being based on type inference, JSDoc annotations, TypeScript declarations, and mixing JavaScript and TypeScript projects, see theJavaScript language service documentation.

When type inference does not provide the desired information, type information may be provided explicitly with JSDoc annotations. This document describes theJSDoc annotations currently supported.

In addition to objects, methods, and properties, the JavaScript IntelliSense window also provides basic word completion for the symbols in your file.

Typings and Automatic Type Acquisition

IntelliSense for JavaScript libraries and frameworks is powered by TypeScript type declaration (typings) files. Type declaration files are written in TypeScript so they can express the data types of parameters and functions, allowing VS Code to provide a rich IntelliSense experience in a performant manner.

Many popular libraries ship with typings files so you get IntelliSense for them automatically. For libraries that do not include typings, VS Code'sAutomatic Type Acquisition will automatically install community maintained typings file for you.

Automatic type acquisition requiresnpmjs, the Node.js package manager, which is included with theNode.js runtime. In this image you can see IntelliSense, including the method signature, parameter info, and the method's documentation for the popularlodash library.

lodash typings

Type declaration files are automatically downloaded and managed by Visual Studio Code for packages listed in your project'spackage.json or that you import into a JavaScript file.

{  "dependencies": {    "lodash":"^4.17.0"  }}

You can alternately explicitly list packages to acquire type declaration files for in ajsconfig.json.

{  "typeAcquisition": {    "include": ["jquery"]  }}

Most common JavaScript libraries ship with declaration files or have type declaration files available.

Fixing npm not installed warning for Automatic Type Acquisition

Automatic Type Acquisition usesnpm, the Node.js package manager, to install and manage Type Declaration (typings) files. To ensure that Automatic Type Acquisition works properly, first ensure that you have npm installed on your machine.

Runnpm --version from a terminal or command prompt to quickly check that npm is installed and available.

npm is installed with the Node.js runtime, which is available for download fromNodejs.org. Install the current LTS (Long Term Support) version and the npm executable will be added by default to your system path.

If you have npm installed but still see a warning message, you can explicitly tell VS Code where npm is installed with thetypescript.npmsetting. This should be set to the full path of the npm executable on your machine, and this does not have to match the version of npm you are using to manage packages in your workspace.typescript.npm requires TypeScript 2.3.4+.

For example, on Windows, you would add a path like this to yoursettings.json file:

{  "typescript.npm":"C:\\Program Files\\nodejs\\npm.cmd"}

JavaScript projects (jsconfig.json)

The presence of ajsconfig.json file in a directory indicates that the directory is the root of a JavaScript project.jsconfig.json specifies the root files and the options for the language features provided by theJavaScript language service. For common setups, ajsconfig.json file is not required, however, there are situations when you will want to add ajsconfig.json.

  • Not all files should be in your JavaScript project (for example, you want to exclude some files from showing IntelliSense). This situation is common with front-end and back-end code.
  • Your workspace contains more than one project context. In this situation, you should add ajsconfig.json file at the root folder for each project.
  • You are using the TypeScript compiler to down-level compile JavaScript source code.

Location of jsconfig.json

To define our code as a JavaScript project, createjsconfig.json at the root of your JavaScript code as shown below. A JavaScript project is the source files of the project and should not include the derived or packaged files (such as adist directory).

jsconfig setup

In more complex projects, you may have more than onejsconfig.json file defined inside a workspace. You will want to do this so that the source code in one project does not appear in the IntelliSense of another project.

Illustrated below is a project with aclient andserver folder, showing two separate JavaScript projects:

multiple jsconfigs

Writing jsconfig.json

Below is a simple template forjsconfig.json file, which defines the JavaScripttarget to beES6 and theexclude attribute excludes thenode_modules folder. You can copy and paste this code into yourjsconfig.json file.

{  "compilerOptions": {    "module":"CommonJS",    "target":"ES6"  },  "exclude": ["node_modules","**/node_modules/*"]}

Theexclude attribute tells the language service which files are not part of your source code. If IntelliSense is slow, add folders to yourexclude list (VS Code will prompt you to do this if it detects slow completions). You will want toexclude files generated by a build process (such as adist directory). These files will cause suggestions to show up twice and will slow down IntelliSense.

You can explicitly set the files in your project using theinclude attribute. If noinclude attribute is present, then this defaults to including all files in the containing directory and subdirectories. When ainclude attribute is specified, only those files are included.

Here is an example with an explicitinclude attribute:

{  "compilerOptions": {    "module":"CommonJS",    "target":"ES6"  },  "include": ["src/**/*"]}

The best practice, and least error prone route, is to use theinclude attribute with a singlesrc folder. Note that file paths inexclude andinclude are relative to the location ofjsconfig.json.

For more information, see the fulljsconfig.json documentation.

Migrating to TypeScript

It is possible to have mixed TypeScript and JavaScript projects. To start migrating to TypeScript, rename yourjsconfig.json file totsconfig.json and set theallowJs property totrue. For more information, seeMigrating from JavaScript.

Note:jsconfig.json is the same as atsconfig.json file, only withallowJs set to true. Seethe documentation fortsconfig.json here to see other available options.

Type checking JavaScript

VS Code allows you to leverage some of TypeScript's advanced type checking and error reporting functionality in regular JavaScript files. This is a great way to catch common programming mistakes. These type checks also enable some exciting Quick Fixes for JavaScript, includingAdd missing import andAdd missing property.

Using type checking and Quick Fixes in a JavaScript file

TypeScript can infer types in.js files same as in.ts files. When types cannot be inferred, they can be specified using JSDoc comments. You can read more about how TypeScript uses JSDoc for JavaScript type checking inType Checking JavaScript Files.

Type checking of JavaScript is optional and opt-in. Existing JavaScript validation tools such as ESLint can be used alongside the new built-in type checking functionality.

You can get started with type checking a few different ways depending on your needs.

Per file

The easiest way to enable type checking in a JavaScript file is by adding// @ts-check to the top of a file.

// @ts-checklet itsAsEasyAs ='abc';itsAsEasyAs =123;// Error: Type '123' is not assignable to type 'string'

Using// @ts-check is a good approach if you just want to try type checking in a few files but not yet enable it for an entire codebase.

Using a setting

To enable type checking for all JavaScript files without changing any code, just add"js/ts.implicitProjectConfig.checkJs": true to your workspace or user settings. This enables type checking for any JavaScript file that is not part of ajsconfig.json ortsconfig.json project.

You can opt individual files out of type checking with a// @ts-nocheck comment at the top of the file:

// @ts-nochecklet easy ='abc';easy =123;// no error

You can also disable individual errors in a JavaScript file using a// @ts-ignore comment on the line before the error:

let easy ='abc';// @ts-ignoreeasy =123;// no error

Using jsconfig or tsconfig

To enable type checking for JavaScript files that are part of ajsconfig.json ortsconfig.json, add"checkJs": true to the project's compiler options:

jsconfig.json:

{  "compilerOptions": {    "checkJs":true  },  "exclude": ["node_modules","**/node_modules/*"]}

tsconfig.json:

{  "compilerOptions": {    "allowJs":true,    "checkJs":true  },  "exclude": ["node_modules","**/node_modules/*"]}

This enables type checking for all JavaScript files in the project. You can use// @ts-nocheck to disable type checking per file.

JavaScript type checking requires TypeScript 2.3. If you are unsure what version of TypeScript is currently active in your workspace, run theTypeScript: Select TypeScript Version command to check. You must have a.js/.ts file open in the editor to run this command. If you open a TypeScript file, the version appears in the lower right corner.

Global variables and type checking

Let's say that you are working in legacy JavaScript code that uses global variables or non-standard DOM APIs:

window.onload =function() {  if (window.webkitNotifications.requestPermission() ===CAN_NOTIFY) {    window.webkitNotifications.createNotification(null,'Woof!','🐶').show();  }else {    alert('Could not notify');  }};

If you try to use// @ts-check with the above code, you'll see a number of errors about the use of global variables:

  1. Line 2 -Property 'webkitNotifications' does not exist on type 'Window'.
  2. Line 2 -Cannot find name 'CAN_NOTIFY'.
  3. Line 3 -Property 'webkitNotifications' does not exist on type 'Window'.

If you want to continue using// @ts-check but are confident that these are not actual issues with your application, you have to let TypeScript know about these global variables.

To start,create ajsconfig.json at the root of your project:

{  "compilerOptions": {},  "exclude": ["node_modules","**/node_modules/*"]}

Then reload VS Code to make sure the change is applied. The presence of ajsconfig.json lets TypeScript know that your Javascript files are part of a larger project.

Now create aglobals.d.ts file somewhere your workspace:

interface Window {  webkitNotifications:any;}declare var CAN_NOTIFY:number;

d.ts files are type declarations. In this case,globals.d.ts lets TypeScript know that a globalCAN_NOTIFY exists and that awebkitNotifications property exists onwindow. You can read more about writingd.ts in theTypeScript documentation.d.ts files do not change how JavaScript is evaluated, they are used only for providing better JavaScript language support.

Using tasks

Using the TypeScript compiler

One of the key features of TypeScript is the ability to use the latest JavaScript language features, and emit code that can execute in JavaScript runtimes that don't yet understand those newer features. With JavaScript using the same language service, it too can now take advantage of this same feature.

The TypeScript compilertsc can down-level compile JavaScript files from ES6 to another language level. Configure thejsconfig.json with the desired options and then use the –p argument to maketsc use yourjsconfig.json file, for exampletsc -p jsconfig.json to down-level compile.

Read more about the compiler options for down level compilation in thejsconfig documentation.

Running Babel

TheBabel transpiler turns ES6 files into readable ES5 JavaScript with Source Maps. You can easily integrateBabel into your workflow by adding the configuration below to yourtasks.json file (located under the workspace's.vscode folder). Thegroup setting makes this task the defaultTask: Run Build Task gesture.isBackground tells VS Code to keep running this task in the background. To learn more, go toTasks.

{  "version":"2.0.0",  "tasks": [    {      "label":"watch",      "command":"${workspaceFolder}/node_modules/.bin/babel",      "args": ["src","--out-dir","lib","-w","--source-maps"],      "type":"shell",      "group": {"kind":"build","isDefault":true },      "isBackground":true    }  ]}

Once you have added this, you can startBabel with the⇧⌘B (Windows, LinuxCtrl+Shift+B) (Run Build Task) command and it will compile all files from thesrc directory into thelib directory.

Tip: For help with Babel CLI, see the instructions inUsing Babel. The example above uses the CLI option.

Disable JavaScript support

If you prefer to use JavaScript language features supported by other JavaScript language tools such asFlow, you can disable VS Code's built-in JavaScript support. You do this by disabling the built-in TypeScript language extensionTypeScript and JavaScript Language Features (vscode.typescript-language-features) which also provides the JavaScript language support.

To disable JavaScript/TypeScript support, go to the Extensions view (⇧⌘X (Windows, LinuxCtrl+Shift+X)) and filter on built-in extensions (Show Built-in Extensions in the...More Actions dropdown), then type 'typescript'. Select theTypeScript and JavaScript Language Features extension and press theDisable button. VS Code built-in extensions cannot be uninstalled, only disabled, and can be re-enabled at any time.

TypeScript and JavaScript Language Features extension

Partial IntelliSense mode

VS Code tries to provide project-wide IntelliSense for JavaScript and TypeScript, which is what makes features such as auto-imports andGo to Definition possible. However, there are some cases where VS Code is limited to working only with your currently opened files and is unable to load the other files that make up your JavaScript or TypeScript project.

This can happen in a few instances:

  • You are working with JavaScript or TypeScript code onvscode.dev orgithub.dev and VS Code is running in the browser.
  • You open a file from a virtual file system (such as when using theGitHub Repositories extension).
  • The project is currently loading. Once loading completes, you will start getting project-wide IntelliSense for it.

In these cases, VS Code's IntelliSense will operate inpartial mode. Partial mode tries its best to provide IntelliSense for any JavaScript or TypeScript files you have open, but is limited and is not able to offer any cross-file IntelliSense features.

Which features are impacted?

Here's an incomplete list of features that are either disabled or have more limited functionality in partial mode:

  • All opened files are treated as part of a single project.
  • Configuration options from yourjsconfig ortsconfig (such astarget) are not respected.
  • Only syntax errors are reported. Semantic errors — such as accessing an unknown property or passing the wrong type to a function — are not reported.
  • Quick Fixes for semantic errors are disabled.
  • Symbols can only be resolved within the current file. Any symbols imported from other files will be treated as being of theany type.
  • Commands such asGo to Definition andFind All References will only work for opened files instead of across the entire project. This also means that symbol from any packages you install undernode_module will not be resolved.
  • Workspace symbol search will only include symbols from currently opened files.
  • Auto imports are disabled.
  • Renaming is disabled.
  • Many refactorings are disabled.

Some additional features are disabled onvscode.dev andgithub.dev:

Checking if you are in partial mode

To check if the current file is using partial mode IntelliSense instead of project-wide IntelliSense, hover over theJavaScript orTypeScript language status item in the status bar:

Partial mode status item

The status item will showPartial mode if the current file is in partial mode.

05/08/2025

[8]ページ先頭

©2009-2025 Movatter.jp