Search code examples
reactjscdnjspdf

How to use jspdf CDN in a react project


I am developing a ReactJS application that must produce a PDF file. I want to use jspdf so I added the following line to the header of my index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

Then I went to the javascript file containing my actual component and I wrote

var pdf=new jsPDF();

Obtaining the error: 'jsPDF is not defined'. So I added this line at the top of the file containing the component:

import {jsPDF} from 'jspdf';

This has led to the npm error Module not found: Can't resolve 'jspdf' in 'C:\my-app\src'. So I should I use a CDN in react?


Solution

  • At the time you are transpiling your code, your node env knows nothing about jsPDF that it's included in the final page. You need to ignore this.

    Define it as a global. Put this comment at the top of your JS file:

    /* global jsPDF */