Search code examples
angulartypescriptautodesk-viewer

Using THREE from forge-viewer/node_modules/@types/three causes compiler error


I need to use Viewer.setThemingColor() method that requires a parameter of type THREE.Vector4.

I am working with Angular 9 and I have installed @types/forge-viewer that also includes a definition for three at forge-viewer/node_modules/@types/three.

Visual Studio Code picks up the definition of THREE.Vector4 and inserts import * as THREE from 'forge-viewer/node_modules/@types/three' but the ng build command throws an error:

Can't resolve 'forge-viewer/node_modules/@types/three'.

I have tried to add three to both tsconfig.app.json (types) and tsconfig.json (typeRoots) in many variations but that does not help.

Additional installing of @types/three and importing from 'three' will fix the compiler error but it creates duplicate definitions in different locations and Visual Studio Code will only automatically see the location from forge-viewer forge-viewer/node_modules/@types/three and not three.

What is the problem her and how to fix it?


Solution

  • I found a way to avoid a compiler error when THREE objects are referenced in code without installing @types/three. In the TS file where something form THREE is referenced, for example a THREE.Vector4, instead of importing THREE from a module insert a "fake" declaration

    declare var THREE: any;
    

    The positive outcomes are:

    1. No compilation error;
    2. No second copy of three.js loaded from a webpack

    A negative outcome is losing a TypeScript intellisense in VS Code but it could be mitigated by temporarily installing the @types/three, developing and testing the code and then removing @types/three.