【问题标题】:Cannot find name '$' in TS file unless referenced in every file除非在每个文件中都引用,否则无法在 TS 文件中找到名称“$”
【发布时间】:2017-05-01 07:44:51
【问题描述】:

我正在 Visual Studio 2015 中设置打字稿。我将在 TS 文件中使用 jquery。当我使用 jquery 时,VS 会在 '$' 下划线并说找不到名称,并且不会成功构建。它构建的唯一方法是,如果我在每个 TS 文件中添加对 jquery 类型的引用。 /// <reference path="typings/index.d.ts" /> 有没有办法在全局范围内使用这个引用而不是添加到每个文件中?

在 Visual Studio Code 中我没有这个问题。

我的目录是这样的 -脚本 --ts ---打字 ---main.ts tsconfig.json --js

我的tasks.json文件在根目录

    {
    "version": "0.1.0",

    // The command is tsc. Assumes that tsc has been installed using npm install -g typescript
    "command": "tsc",

    // The command is a shell script
    "isShellCommand": true,

    // Show the output window only if unrecognized errors occur.
    "showOutput": "silent",

    // Tell the tsc compiler to use the tsconfig.json from the open folder.
    "args": ["-p", "../Scripts/Weblink/ts"],

    // use the standard tsc problem matcher to find compile problems
    // in the output.
    "problemMatcher": "$tsc"
}

脚本/ts中的taskconfig.json

{
"compileOnSave": true,
"compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "../lib/"
},
"exclude": [
    "typings/*"
]
}

【问题讨论】:

  • 您使用的是哪个版本的打字稿?
  • 最新版本 2.1.4
  • 使用打字稿的VS文件安装,而不是Node
  • 尝试在tsconfig.json中指定引用typescriptlang.org/docs/handbook/tsconfig-json.html
  • 谢谢,它现在构建成功,但是无论出于何种原因,VS 仍然会在 $ 下划线并出现相同的错误

标签: typescript visual-studio-2015


【解决方案1】:

在 TypeScript 2.x 中,你应该像这样安装类型:

npm install --save @types/jquery

然后:

import * as $ from "jquery";

无需引用,TypeScript 会自动处理。

More info

【讨论】:

  • 并且任何插件都应该是added to a typings文件,所以编译器会在已知的jquery类型接口中合并这些签名。
  • 我目前正在重构包含大量declare const $: any 的代码。如果用 import * as $ from "jquery" 替换它们,对性能、捆绑包的大小……或其他我无法想象的东西有什么影响吗?
【解决方案2】:
  • 在 TypeScript 3 中使用 npm:

    npm install --save-dev @types/jquery

    还有:

    import "jquery";

    别名不是必需的。

  • 如果你不使用 npm:

    添加一个包含declare module 'jquery';的新声明(jquery.d.ts)文件

    还有:

    import "jquery";

【讨论】:

    【解决方案3】:

    添加到您的 tsconfig.json:

    "moduleResolution": "node",
    "lib": [ "es2015", "es2017", "dom" ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 2016-02-04
      • 2016-02-15
      • 1970-01-01
      • 2020-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多