I am building a PixiJS game with native ES modules, without using a bundler such as Parcel or Rollup.
I am also loading PixiJS as a native module, I found the module in node_modules/pixi.js/dist/esm/pixi.js
. I can now use:
import { Sprite } from './pixi.mjs'
The only problem is that the accompanying index.d.ts
file is not recognised by VS Code (I found this file in node_modules/pixi.js/index.d.ts
), so type checking for PixiJS doesn't work correctly, even though the code DOES run!
My folder structure is super simple. There is not even a package.json
.
index.html
js/app.js
js/pixi.mjs
js/pixi.mjs.map
js/index.d.ts
How can I force VS Code to read the index.d.ts
file?
There are a couple of issues with this approach.
First of all, if you look at the types installed by pixi.js in node_modules/pixi.js/index.d.ts
you will find that it is mostly empty, and
it references external packages starting with @pixi
. This is due to the mono-repo approach in the pixi project.
You will only fulfill those references if these packages are installed as npm modules (which happens automatically after installing pixi.js) and for which you need a package.json
so that TypeScript finds them by their package name.
Secondly, VS Code (or better said, the TypeScript engine) is not capable of relating the files pixi.mjs
and index.d.ts
once they are moved out of the node_modules
folder. Although the classes are named the same (Sprite, Container, etc.), TypeScript cannot safely conclude that they refer to the same thing.
This workflow is automatic when using npm thanks to the types
property in node_modules/pixi.js/package.json
. As an alternative, you can rename the file index.d.ts
to pixi.mjs.d.ts
and TypeScript will relate them by file name.
This is the folder structure that TypeScript can understand:
index.html
js/app.js
js/pixi.mjs
js/pixi.mjs.d.ts
js/pixi.mjs.map
Finally, the previous fixes will only provide type inference but no error detection in js files. If you want VS Code to report errors, you need to create a tsconfig.json
file with the following settings:
{
"compilerOptions": {
"noEmit": true,
"checkJs": true,
},
"include": ["js/*.js"],
}