jquery - 如何通过使用 SystemJS 作为模块加载器将 jquery 与 TypeScript 一起使用(ReferenceError:jQuery 未在 Object.execute 中定义)
问题描述
我已经使用以下命令正确安装了 jquery:
npm install --save jquery
和
npm i --save @types/jquery
和
npm install -g typings
和
typings install dt~jquery --global –save
我已经从文件系统资源管理器中删除了文件夹类型(因为 Visual Studio Code 出于某种原因无法删除它)并且我已经删除了文件 typings.json 我还执行了以下命令:
npm install --save-dev @types/jquery
这些命令已在 Microsoft Visual Studio Code 的终端中执行。
我正在使用 SystemJS 加载模块。
文件 app.ts:
import $ from 'jquery';
(function($) {
// Use $() inside of this function
$("#app").css({"background-color": "green"});
})(jQuery);
文件 app.js:
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
return {
setters: [],
execute: function () {
(function ($) {
// Use $() inside of this function
$("#app").css({ "background-color": "green" });
})(jQuery);
}
};
});
文件 index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Learning TypeScript</title>
<script src='node_modules/systemjs/dist/system.js'></script>
</head>
<body>
<div id="app">Change it with jQuery</div>
<script>
System.import('./node_modules/jquery/dist/jquery.min.js');
System.import('./app.js');
</script>
</body>
</html>
执行 tsc 命令时没有发生错误。
有时 jQuery 工作正常,但有时当我按 F5 键(重新加载页面)时,Web 浏览器 Google Chrome 77.0 的控制台中会出现以下错误:
Uncaught (in promise) ReferenceError: jQuery is not defined
at Object.execute (app.js:10)
请帮助我正确执行 jQuery 代码。提前谢谢了。
解决方案
TypeScript 需要知道你jQuery
从哪里导入。$
显然是正确声明的,但jQuery
可能不是。
您很可能需要包含如下导入语句来声明jQuery
:
import * as jQuery from 'jquery';
此外,如果您遇到范围问题,您可能需要尝试在上述导入语句之后全局声明 jquery 对象,如下所示:
window.$ = $;
window.jQuery = jQuery;
最后,如果您想确保 app.ts 使用可能已经全局定义的任何 jQuery 定义,请仅在它们不存在时更新全局变量,如下所示:
window.$ = window.$ || $;
window.jQuery = window.jQuery || jQuery;
推荐阅读
- c++ - VTK:尝试使用 vtkrubberbandpick 和 vtkHardwareSelector 选择区域中的可见单元格
- c++ - c++/CLI 代码中的内存泄漏
- c++ - 取消引用时销毁对象
- r - 使用stargazer输出从R markdown编织pdf doc
- postgresql - 我找不到我的 pid 文件来删除它,以便我可以再次启动 postgresql?
- spring-boot - 如何从命令行执行 Cucumber Spring Boot Packaged Jar?
- php - TYPO3 CMS 8.7.13 安装工具升级向导:执行“在单行上执行数据库迁移”时出错
- java - SpringBoot 将配置存储在 BOOT 中
- excel - 需要使用 Outlook 在邮件正文中创建多行
- java - wagon-ftp "连接超时"