You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用serverless-esbuild在AWS Lambda打包jsdom时遇找不到xhr-sync-worker.js错误

解决AWS Lambda + serverless-esbuild打包jsdom的xhr-sync-worker.js错误

方案1:修正external配置路径

你当前的external配置用了相对路径./xhr-sync-worker.js,但该文件实际位于node_modules/jsdom/lib/jsdom/living/xhr/目录下,esbuild无法识别这种相对路径的外部模块。需要将external配置改为完整的包内路径:

修改serverless.yml的custom.esbuild部分:

custom:
  esbuild:
    bundle: true
    minify: false
    sourcemap: true
    target: 'node20'
    external:
      - 'jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js'
    platform: 'node'
    concurrency: 10

方案2:注入代码覆盖同步Worker的引用

如果你的Lambda函数不需要使用同步XHR,可以通过esbuild的inject配置,强制将syncWorkerFile设为null,避免加载该文件:

  1. 在项目根目录创建inject.js文件,内容如下:
// 覆盖jsdom中同步XHR Worker的引用
const originalRequireResolve = require.resolve;
require.resolve = function (path) {
  if (path === './xhr-sync-worker.js') {
    return null;
  }
  return originalRequireResolve(path);
};
  1. 修改serverless.yml的esbuild配置,添加inject选项:
custom:
  esbuild:
    bundle: true
    minify: false
    sourcemap: true
    target: 'node20'
    inject: ['./inject.js']
    platform: 'node'
    concurrency: 10

方案3:复制Worker文件到打包目录

如果确实需要使用同步XHR,需要让esbuild将xhr-sync-worker.js复制到打包后的目录,确保运行时能找到:

修改serverless.yml的esbuild配置,添加copy选项(需确保serverless-esbuild版本支持该功能):

custom:
  esbuild:
    bundle: true
    minify: false
    sourcemap: true
    target: 'node20'
    platform: 'node'
    concurrency: 10
    copy:
      - from: 'node_modules/jsdom/lib/jsdom/living/xhr/xhr-sync-worker.js'
        to: './xhr-sync-worker.js'

额外建议

Lambda环境中尽量避免使用同步XHR,优先采用异步请求(比如fetch或异步版XMLHttpRequest),这样可以彻底绕过该Worker文件的问题。同时,确保jsdom版本与Node.js 20兼容,建议使用最新稳定版的jsdom。

内容的提问来源于stack exchange,提问作者user12504353

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:22:36