4
votes

I'm trying to write a cloudflare worker following the documentation and use Webpack to generate one single file to upload.

After running the script as in the docs:

curl -X PUT "https://api.cloudflare.com/client/v4/zones/ZONE_ID/workers/script" -H "Content-Type:application/javascript" -H "X-Auth-Email:CLOUDFLARE_EMAIL" -H "X-Auth-Key:CLOUDFLARE_KEY" --data-binary "@dist/index.js"

I'm getting the following error:

{
  "result": null,
  "success": false,
  "errors": [
    {
      "code": 10021,
      "message": "Uncaught ReferenceError: exports is not defined\n  at line 1\n"
    }
  ],
  "messages": []
}

My webpack config:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: ['./src/index.js'],
  target: 'web',
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'babel-loader',
      exclude: /node_modules/,
    }],
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, 'dist'),
    filename: 'index.js',
  },
};

I cannot find documentation or example about creating workers with webpack but I don't think this is a new thing :)

Thanks

1
I believe @john-fawcett has gotten this to work so hopefully he can answer. (I think he's on vacation though...) - Kenton Varda
Hmm that @ didn't work, I'll ping him directly. - Kenton Varda
I don't know webpack, but it looks to me like setting libraryTarget: 'commonjs' is the problem here. I think you may want to try libraryTarget: "this" instead? - Kenton Varda
Ok, looks like I have been able to make some progress here, I'm getting 10023 "Unauthorized" - martosoler
"Unauthorized" usually means your API key is incorrect. Is it possible that it changed? - Kenton Varda

1 Answers

0
votes

The problem here is libraryTarget: 'commonjs'. This is incorrect for workers. You should use libraryTarget: "this" instead, or omit libraryTarget altogether.

We recently published a blog post on how to use Webpack with Cloudflare Workers: https://blog.cloudflare.com/using-webpack-to-bundle-workers/