我使用gulp-angular的Yeoman生成器创建了一个新项目,语言设置为TypeScript。然后运行Gulp构建过程,并在web浏览器中打开页面,这些都没有出现任何更大的问题。我只需要用ref: "1.4.1"
替换tsd.json
中的ref: "master"
就可以使构建工作。基本上我执行了以下命令:
yo gulp-angular
vim tsd.json
gulp
gulp serve
code .
之后我在Visual Studio Code中打开项目。
现在,Visual Studio Code会抱怨它在每次使用AngularJS数据类型的情况下"找不到命名空间'ng'"。它还抱怨MomentJS和*.d.ts
文件中定义的其他类型。
项目的tsd.json
是这样的:
{
"version": "v4",
"repo": "borisyankov/DefinitelyTyped",
"ref": "1.4.1",
"path": ".tmp/typings",
"bundle": ".tmp/typings/tsd.d.ts"
}
.tmp/typings
文件夹包含以下文件:
angular-ui-router/angular-ui-router.d.ts
angularjs/angular-animate.d.ts
angularjs/angular-cookies.d.ts
angularjs/angular-mocks.d.ts
angularjs/angular-resource.d.ts
angularjs/angular-sanitize.d.ts
angularjs/angular.d.ts
jquery/jquery.d.ts
moment/moment-node.d.ts
moment/moment.d.ts
toastr/toastr.d.ts
tsd.d.ts
给一个例子,其中一个源文件Visual Studio Code抱怨,这里是navbar.directive.ts
文件:
module editorTs {
'use strict';
/** @ngInject */
export function acmeNavbar(): ng.IDirective {
return {
restrict: 'E',
scope: {
creationDate: '='
},
templateUrl: 'app/components/navbar/navbar.html',
controller: NavbarController,
controllerAs: 'vm',
bindToController: true
};
}
/** @ngInject */
class NavbarController {
public relativeDate: string;
constructor(moment: moment.MomentStatic) {
this.relativeDate = moment(1444135396045).fromNow();
}
}
}
在这个文件中,Visual Studio Code抱怨ng.IDirective
类型,它"无法找到命名空间'ng'",它是抱怨moment.MomentStatic
类型,它"无法找到命名空间'moment'"。
通过在navbar.directive.ts
的顶部添加以下内容来显式引用类型定义文件可以解决此问题:
/// <reference path="../../../../.tmp/typings/angularjs/angular.d.ts"/>
/// <reference path="../../../../.tmp/typings/moment/moment.d.ts"/>
但是这些文件已经在.tmp/tsd.d.ts
中被引用了,它包含以下内容:
/// <reference path="angular-ui-router/angular-ui-router.d.ts" />
/// <reference path="angularjs/angular-animate.d.ts" />
/// <reference path="angularjs/angular-cookies.d.ts" />
/// <reference path="angularjs/angular-mocks.d.ts" />
/// <reference path="angularjs/angular-resource.d.ts" />
/// <reference path="angularjs/angular-sanitize.d.ts" />
/// <reference path="angularjs/angular.d.ts" />
/// <reference path="jquery/jquery.d.ts" />
/// <reference path="moment/moment-node.d.ts" />
/// <reference path="moment/moment.d.ts" />
/// <reference path="toastr/toastr.d.ts" />
所以不需要显式地引用这些文件?
添加tsconfig.json
到我的VS Code项目的根是什么为我解决了这个问题。此外,不得不重新启动VS code。下面是我在文件中添加的内容:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"sourceMap": true
}
}
有关tsconfig.json
文件的更多信息,请查看:
无法找到命名空间'ng'"
确保项目不包含对declare module ng
的引用。现在也是一样。
基于编辑的问题:
通过在navbar.directive.ts的顶部添加以下代码来显式引用类型定义文件可以解决
问题
请使用tsconfig.json
: https://basarat.gitbooks.io/typescript/content/docs/project/compilation-context.html
我在代码中一个隐蔽的位置发现了以下内容。可能是为了避免输入错误。似乎vscode遇到了这个问题,并将全局'angular'变量重新定义为'any'类型。
var angular = window['angular'];
我有同样的问题;似乎typings剥离了引用"ng"导入的原始定义文件。
把这个添加回你原来的angular/index.d。ts文件:
// Collapse angular into ng
import ng = angular;
或者更好的是,将它放在ng.d.ts文件中,这样它就不会再次被类型覆盖。