我试图让我的第一个TypeScript和DefinitelyTyped Node.js应用程序启动和运行,并运行到一些错误。

当我试图编译一个简单的TypeScript Node.js页面时,我得到错误“TS2304:找不到名称'require'”。我已经阅读了Stack Overflow上发生的其他几次此错误,我不认为我有类似的问题。 我在shell提示符下运行命令:

tsc movie.server.model.ts.

这个文件的内容是:

'use strict';

/// <reference path="typings/tsd.d.ts" />

/*    movie.server.model.ts - definition of movie schema */

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

var foo = 'test';

在var mongoose=require('mongoose')行上抛出错误。

typings/tsd.d. d的内容。Ts文件是:

/// <reference path="node/node.d.ts" />
/// <reference path="requirejs/require.d.ts" />

.d。Ts文件引用被放置在适当的文件夹中,并添加到typings/tsd.d。通过命令:

tsd install node --save
tsd install require --save

生成的.js文件似乎工作正常,所以我可以忽略这个错误。但我想知道为什么这个错误发生,我做错了什么。


当前回答

我还有另一个答案,建立在之前所有描述npm install @types/node并在tsconfig中包含node的答案之上。json / compilerOptions / types。

在我的例子中,我有一个基本的tsConfig。json和Angular应用程序中一个单独的扩展json:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": []
 },

我的问题是这个tsconf .app.json中的空类型-它破坏了基本配置中的一个。

其他回答

我发现解决方案是使用TSD命令:

tsd install node --save

它添加/更新typings/tsd.d。Ts文件,该文件包含节点应用程序所需的所有类型定义。

在我的文件顶部,我像这样引用tsd.d.ts:

/// <reference path="../typings/tsd.d.ts" />

截至2016年1月,需求的定义如下:

declare var require: NodeRequire;

interface NodeModule {
    exports: any;
    require: NodeRequireFunction;
    id: string;
    filename: string;
    loaded: boolean;
    parent: any;
    children: any[];
}

在tsconfig.json中添加如下内容:

"typeRoots": [ "../node_modules/@types" ]

我还有另一个答案,建立在之前所有描述npm install @types/node并在tsconfig中包含node的答案之上。json / compilerOptions / types。

在我的例子中,我有一个基本的tsConfig。json和Angular应用程序中一个单独的扩展json:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": []
 },

我的问题是这个tsconf .app.json中的空类型-它破坏了基本配置中的一个。

除了cgatian的答案,对于TypeScript 1.x

如果仍然看到错误,请在编译器选项中特别提供index.d.ts。

"files": [
    "typings/index.d.ts"
]
import * as mongoose from 'mongoose'