Search code examples
typescripttypescript-typingscanvasjs

CanvasJs in Typescript


I am trying to use canvasJS in my typescript file. I have the declaration file - index.d.ts. and the corresponding javascript file is https://canvasjs.com/assets/script/canvasjs.min.js. I am using require.js in my project. Unfortunately when I run, webpage crashes indicating that require.js couldn't find the corresponding index.js. If i create an index.js and copy contents of the https://canvasjs.com/assets/script/canvasjs.min.js. everything will be fine.

I don't want to do that. Instead I would like the index.d.ts to directly refer or look for the url. How to do this?


Solution

  • That is because index.d.ts only holds the definition, it will not import any library. What I would suggest is to use npm install canvasjs to install the package, then add the types using: npm install --save @types/canvasjs. This will put the canvasjs into the node_modules. When you try importing it using

    import CanvasJS from 'canvasjs';
    

    typescript will try resolving the import the library using those rules, in short, it will recursively try finding the node_modules folder starting from the file importing the canvasjs and escalating the task to its parent folder if not found.

    Another way is to put the import https://canvasjs.com/assets/script/canvasjs.min.js in the header of your html file (assuming you do have one) or somewhere in your js code, add the typing to npm using npm install --save @types/canvasjs and finally modify the tsconfig.json

    {
       "compilerOptions": {
           "types" : ["canvasjs"]
       }
    }