【问题标题】:How to support several versions of the same module with typescript?如何使用 typescript 支持同一模块的多个版本?
【发布时间】:2020-06-07 05:41:01
【问题描述】:

我正在制作一个打字稿 npm 包。
它使用 discord.js,但 discord.js 有两个主要版本:
* discord.js 11.5
* discord.js v12.0.0-dev

我希望我的模块同时支持这两个版本。我的意思是,用户可以安装他们想要的 discord.js 版本,并且该包将使用好的代码。

对于另一个项目,在 javascript(没有打字稿)中,我使用这个:

const { version } = require("discord.js");
if(version === "12.0.0-dev"){
    // code for v12
} else {
    // code for v11
}

而且效果很好。但是,对于打字稿,由于打字,它更复杂。事实上,discord.js 的类型在 v11 和 v12 中是不一样的,所以我无法同时编译这两个版本的代码:

const { Guild, version } = require("discord.js");
if(version === "12.0.0-dev"){
    Guild.iconURL(); // for v12
} else {
    Guild.iconURL; // for v11
}

如果安装了 v12,则会抛出 iconURL() doesn't exist on Guild,如果是 v11,则会抛出 iconURL doesn't exist on Guild
有什么方法可以在同一个包中同时支持这两个版本,而不需要为每个版本创建一个分支?

【问题讨论】:

    标签: javascript node.js typescript types discord.js


    【解决方案1】:

    虽然不理想,但您可以手动下载 v11 和 v12 的类型并将模块名称更改为以下内容:

    // discord.js@11.d.ts
    declare module 'discord.js@11' {
      ...
    }
    
    // discord.js@12.d.ts
    declare module 'discord.js@12' {
      ...
    }
    

    然后你可以像这样导入类型:

    import { Guild as Guild12, version } from "discord.js";
    import { Guild as Guild11 } from "discord.js@11";
    
    declare const guild: Guild11 | Guild12 // obviously wouldn't be declared like this in your actual code
    
    // At the time of writing v12.0.2 has been released
    if (version === "12.0.2") {
        (guild as Guild12).iconURL(); // for v12
    } else {
        (guild as Guild11).iconURL; // for v11
    }
    

    你也可以定义一个类型保护:

    function isV12(guild: Guild11 | Guild12): guild is Guild12 {
      return version === "12.0.2";
    }
    
    if (isV12(guild)) {
      guild.iconURL();
    } else {
      guild.iconURL();
    }
    

    我尝试在 package.json 中像这样为 discord@11 和 discord@12 起别名:

    "devDependencies": {
      "discord.js11": "npm:discord.js@11.6.2",
      "discord.js12": "npm:discord.js@12.0.2"
    }
    

    但我收到了这个错误:

    import { Guild as Guild12, version } from "discord.js12";
    //                                        ~~~~~~~~~~~~~~
    // with pnpm:
    // File '/path/to/project/node_modules/.pnpm/registry.npmjs.org/discord.js/12.0.2/node_modules/discord.js/typings/index.d.ts' is not a module. (ts2306)
    // with npm:
    // File '/path/to/project/node_modules/discord.js12/typings/index.d.ts' is not a module. (ts2306)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 2015-01-25
      • 2012-09-24
      • 1970-01-01
      • 2021-10-16
      • 2012-12-21
      • 1970-01-01
      相关资源
      最近更新 更多