Add Intellisense for third-party JavaScript libraries in VS Code (it is not always automatic)

Rob OLeary - Dec 28 '20 - - Dev Community

In VS Code, you may have noticed that if you are using a third-party JavaScript library in your front-end code, you don't get any IntelliSense goodness. 🙁

This is for the case where you using a script tag to include a third-party library.

<!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>
Enter fullscreen mode Exit fullscreen mode

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

IntelliSense for JavaScript libraries and frameworks is powered by TypeScript type declaration files (files with the .d.ts extension) . Type declaration files are written in TypeScript so that they can express 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. This is a fairly common scenario in front-end codebases.

Gimme, gimme. Im getting IntelliSense withdrawal! 😖

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

npm install --save-dev @types/gsap
Enter fullscreen mode Exit fullscreen mode

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.

intellisense

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


You can subscribe to my RSS feed to get my latest posts.


. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player