2017-08-04 185 views
1

我在Visual Studio中使用TypeScript的内置支持,因此当我保存TypeScript文件时,它们被转换为JavaScript文件。Visual Studio 2017与TypeScript的编译错误

我有以下脚本:

declare namespace myLib { 
    function makeGreeting(s: string): string; 
    let numberOfGreetings: number; 
} 

$(document).ready(function() { 
    alert("bp1"); 
}); 

我tsconfig.json文件包含以下内容:

{ 
    "compileOnSave": true, 
    "include": [ "*.ts" ], 
    "compilerOptions": { 
    "allowJs": true, 
    "sourceMap": true, 
    "outFile": "..\\js\\site.js", 
    "target": "es3" 
    }, 
    "typeAcquisition": { 
    "enable": true, 
    "include": [ "jquery" ] 
    } 
} 

当我保存文件时,它transpiled为JavaScript没有任何问题,但是当我重建项目我遇到如下错误:

TS2304 Build:找不到名称'$'。演示文稿(Presentation \ Presentation)C:\ Development-MVC \ NET \ Ev \ Web \ UI \ Presentation \ Content \ ts \ welcome.ts 6

我认为这是与类型获取功能在构建工作,但我不知道如何解决它。

回答

1

自动获取类型定义似乎不适用于jQuery。有limited information on type acquisition here

这是另一种方法。

确保您已经安装了jquery及其类型。我们可以使用命令行中的NPM来完成此操作。

npm install jquery --save 
npm install @types/jquery --save-dev 

或者,我们可以手动编辑package.json文件。

{ 
    "dependencies": { 
    "jquery": "^3.2.1" 
    }, 
    "devDependencies": { 
    "@types/jquery": "^3.2.11"  <----- These types will be necessary. 
    } 
} 

安装jQuery及其类型将解决Cannot find name '$'错误。

之后,在你的tsconfig中,确保使用domes2015库。否则,编译器会在解析jquery之后输出新的错误。

{ 
    "compileOnSave": true, 
    "include": [ "*.ts" ], 
    "compilerOptions": { 
    "allowJs": true, 
    "sourceMap": true, 
    "outFile": "..\\js\\site.js", 
    "target": "es3", 
    "lib": [      <---- These two libs will be necessary. 
     "dom", 
     "es2015" 
    ] 
    }, 
    "typeAcquisition": { 
    "enable": true, 
    "include": [ "jquery" ] 
    } 
} 
+1

最后是使用npm安装@types包的情况,我已经使用Bower安装了jquery。 tsconfig设置没有区别。我还必须将' true '添加到项目文件中。 –