如何通过将SystemJS用作模块加载器将jQuery与TypeScript一起使用

问题描述 投票:0回答:1

我已经使用以下命令正确安装了jquery:

npm install --save jquery

npm i --save @types/jquery

npm install -g typings

typings install dt~jquery --global –save

我已从文件系统资源管理器中删除了文件夹的类型(因为某些原因,Visual Studio Code无法删除它),并且我已删除了类型的文件。我还执行了以下命令:

npm install --save-dev @types/jquery

命令已在Microsoft Visual Studio Code的终端中执行。

由于错误“ app.js:5 Uncaught ReferenceError:未在app.js:5定义jQuery,我无法将jQuery与TypeScript一起使用”我正在使用SystemJS加载模块。

文件app.ts:

(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('./app.js');

            // It seems to work fine
            System.import('./node_modules/jquery/dist/jquery.min.js').then(function(jquery) {
                    console.log("jQuery and it's dependencies are now loaded!");
            });
        </script>
    </body>
</html>

[以下错误出现在Web浏览器Google Chrome 77.0的控制台中:app.js:5未捕获的ReferenceError:未在app.js:5上定义jQuery

[请帮助我正确执行jQuery代码。提前非常感谢。

jquery typescript
1个回答
0
投票

TypeScript需要知道从何处导入jQuery$显然已正确声明,但jQuery可能未正确声明。

您很可能需要包括如下的import语句,以同时声明$jQuery

import {$,jQuery} from 'jquery';

此外,如果遇到范围问题,您可能希望尝试在上述import语句之后按如下方式全局声明jquery对象:

window.$ = $;
window.jQuery = jQuery;
© www.soinside.com 2019 - 2024. All rights reserved.