【问题标题】:Typescript module, require external node_modules打字稿模块,需要外部 node_modules
【发布时间】:2015-05-15 11:56:02
【问题描述】:

我需要在一个简单的打字稿文件中使用一个简单的 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');

感谢提前

感谢提前

【问题讨论】:

  • 很确定你应该简单地写import globimport 'glob'
  • 导入全局;在 IDE 中给我一个错误,在使用 import 'glob' 时我应该如何引用我的库?感谢您的回答
  • 应该是 var glob = require('glob');你也使用 import 吗?
  • 这不是带有 import 的标准 typescript 方法吗?
  • 您是否为打字稿编译器指定了正确的--module 选项?对于节点,它应该是--module commonjs

标签: javascript node.js typescript


【解决方案1】:

您使用了正确的语法:

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 获取它。

【讨论】:

  • 使用 TypeScript 管理和声明每个模块真的很困难,所以 :-o 。绝对类型的源真的是最新的并且确定吗?感谢您的回复
  • Definitely Typed 由社区维护,目前每天都会收到更新:github.com/borisyankov/DefinitelyTyped/commits/master
【解决方案2】:

这是您的代码的错误

    import glob = require('glob');

因为在 node.js 中 import 不是保留关键字。如果您需要应用程序中的任何模块,您只需使用以下语句来要求它

    var glob = require('glob');

完成后就可以使用了

    console.log(glob);

打印 glob 的值。替换 import 有望为您完成这项工作。

【讨论】:

猜你喜欢
  • 2014-09-28
  • 2014-05-22
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
相关资源
最近更新 更多