34

我正在用 jquery 测试 typescript,但是当我编译 test.ts 文件时,它总是给我一个错误提示:找不到名称'$'。

我已经导入了 jquery 并添加了它的定义参考。如果我import $ = require("jquery")在我的文件中使用,编译时会出现test.ts另一个错误“ ”。但是,JQuery 文件夹已经存在于 node_modules 文件夹中。Cannot find module jquerytsc

有谁知道在打字稿中使用 jquery 的正确方法是什么?

以下是我的步骤:

  1. 使用安装 jquerynpm install jquery --save
  2. 使用安装类型和 jquery 定义typings install --global --save dt~jquery
  3. 在 test.ts 顶部添加 jquery 引用/// <reference path="../../../typings/globals/jquery/index.d.ts" />

tsconfig.json

{
    "compilerOptions": {
        "jsx": "react",
        "outDir": "./dist",
        "sourceMap": true,
        "noImplicitAny": true,
        "module": "commonjs",
        "target": "es5",
        "experimentalDecorators": true
    },
    "exclude": [
        "node_modules"
    ],
    "files": [
        "./typings/index.d.ts",
        "./src/wo/tests/test.ts",
    ]
}

测试.ts

/// <reference path="../../../typings/globals/jquery/index.d.ts" />

let test:any=$("div");
4

5 回答 5

42

如果您在 90% 的情况下发现这些错误是因为 @types/jquery 的版本控制问题

尝试运行:

 npm install jquery --save

然后在app.module.ts

import * as $ from 'jquery';

然后运行:

  npm install @types/jquery@2.0.47

你应该准备好了。

于 2017-08-07T05:34:41.773 回答
14

我不知道它是否有帮助,但我为我的日期选择器解决了同样的问题。

首先我用这个命令安装了 jQuery:npm install --save-dev @types/jquery

然后在 angular-cli.json 文件中添加依赖项:

"styles": [
            "../node_modules/bootstrap/dist/css/bootstrap.css",
            "../node_modules/font-awesome/css/font-awesome.css",
            "../node_modules/ng2-datetime/src/vendor/bootstrap-datepicker/bootstrap-datepicker3.min.css",
            "styles.css"
        ]

"scripts": [
            "../node_modules/jquery/dist/jquery.js",
            "../node_modules/ng2-datetime/src/vendor/bootstrap-datepicker/bootstrap-datepicker.min.js"
        ]

我认为添加 jQuery 部分可能对你有用。请让我知道它是否有效。

于 2016-12-12T07:20:33.967 回答
1

安装并导入以下包。它将解决错误(“找不到名称'$'”)。角度版本是 7

导入'datatables.net';

于 2019-03-19T13:54:37.643 回答
1
import * as $ from "jquery";

对我不起作用。够有趣的,

import { ajax, css } from "jquery";

实际上解决了我的问题。

于 2020-02-26T18:03:10.203 回答
-3

您可能有一些需要修复的漏洞。

运行npm audit fix以修复它们,或npm audit了解详细信息。

于 2019-07-24T12:58:18.643 回答