我开发了一个本地 NodeJS 模块(使用 NAN 助手)。现在我想知道记录它的最佳方式是什么。
模块导出的方法仅存在于 C++ 源代码中,但我希望导出 Javascript 文档。
最佳答案
编辑:我发现另一种我认为更好的方法:
所有 JSDoc 需要的是能够将 doclet 附加到 SOMETHING,因此您实际上可以这样做(如果您忽略 JSHint 关于期待赋值或调用而不是表达式的警告):
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
* @class
*/
nativeStuff.MyCoolClass;
/**
* My Cool Method
* @function
* @param {String} [name] The argument
*/
nativeStuff.MyCoolClass.prototype.CoolMethod;
/**
* Some Other Value
* @type {String}
*/
nativeStuff.someStringValue;
module.exports = nativeStuff;
这具有使用 IDE(至少是 WebStorm)的优势,并且不需要您复制或代理对象本身。请注意,您必须明确告诉它每个条目是什么类型的字段(使用@function 或@class 或@type),否则它无法自动推断。
原始答案
我知道有几种方法,但我承认没有一种看起来特别优雅。
在您 require()
代码的 native 部分并使其作为模块可用的小适配器文件中,您可以单独分配每个组件并以这种方式记录它们:
var nativeStuff = require('some/native/stuff');
// If your module only has one thing
/**
* My Cool Class
* @class MyCoolClass
*/
module.exports = nativeStuff;
// If it has several things
module.exports = {
/**
* My cool class
* @class
*/
MyCoolClass: nativeStuff.MyCoolClass,
/**
* My Other Cool Member
*/
OtherCoolMember: nativeStuff.OtherCoolMember
};
如果您想拆开类并重新组装它,您也可以用这种方式记录类成员,但是越深入它就会变得有点笨拙。
我知道的另一种方法是将每个类方法包装在原生 JS 中,这会带来(几乎可以忽略不计的)性能损失:
var nativeStuff = require('some/native/stuff');
/**
* My Cool Class
*/
class MyCoolClass {
constructor() {
this._nativeObj = new nativeStuff.MyCoolClass();
}
/**
* Some Cool Method
* @param {String} [name] My name
*/
coolMethod(name) {
return this._nativeObj(name);
}
}
module.exports = MyCoolClass;
(注意这也适用于旧的 JS 版本,但 ES6 类使内容更容易在视觉上理解:)
您也可以尝试使用 @typedef指令来定义事物,因为关于 typedef 的 doclet 可以与其描述的对象分开,但我认为 typedef 一般不能记录方法或类,它们仅用于数据对象。
关于javascript - 如何记录 NodeJS 原生 (V8) 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33994805/