node.js - 你如何使用 typescript 编写 Node 模块?

标签 node.js typescript commonjs

所以,对于另一个问题(你如何导入使用 typescript 的模块)的一般答案是:

1) 创建一个 blah.d.ts 定义文件。

2) 用途:

/// <reference path="./defs/foo/foo.d.ts"/>
import foo = require("foo");

至关重要的是,您需要 both 文件 foo.d.ts 和 foo.js 在 node_modules 的某处加载; NAME foo 必须完全 匹配两者。现在...

我想回答的问题是您如何编写一个可以通过这种方式导入的 typescript 模块?

假设我有一个这样的模块:

- xq/
- xq/defs/Q.d.ts
- xq/index.ts
- xq/base.ts
- xq/thing.ts

我想用 base.ts 中的类“Base”和 thing.ts 中的“Thing”类导出模块“xq”。

如果这是 javascript 中的 Node 模块,我的 index.ts 将类似于:

var base = require('./base');
var thing = require('./thing');
module.exports = {
  Base: base.Base,
  Thing: thing.Thing
};

让我们尝试使用类似的 typescript 文件:

import base = require('./base');
export module xq {
    export var base = base.Base;
}

调用它:

tsc base.ts index.ts things.ts ... --sourcemap --declaration --target ES3 
                                   --module commonjs --outDir dist/xq

会发生什么?好吧,我们得到了我们的 base.d.ts:

export declare class Base<T> {
  ...
}

还有令人兴奋的无用 index.d.ts:

export declare module xq {
    var Base: any; // No type hinting! Great. :(
}

并且完全无效的不事件导入模块的javascript:

(function (xq) {
    xq.base = xq.base.Base;
})(exports.xq || (exports.xq = {}));
var xq = exports.xq;

我已经尝试了很多关于这个主题的变体,我唯一能做的就是:

declare var require;
var base = require('./base');
export module xq {
    export var base = base.Base;
}

...但这显然完全破坏了类型检查器。

所以。

Typescript 很棒,但这个模块的东西完全烂透了。

1) 是否可以使用内置的定义生成器(我很怀疑)

2) 你是如何手工完成的?我在 .d.ts 文件中看到了 import 语句,我认为这意味着有人已经想出了如何做到这一点;这些是如何工作的?你如何为一个有一个声明和一个 import 语句的模块做 typescript ?

(例如,我怀疑进行模块声明的正确方法是:

/// <reference path="base.d.ts" />
declare module "xq" {
  import base = require('./base'); 
  module xq {
    // Some how export the symbol base.Base as Base here
  }
  export = xq;
}

...但我不知道 typescript 会是什么)。

最佳答案

对于 JavaScript:

var base = require('./base');
var thing = require('./thing');
module.exports = {
  Base: base.Base,
  Thing: thing.Thing
};

typescript :

import base = require('./base');
import thing = require('./thing');
var toExport = {
  Base: base.Base,
  Thing: thing.Thing
};
export = toExport;

甚至是这个 typescript :

import base = require('./base');
import thing = require('./thing');
export var Base = base.Base;
export var Thing = thing.Thin;

关于node.js - 你如何使用 typescript 编写 Node 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23739044/

相关文章:

javascript - Backbone localStorage 没有使用良好的同步方法

javascript - 在 nodejs/commonjs 模块的根范围内声明对象 - 到 var 还是不到 var?

javascript - 将远程文件读取到浏览器中的 Node 缓冲区中

javascript - html 上的表单提交(获取请求)转到空白页面,并且当 Node 服务器中的 console.log 时没有任何记录

javascript - 如何在Electron主js脚本中调用Webpack捆绑的函数

reactjs - 我们需要带有 TypeScript 的 propTypes 吗?

javascript - Node.js 和模块作用域 : Most Efficient Way to Read Files into Memory

javascript - Nodejs 模块导出困惑

javascript - 在初始化时将所有过滤器选项设置为 'active' - Angular

javascript - 将 $(this) 编译为 $(_this)