Add missing intellisense for JavaScript libraries in VS Code

You may have noticed that if you use a script tag to include a library, you don’t get any intellisense suggestions in your JavaScript file. VS Code doesn’t seem to know about the library.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
<script src="https://unpkg.co/gsap@3/dist/gsap.min.js"></script>
<script src="main.js"></script>
</body>
</html>

In this example, I’m including the Greensock (GSAP) animation library. In main.js, I don’t get intellisense suggestions for GSAP.

Intellisense for JavaScript libraries and frameworks is powered by TypeScript type declaration files (with the .d.ts extension). These files have the data types of parameters and functions, allowing VS Code to provide a rich intellisense experience.

VS Code has automatic type aquisition, which means that it will automatically fetch these types for you, but with a big caveat.

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

In my use case, I do neither. With the way website are being built, most people have a package.json with the libraries included, so they might not bump into this. But it it can happen to beginners and people eschewing tools.

Gimme, gimme. Im getting intellisense withdrawal! 😅

The simplest solution is to find the NPM package with the types for the library you are using, and include it as a dev dependency. This way, your code can remain the same.

Bash
npm install --save-dev @types/gsap

Once the download completes, intellisense is available immediately.

intellisense for gsap

Types for some libraries are sourced from the DefinitelyTyped GitHub repo. Many popular packages follow this @types/<<library name>> naming convention also.

You can search for NPM packages that have type definitions using https://www.typescriptlang.org/dt/search.

You may find that some packages are not up-to-date. I found @types/gsap to be incomplete. It does not include a definition for the gsap object. The gsap npm package covers the entire API. So, you can install that as a dependency instead - npm install --save-dev gsap.

One thing to note is that the type definitions don’t provide intellisense inside script tags in your HTML file no matter what you do. There is an open issue requesting this feature. Hopefully, this will be resolved in the near future! 🤞

Tagged