【发布时间】:2020-04-02 03:37:59
【问题描述】:
作为学习 Typescript 的练习,我正在为当前项目转换 javascript。 该项目由烧瓶提供,并使用 VSCode 进行编辑。我非常想在 javascript 部分使用 Typescript,主要是为了改进 VSCode 中的智能感知和类型检查。
我通过 npm 安装了 @types/jquery,如果我的 .ts 文件中有 import $ from "jquery",那么一切都很好,VSCode 中没有错误。但是,当我使用 tsc 编译代码并在 chrome 中运行该站点时,我的 javascript 代码中的 import $ from "jquery" 在 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>
【问题讨论】:
标签: javascript jquery typescript visual-studio-code