Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NPM package as normal javascript in HTML

Tags:

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>
like image 968
Anil Agrawal Avatar asked Dec 13 '19 06:12

Anil Agrawal


People also ask

Can we use NPM package in JavaScript?

NPM is the default package manager for node. It is used to install, share, and manage javascript packages in a project.

Can I use npm module in browser?

If you simply want to test out some NPM modules right inside your browser without setting up an entire app, you can use Browserify in three simple steps to use NPM modules.

Can I use TypeScript NPM package in JavaScript?

For NPM Packages, TypeScript is pretty slick in that its output can be leveraged in both JavaScript and TypeScript projects.

What is npm module in JavaScript?

NPM is a package manager for Node. js packages, or modules if you like. www.npmjs.com hosts thousands of free packages to download and use. The NPM program is installed on your computer when you install Node.js. NPM is already ready to run on your computer!


2 Answers

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.

like image 169
Anthony Poon Avatar answered Oct 04 '22 10:10

Anthony Poon


You can use the CDN for such library. In this case, check here: https://cdnjs.com/libraries/html2canvas

You should find one for production and regular development there. (https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js) =>development

<script>
  const htmlCanvas = require("htmlcanvas")
</script>
like image 30
Tolumide Avatar answered Oct 04 '22 10:10

Tolumide