【问题标题】:Can't compile an optional Node.js dependency with Angular compiler无法使用 Angular 编译器编译可选的 Node.js 依赖项
【发布时间】:2022-01-15 00:55:28
【问题描述】:

我创建了一个 npm 库,其中包含如下代码:

let _Buffer: typeof Buffer;
let _require: NodeRequire;
let _readFile: (path: string, callback: (err: (NodeJS.ErrnoException | null), data: Buffer) => void) => void;

try {
  _Buffer = typeof Buffer !== undefined && Buffer;
  _require = typeof require !== undefined && require;

  if (_Buffer && _require)
    _readFile = _require('fs').readFile;
}
catch {}

我已经设法使上述代码的一部分在其他项目中工作,例如对Buffer 的可选依赖。 require 的使用不是我以前尝试过的,这就是现在让我感到悲伤的原因。 Angular 决心尝试解决对fs 的依赖,无论我如何尝试隐藏它(包括像_require('f' + 's') 这样的傻事),导致这样的错误:

./node_modules/@tubular/astronomy/dist/fesm2015/index.js:3:300-4:1 - 错误:找不到模块:错误:无法解析“/Users/kshetline/”中的“fs” Programming_projects/svc-ng/node_modules/@tubular/astronomy/dist/fesm2015'

我最想做的是找到一种设计 npm 库的方法,所以这根本不是问题。

一个不太令人满意的解决方案是找到一种方法来告诉 Angular 编译器忽略这个特定的外部依赖项。然而,这对谷歌来说是一个困难的话题,因为搜索都提供了关于 Angular 依赖注入系统的信息,而不是关于这种类型的编译时依赖。

目标是让库在 Node.js 环境中使用时具有额外的 Node.js 功能,但在这些功能不可用时仍可在浏览器中流畅运行。

【问题讨论】:

    标签: javascript node.js angular typescript


    【解决方案1】:

    有趣...我上面的代码实际上可以很好地隐藏fs 依赖项。

    发生的事情是,较早的尝试没有成功,并且不知何故,在 node_modules 或 package-lock.json 或 IntelliJ IDEA 的缓存系统或 Angular 的缓存系统中的某个地方,对fs 的不需要的依赖被锁定了,只是安装以前具有依赖关系的更新 npm 库并没有削减它。

    在清除上述所有可疑的不良依赖项的不需要内存的来源之后,我的代码最终将编译并运行。

    经过一番努力,我想出了一个改进的代码版本,因为它可以更好地与 rollup 和 webpack 配合使用,避免了将 fs 声明为外部依赖项的需要。

    let _Buffer: typeof Buffer;
    let _readFile: (path: string, callback: (err: (NodeJS.ErrnoException | null), data: Buffer) => void) => void;
    
    try {
      _Buffer = typeof Buffer !== undefined && Buffer;
      // eslint-disable-next-line no-new-func
      _readFile = !!_Buffer && (new Function('req', 'return req("fs").readFile'))(typeof require !== 'undefined' && require);
    }
    catch {}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-02
      • 2019-11-01
      • 1970-01-01
      • 2015-01-02
      • 2019-06-22
      • 2021-10-20
      • 2019-10-20
      • 1970-01-01
      相关资源
      最近更新 更多