javascript - 如何在 Typescript 中使用 jquery(或其他外部库)?
问题描述
作为学习 Typescript 的练习,我正在为当前项目转换 javascript。该项目由烧瓶提供,并使用 VSCode 进行编辑。我非常想在 javascript 部分使用 Typescript,主要用于 VSCode 中改进的智能感知和类型检查。
我通过 npm 安装了@types/jquery,如果我import $ from "jquery"
的 .ts 文件中有,那么一切都很好,VSCode 中没有错误。但是当我用 tsc 编译代码并在 chrome 中运行该站点时,import $ from "jquery"
我的 javascript 代码中的 chrome 控制台中会出现“无法解析模块说明符“jquery””。如果我注释掉该 javascript 行,则没有错误。
所以,我的问题是:如何将 Typescript 与外部库一起使用,从 CDN 加载并带有脚本标签,而不会在编译的 javascript 代码中出现导入错误?
似乎应该有比返回所有编译代码并注释掉外部库的导入更好的方法。
# This code looks the same in both the.ts and.js file,
# but it gives a 'Failed to resolve module specifier "jquery"'
# error when the .js is run in my project.
# If I comment out the import in the .ts file,
# the .ts has error -Cannot find name '$'- and will not compile.
# If I comment out the import in the compiled .js file, the page loads fine.
import $ from "jquery"
function foo() {
$('#some-element')
}
<!-- jquery is loaded from CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
解决方案
首先通过npm安装jquery:
npm i jquery
接着
import $ from "jquery";
并使用它
推荐阅读
- c# - 消息=')' 附近的语法不正确。Source=Core .Net SqlClient 数据提供者
- odbc - Power BI ODBC - 如何选择架构
- java - 在 JSch 频道上运行脚本,但在找不到脚本时不会抛出异常
- xamarin.forms - 如何在 xamarin.forms 中扫描图像
- javascript - Node.js 需要一个相对于包根目录的文件
- mediarecorder - MediaRecorder:如何停止视频录制并在同一视频元素中播放?
- javascript - 我不知道为什么我变得不确定。我怎样才能使这项工作?
- javascript - 用require加载本地json文件?
- pandas - 删除所选列表中不存在的项目
- android - 喷气背包导航上的 NoSuchMethodError (safeargs)