[英]How use jquery (or other external libraries) in Typescript?
作为学习 Typescript 的练习,我正在为当前项目转换 javascript。 该项目由flask 提供,并使用VSCode 进行编辑。 我非常想在 javascript 部分使用 Typescript,主要是为了改进 VSCode 中的智能感知和类型检查。
我通过 npm 安装了 @types/jquery,如果我在 .ts 文件中import $ from "jquery"
那么一切都很好,VSCode 中没有错误。 但是,当我使用 tsc 编译代码并在 chrome 中运行站点时,我的 javascript 代码中的import $ from "jquery"
在 chrome 控制台中显示“无法解析模块说明符“jquery”。 如果我注释掉该 javascript 行,则没有错误。
所以,我的问题是:如何将 Typescript 与外部库一起使用,从 CDN 加载带有 script 标签,而不会在编译的 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";
并使用它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.