【问题标题】:How to "import" a typedef from one file to another in JSDoc using Node.js?如何使用 Node.js 在 JSDoc 中将 typedef 从一个文件“导入”到另一个文件?
【发布时间】:2018-09-24 23:21:32
【问题描述】:

假设我有一个名为“File1.js”的文件。在这个文件中,我导出了一个对象对象,并给每个对象一个 typedef,就像这样。

/**
 * My typedef for each object.
 * @typedef {Object} MyObject1
 * @property {String} username Your username
 * @property {String} realname Your real name.
 * @property {boolean} isUnique Are you unique as a person?
 */
module.exports = {
  /**
   * Person One!
   * @type {MyObject1}
   */
  myperson: {
    username: 'TheDragonSlayer',
    realname: 'George',
    isUnique: true
  },
  /**
   * Person Two!
   * @type {MyObject1}
   */
  myperson2: {
    username: 'BobMagee',
    realname: 'Bob',
    isUnique: false
  }
}

现在,在名为“File2.js”的文件中,我在构造函数中引用该对象并将其设置为新的MyObject1

const persons = require('./File1.js');

class File2 {
  constructor(options = {}) {
    /**
     * The person for this file.
     * @type {MyObject1}
     */
    this.person = options.person ? persons[options.person] : persons.myperson2;
  }
}

module.exports = File2;

我使用 Visual Studio Code 进行开发,因此通过按 Ctrl+Space 可以获得 IntelliSense。在文件一中,当我制作人员对象时,IntelliSense 告诉我 username 是一个字符串,realname 是一个字符串,isUnique 是一个布尔值。但是,当我进入 file2 并通过 this.person 引用新创建的人时,在输入 this.person.username 时,它不会出现“用户名:字符串”的预期结果。

是否可以在 vanilla Node.js 的 File2 中使用 typedef MyObject1,还是我不走运?

编辑:有了更多信息,我能够使用 @export 和 @import 为 TypeScript 找到答案,以及我尝试过的各种标签。这一切都无济于事。我还尝试将 File1.js 标记为 @module,并执行 module:mymodule~MyMethod,但每次我这样做时,它只会将 this.person 标记为 NodeModule 而不是方法本身。

【问题讨论】:

  • 您的意思是 @typedef 而不是 File1 中的 @typdef
  • @PeterG 是的,很抱歉!
  • 这可能只是 Intellisense 智能程度的问题,而不是 JSDoc 的问题。使用 WebStorm IDE,我发现此方案按预期工作,但我经常发现对 JSDoc 支持的限制 - 例如,当 @typedef 在依赖项项目中时,它无法按预期工作。
  • 在下面的一个答案中对此效果有评论,但import("some-module") 受 Typescript 支持,但 不是 官方 JSDoc。

标签: javascript node.js jsdoc


【解决方案1】:

使用函数import 将声明的类型导入文件File2.js

const persons = require('./File1.js');

/**
 * @typedef {import('./File1.js').MyObject1} MyObject1
 */

class File2 {
...

它对我有用。

【讨论】:

猜你喜欢
  • 2015-02-02
  • 2017-08-28
  • 2020-08-18
  • 2021-06-21
  • 2018-01-09
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 2021-06-22
相关资源
最近更新 更多