简体   繁体   English

在VS Code中使用TypeScript中的jQuery

[英]Use jQuery in TypeScript in VS Code

I'm trying to add jQuery to a TypeScript project in Visual Studio Code. 我正在尝试将jQuery添加到Visual Studio Code中的TypeScript项目中。 The goal is to use it via the $, as I would do in plain JavaScript, WITHOUT providing the jQuery tag in the head of my html. 目标是通过$使用它,就像在纯JavaScript中一样,没有在我的html头部提供jQuery标记。

I have my jquery and its definition installed on the project: 我在项目中安装了我的jquery及其定义:

包

Hence, $ and intellisense is working like a charm: 因此,$和intellisense就像一个魅力:

VSCode

But opening the page I'm getting the error: "ReferenceError: $ is not defined". 但打开页面我收到错误:“ReferenceError:$未定义”。

I have read several related topics, including this , but the question there is about Visual Studio, and the last answer also suggest to load jQuery via tag in html, what I'm trying to avoid. 我已经阅读了几个相关的主题,包括这个 ,但是关于Visual Studio的问题,最后的答案还建议在html中通过标签加载jQuery,我正在努力避免。

So how do I tell the ts compiler to include jQuery? 那么如何告诉ts编译器包含jQuery呢? I cannot import it because there is no export in jQuery. 我无法导入它,因为jQuery中没有导出。 Am I missing something from tsconfig.json? 我错过了tsconfig.json的内容吗?

tsconfig

Your packages are installed in the node_modules folder. 您的软件包安装在node_modules文件夹中。 You need to somehow serve these up on the page. 你需要以某种方式在页面上提供这些服务。 As it stands only your own javascript code is included (the /// <reference path='...' style reference is a design-time only thing) on the page. 因为它只包含你自己的javascript代码( /// <reference path='...'样式引用只是一个设计时的东西)在页面上。

You also need to include the jquery library in order to avoid the run-time error. 您还需要包含jquery库以避免运行时错误。

You have a couple of options: 你有几个选择:

  1. Simply reference the jquery script in your html (something you said you wanted to avoid) 只需在你的html中引用jquery脚本(你说你想避免的)
  2. Use a build tool such as webpack or browserify/tsify to import your references and change the /// <reference path='...' reference to import * as $ from "jquery"; 使用构建工具(如webpack或browserify / tsify)导入引用并将/// <reference path='...'引用更改为import * as $ from "jquery"; in which case the bundler will add the imported script to your outputed js file 在这种情况下,bundler会将导入的脚本添加到您输出的js文件中

More information here: http://www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html 更多信息请访问: http//www.typescriptlang.org/docs/handbook/integrating-with-build-tools.html

As an aside, this isn't really a typescript thing - if using plain js you would still either need to use the build tool with an import statement or have the jquery library loaded onto your page. 顺便说一下,这不是一个打字稿的东西 - 如果使用普通的js,你仍然需要使用带有import语句的构建工具或者将jquery库加载到你的页面上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM