1

I am trying to implement print functionality in my Angular2 Application. I came across this package html2canvas. It looks impressive but when I am trying to include that in my application it is throwing me an error.

Here are my steps which I have followed

  1. Downloaded js file from here
  2. Added <script src="scripts/html2canvas.js"></script>
  3. declared in TS file declare var html2canvas: any;
  4. added code to print (when user click print button - test code)

    printview(): void { html2canvas(document.body).then(function(canvas) { document.body.appendChild(canvas); }); }

but as soon as user click print button I get following error

browser_adapter.ts:78 ReferenceError: html2canvas is not defined

Any help or hint would be useful ...

microchip78
  • 2,040
  • 2
  • 28
  • 39

1 Answers1

6

TypeScript needs definitions in order to indentify VanillaJS frameworks.

Think of it this way, TypeScript relies on the TS files it haves in order to indentify objects, html2canvas is included in your HTML but TypeScript has now way of identifying the html2canvas object.

Possible solutions:


Best:

Upgrade to TypeScript 2.* and use the new 'typeRoots' and 'types' fields.

Follow these steps after upgrading to TS 2.0+

npm i @types/html2canvas

and update your 'tsconfig.json' file like so:

{ "compilerOptions": { // your options, "typeRoots": [ "./node_modules/@types" ], "types": [ "html2canvas" ] } }


Acceptable:

Manually download the definition file (not recommended as you need to maintain every updated definition by manually fetching the latest version).


Quick and dirty:

Create a 'references.d.ts' file in your root folder (next to the tsconfig.json) and write the following:

declare var html2canvas: any;

By doing this, the transpiler will know that you as a coder are aware of 'html2canvas''s existence, so it will not consider it as an error (be major disadvantage with this 'solution' is that you have no IntelliSense support for the library so basically you're just writing code in blind.


So for a solid project I recommend the Best solution, if you just want to play around with TS for testing purposes, any of the other solutions are ok :).

If you want to read more about the new type properties included in TS2, read the response to this other question:

Typescript 2.0. "types" field in tsconfig.json

and of course consult the documentation:

https://www.typescriptlang.org/docs/handbook/compiler-options.html

Community
  • 1
  • 1
Vlad Jerca
  • 2,194
  • 1
  • 10
  • 5
  • With the 'typeRoots' specified in the `tsconfig,json` file, isn't an error to additionally specify the `types` element? I.e. shouldn't it be enough to just specify `typeRoots`? – Cuga May 16 '17 at 13:15
  • Thanks for the great answer. I'm never getting into the .then( ... ). I get the following error: __WEBPACK_IMPORTED_MODULE_7_html2canvas__ is not a function Any thoughts would be appreciated! – Toolsmythe Jun 05 '17 at 21:01