How to bundle up NodeJS with Javascript for wrangler

689 Views Asked by At

The issue: I want to build a Cloudflare worker which uses NodeJS dependencies. However, due to issues with Wrangler, I cannot deploy it there using the command wrangler deploy.

The error:

X [ERROR] Could not resolve "async_hooks"
  node_modules/undici/lib/api/api-connect.js:4:34:
      4 │ const { AsyncResource } = require('async_hooks')
        ╵                                   ~~~~~~~~~~~~~

  The package "async_hooks" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.

There are many errors like this, and finally:

X [ERROR] Build failed with 74 errors:

  node_modules/@discordjs/rest/dist/index.js:445:30: ERROR: Could not resolve "timers/promises"
  node_modules/@discordjs/ws/dist/index.js:117:42: ERROR: Could not resolve "worker_threads"
  node_modules/@discordjs/ws/dist/index.js:448:31: ERROR: Could not resolve "timers/promises"
  node_modules/discord.js/src/client/BaseClient.js:3:29: ERROR: Could not resolve "node:events"
  node_modules/discord.js/src/client/Client.js:3:24: ERROR: Could not resolve "node:process"
  ...

I've tried adding "platform": "node" to package.json, but it isn't affecting anything.

1

There are 1 best solutions below

0
On

Try to add to the package.json file this try adding some settings from this line to your package.json file

    // package.json

    "build": "npx esbuild ./src/index.ts --bundle --platform=node --external:node:* --outfile=build/worker.js"