首页 > 解决方案 > 如何在 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>

标签: javascriptjquerytypescriptvisual-studio-code

解决方案


首先通过npm安装jquery:

npm i jquery

接着

import $ from "jquery";

并使用它


推荐阅读