我有一个用 Typescript 编写的 Node.js 项目,我正在尝试让它与 mime.js ( https://github.com/broofa/node-mime ) 一起工作。我有一个声明文件( https://github.com/borisyankov/DefinitelyTyped/blob/master/mime/mime.d.ts ),但无法在 typescript 中获取 node.js 来很好地使用它。
我有以下内容:
/// <reference path="../../libs/mime.d.ts" />
import mime = require( 'mime' );
这让类型脚本编译器保持愉快,一切都很好,直到我尝试在 Node 中运行它。
当我尝试运行它时,我得到
Cannot find module 'mime'
但是,如果我将生成的 JavaScript 编辑为以下内容:
import mime = require( '../../libs/mime' );
一切正常。如果我更改 typescript 文件以包含相对路径的 require,我会收到编译器错误:
Cannot find external module '../../libs/mime'
如何将 Typescript 引用到 mime.d.ts 文件和 mime.js 文件,以便编译器和 Node 都满意。
非常感谢
最佳答案
TypeScript 仅支持 TypeScript 模块的相对路径。环境 JavaScript 模块应放置在 node_modules
文件夹中。来自 Node.js doc :
If the module identifier passed to require() is not a native module, and does not begin with '/', '../', or './', then node starts at the parent directory of the current module, and adds /node_modules, and attempts to load the module from that location.
解决方法 1
将 .d.ts
放置在 .js
模块旁边,并将其更改为:
declare module "mime" {
...
}
至:
declare module Mime {
...
}
export = Mime;
解决方法 2
重写 .d.ts
文件:
declare module "mime" {
export function lookup(path: string): string;
...
}
至:
declare interface IMime {
function lookup(path: string): string;
...
}
然后使用普通的 var
而不是 import
:
var mime = <IMime>require( '../../libs/mime' );
关于javascript - 如何使用 TypeScript 声明文件在 Node.js 中请求外部 js 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31946616/