如何在 HTML 中像普通 javascript 一样使用 NPM 包 [英] How to use NPM package as normal javascript in HTML

查看:164
本文介绍了如何在 HTML 中像普通 javascript 一样使用 NPM 包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的应用程序中使用 html2canvas JS 库.通过在我的 HTML 文件中直接加载 html2canvas.js 文件,我能够在我的应用程序中使用旧版本的 html2canvas.

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.

但新版本仅通过 npm 包支持.

But newer versions are supported only through npm packages.

当我尝试在我的 HTML 文件中包含更新的 html2canvas.js 时,它说

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

html2canvas 未定义

html2canvas is not defined

我曾尝试修改 html2canvas.js 文件,以便我可以直接在我的 HTML 文件中使用它,而无需使用任何其他包管理器或其他依赖项.

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.

我从这里下载了 html2canvas.我无法通过直接在 HTML 文件中加载这个文件来使用它.如下

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>

推荐答案

npm 安装的包位于 /node_modules/ 中,前端不能直接使用.要使用这些模块,您需要使用 ES6 语法并使用以下代码导入它们:

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"

然而,浏览器无法直接读取 ES6 语法.因此,您需要使用 Babel 将您的 ES6 代码转换为普通的 JS 代码.请参阅 https://hackernoon.com/use-es6-javascript-syntax-require-import-etc-in-your-front-end-project-5eefcef745c2

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

转换代码后,使用

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆