【问题标题】:Writing a Typescript Library with a Web Assembly Dependency?编写具有 Web 程序集依赖的 Typescript 库?
【发布时间】:2019-10-10 10:55:39
【问题描述】:

我正计划编写一个用于分发的打字稿库,这将取决于cephes

为了在浏览器中使用 Web 程序集,我们必须像这样编译它:

const cephes = require('cephes'); // Browser
await cephes.compiled;

我不确定如何为包装 cephes 的 Typescript 库实现此功能。

例如,库将提供一个 NormalDistribution,可以像这样导入:

import { NormalDistrbution } from 'cephesdistributions';

如果我们进行树摇动,那么 NormalDistribution 可能是包中包含的唯一导入。因此,我们是否需要在cephesdistributions 提供的所有模块中包含await cephes.compiled

【问题讨论】:

    标签: javascript typescript browser webassembly


    【解决方案1】:

    我认为你应该尽可能直截了当。由于您的消费者无法真正绕过await,我建议您将其留给消费者await cephes.compiled

    如果您要捆绑 cephes,您可能希望从库中重新导出 cephes.compiled,以便您的消费者可以使用您的库:

    const cephes = require('cephes');
    
    export const compiled = cephes.compiled;
    
    export class NormalDistribution {
      public mean: number;
      public sd: number;
    
      constructor(mean = 0, sd = 1) {
        this.mean = mean;
        this.sd = 1;
      }
    
      cdf(x: number): number {
        // If this gets called before someone has `await`:ed `compiled`
        // there will be trouble.
        return cephes.ndtr(x);
      }
    }
    

    这意味着您导出的类将使其类型立即可用,即使过早调用它们会崩溃。由于您的消费者与您一样依赖cephes.compiled 被解析,因此您可以考虑在适当的情况下存储编译状态和“保护”。例如,

    const cephes = require('cephes');
    
    let isCompiled = false;
    export function assertIsCompiled() {
      if (isCompiled) {
        return;
      }
    
      throw new Error('You must wait for `cephesdistributions.compiled` to resolve');
    }
    
    export const compiled = cephes.compiled.then(() => { isCompiled = true });
    
    export class NormalDistribution {
      public mean: number;
      public sd: number;
    
      constructor(mean = 0, sd = 1) {
        assertIsCompiled();
    
        this.mean = mean;
        this.sd = 1;
      }
    
      cdf(x: number): number {
        return cephes.ndtr(x);
      }
    }
    

    【讨论】:

    • 很好的解释——我喜欢 assertIsCompiled() 技术!
    猜你喜欢
    • 2014-04-25
    • 1970-01-01
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2015-04-28
    • 2013-01-10
    相关资源
    最近更新 更多