Typescript模块,需要外部node_modules

Typescript module, require external node_modules

本文关键字:node modules 外部 模块 Typescript      更新时间:2023-09-26

我需要在一个简单的typescript文件中使用一个简单的node_module,但是似乎编译器不想得到它。

这是我的简单ts文件:

import glob = require('glob');
console.log(glob);

我得到了这个错误:

[13:51:11] Compiling TypeScript files using tsc version 1.5.0
[13:51:12] [tsc] > F:/SkeletonProject/boot/ts/Boot.ts(4,23): error TS2307: Cannot find external module 'glob'.
[13:51:12] Failed to compile TypeScript: Error: tsc command has exited with code:2
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: Failed to compile: tsc command has exited with code:2
npm ERR! skeleton-typescript-name@0.0.1 start: `node compile && node ./boot/js/Boot.js`
npm ERR! Exit status 8
npm ERR!
npm ERR! Failed at the skeleton-typescript-name@0.0.1 start script.
然而,当我在同一个脚本中使用一个简单的声明时,它工作了:
var x = 0;
console.log(x); // prints  0 after typescript compilation

在这种情况下我做错了什么?

编辑:

我的gulp文件:

var gulp = require('gulp');
var typescript = require('gulp-tsc');

gulp.task('compileApp', ['compileBoot'], function () {
    return gulp.src(['app/src/**/*.ts'])
        .pipe(typescript())
        .pipe(gulp.dest('app/dist/'))
});
gulp.task('compileBoot', function () {
    return gulp.src(['boot/ts/*.ts'])
        .pipe(typescript({
            module:'commonjs'
        }))
        .pipe(gulp.dest('boot/js/'))
});
gulp.start('compileApp');

Thanks for advance

Thanks for advance

您使用的语法是正确的:

import glob = require('glob');

但是错误:Cannot find external module 'glob'指出你正在使用一个特殊的情况。

默认情况下,编译器正在查找glob.ts,但在您的情况下,您使用的是节点模块,而不是您编写的模块。因此,glob模块需要特殊处理…

如果glob是一个纯JavaScript模块,您可以添加一个名为glob.d.ts的文件,其中包含描述该模块的类型信息。

glob.d.ts

declare module "glob" {
    export class Example {
        doIt(): string;
    }
}

app.ts

import glob = require('glob');
var x = new glob.Example();

一些Node模块已经在包中包含了.d.ts,在其他情况下,你可以从Definitely Typed中获取它。

这是你的代码的错误

    import glob = require('glob');

因为在node.js中import不是一个保留关键字。如果在应用程序中需要任何模块,只需使用语句

来要求它
    var glob = require('glob');

完成后可以使用

    console.log(glob);

打印glob的值。