GreenSock and TypeScript

Viewed 23

I am writing a program in TypeScript and compiling code to JavaScript before running it on a browser. This is my package.json scripts:

"scripts": {
  "clean": "rm -rf dist/",
  // gsap.min.js is under ts/src/lib/
  "build": "tsc && copyfiles -u 1 ts/src/lib/* dist/"
},

However, I cannot reference gsap in a TypeScript file as I get the the error Cannot find name 'gsap'. I believe this is because tsc does not read minified files (even if allowJs flag is true).

I can, however, use gsap fine in a JavaScript file, since the checking is less strict. (In JavaScript, referencing a variable that is not defined only throws an error when run, e.g. in browser console.)

Attempt to fix

I tried defining gsap, hoping gsap.min.js will then override the variable. However, gsap remains undefined at runtime (at least tsc compiles this with no errors). So this does not work.

<!-- index.html snippet -->
<script src="dist/src/lib/pseudo.js"></script>
<script src="dist/src/lib/gsap.min.js"></script>
// pseudo.js
let gsap: any;
1 Answers

If you use a bundler, then if you install gsap (npm install gsap) rather than just copying a minified version of it into your project, it should resolve the problem has gsap provides type definitions.

If you're not using a bundler, copy the .d.ts files containing the types (from https://github.com/greensock/GSAP/tree/master/types) into your project's directory tree, and if TypeScript doesn't automatically pick them up, point it at them via tsconfig.json. The type files include the necessary declaration to tell TypeScript about the gsap global (specifically, that declaration is in gsap-core.d.ts).

Related