首页 > 解决方案 > 如何通过使用 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 代码。提前谢谢了。

标签: jquerytypescriptsystemjs

解决方案


TypeScript 需要知道你jQuery从哪里导入。$显然是正确声明的,但jQuery可能不是。

您很可能需要包含如下导入语句来声明jQuery

import * as jQuery from 'jquery';

此外,如果您遇到范围问题,您可能需要尝试在上述导入语句之后全局声明 jquery 对象,如下所示:

window.$ = $;
window.jQuery = jQuery;

最后,如果您想确保 app.ts 使用可能已经全局定义的任何 jQuery 定义,请仅在它们不存在时更新全局变量,如下所示:

window.$ = window.$ || $; 
window.jQuery = window.jQuery || jQuery;

推荐阅读