How to use NPM package as normal javascript in HTML

Anil Agrawal picture Anil Agrawal · Dec 13, 2019 · Viewed 12.6k times · Source

I want to use html2canvas JS library in my application. I were able to use older versions of html2canvas in my application by directly loading html2canvas.js file in my HTML file.

But newer versions are supported only through npm packages.

When I try to include newer html2canvas.js in my HTML file, it says

html2canvas is not defined

I had tried to modify html2canvas.js file, so that I can directly use it in my HTML file, without using any other package manager or other dependencies.

I had downloaded html2canvas from here. I am unbale to use it by loading this file directly in HTML file. as below

<script type="text/javascript" src="js/html2canvas.js"></script>

Answer

Anthony Poon picture Anthony Poon · Dec 13, 2019

Package installed by npm is located in /node_modules/ which cannot be used by front end directly. To use those modules, you need to use ES6 syntax and import them by using the following code:

// Just an example, you need to read the doc to see how to import
import html2cavas from "html2cavas"

However, browser cannot read ES6 syntax directly. As a result, you need to use Babel to transpile your ES6 code to normal JS code. See https://hackernoon.com/use-es6-javascript-syntax-require-import-etc-in-your-front-end-project-5eefcef745c2

After you transpiled your code, use the <script> tag to import the transpiled code.

Alternatively, you might be able to copy what you need from /node_modules/ and copy it to your js folder. However it is not recommended.