如何在TypeScript中正确地要求和声明节点库类型?

Leo*_*ler 7 node.js typescript definitelytyped visual-studio-code

我试图写一个包,使用标准的节点库,例如在打字稿节点fs,path,stream,http,等.

当我尝试在.ts文件中导入库时,VS Code会在相应的行中标记错误:
[ts] Cannot find module 'fs'.无论我如何导入库,都会发生这种情况:

import * as fs from 'fs';    // [ts] Cannot find module 'fs'
import fs = require('fs');   // [ts] Cannot find module 'fs'
const fs = require('fs');    // [ts] Cannot find name 'require'
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我(应该)安装了正确的定义typings install --save --ambient node.

当我编译为JavaScript(使用gulpgulp-typescript,而不是tsc)时,compliation 工作,语法高亮显示没有错误,直到我再次输入1个字符:

在此输入图像描述

如何正确定义TypeScript的节点库?


我使用VS Code进行代码突出显示和自动完成,gulp以及gulp-typescript编译和typings使用typescript库声明.

该项目的目录结构:

?? build/
?  ?? (output files)
?? src/
?  ?? myfile.ts
?? typings/
?  ?? browser/
?  ?  ?? ambient/
?  ?     ?? node/
?  ?        ?? index.d.ts
?  ?? main/
?  ?  ?? ambient/
?  ?     ?? node/
?  ?        ?? index.d.ts
?  ?? browser.d.ts
?  ?? main.d.ts
?? gulpfile.js
?? package.json
?? tsconfig.json
?? typings.json
Run Code Online (Sandbox Code Playgroud)

我的tsconfig.json:

{
    "compileOnSave": false,
    "compilerOptions": {
        "declaration": true,
        "module": "system",
        "moduleResolution": "node",
        "noEmitOnError": true,
        "noImplicitAny": true,
        "target": "es5"
    },
    "exclude": [
        "node_modules",
        "typings/browser",
        "typings/browser.d.ts"
    ]
}
Run Code Online (Sandbox Code Playgroud)

我的typings.json:

{
  "ambientDependencies": {
    "node": "registry:dt/node#4.0.0+20160412142033"
  }
}
Run Code Online (Sandbox Code Playgroud)

我的gulp任务:

gulp.task('build-typescript', () => {
    const gulpts = require('gulp-typescript');
    const tsProject = gulpts.createProject('tsconfig.json', {
        typescript: require('typescript'),
        outFile: 'mylibrary.js',
        noLib: true
    });

    let tsstream = (
        gulp.src([
            'node_modules/typescript/lib/lib.es6.d.ts',
            'typings/main.d.ts',
            'src/sharpscript.ts'])
        .pipe(sourcemaps.init())
        .pipe(gulpts(tsProject))
    );

    return require('merge2')(
        tsstream.dts.pipe(gulp.dest('build')),
        tsstream.js
            .pipe(sourcemaps.write('.', { includeContent: true }))
            .pipe(gulp.dest('build'))
    );
});
Run Code Online (Sandbox Code Playgroud)

如果有人遇到同样的问题,我很感谢任何见解.

Kal*_*lle 3

使用“typings install ...”安装类型声明几个月以来就已经过时了。新方法是直接通过 npm 和 @types 命名空间安装它。要安装节点类型声明,只需使用npm install @types/node --save-dev.