Requiring npm packages not working in QR Code example

Hello!

I am following the tutorial on building a serverless function here: https://developers.cloudflare.com/workers/tutorials/build-a-serverless-function

I’m at the point of requiring the qr-image package. I have it installed and referenced in package.json

However, when I publish with Wrangler to test the results, I get the following:

13:28 $ wrangler publish
💁  JavaScript project found. Skipping unnecessary build!
Error: Something went wrong! Status: 400 Bad Request, Details {
  "result": null,
  "success": false,
  "errors": [
    {
      "code": 10021,
      "message": "Uncaught ReferenceError: require is not defined\n  at line 1\n"
    }
  ],
  "messages": []
}

The line being referenced is the same line from the tutorial:

const qr = require('qr-image')

I’ve browsed around the documentation but can’t understand why this is. It seems perhaps I have to integrate webpack with the worker so it compiles all modules required into a bundle, but it’s not clear how that works with Cloudflare Workers.

Appreciate any help!

I believe I’ve resolved my issue by setting up the publish command to use Webpack, as per https://developers.cloudflare.com/workers/tooling/wrangler/webpack/

I believe this should be mentioned in the guide. I’ll review contribution guidelines and see if it makes sense for me to commit a change for the docs.

Thanks!

2 Likes