Local node module for Workers, Unexpected token Error


I’m having fun modularizing my code into locally available node.js modules. I’m 90% or the way there, but encountering one sticky error that I just can’t seem to figure out. Although it should be pretty simple.

I have a private git repo hosting this first module, I add the module by git+https://... reference, and import { ... } from 'mymodule'. The npm install ... goes fine, the error is with wrangler build (this is a Workers Site project):

$ wrangler build
⬇️ Installing wranglerjs...
⬇️ Installing wasm-pack...
 ./workers-site/node_modules/@cbi/logit/index.js 48:31
Module parse failed: Unexpected token (48:31)
You may need an appropriate loader to handle this file type.
|     /* store in the KV for later retrieval */
>     await LOGS.put(key, logs_s))
| }
 @ ./workers-site/index.js 2:0-97
Error: webpack returned an error. You may be able to resolve this issue by running npm install.

Well, obviously, during build, the Workers KV symbol, LOGS, isn’t going to be defined. How do I make it happy?

I’ve been digging through the CF kv-asset-handler code, and trying to mimic it, but without success. Although it has __STATIC_CONTENT as a KV store…

Any insight from the JS experts?

To make the question a bit more concise: How does the CF code at https://github.com/cloudflare/kv-asset-handler.git avoid the fact that __STATIC_CONTENT is undefined?

There’s a “allow user submitted options to override defaults” using Object.assign(), but I don’t see how that’s fooling webpack?

To answer your question that is correct __STATIC_CONTENT is a KV store bound to the script. Javascript does not actually care about undefined variables until runtime. (Note Typescript does and there is another work around for that if you’re interested) So the undefined variable is not what is throwing this error.

For your code, I see there is a syntax error:

await LOGS.put(key, logs_s))

Remove the extra ) to get webpack running. You also want to make sure you have LOGS all set up as a KV https://developers.cloudflare.com/workers/tooling/wrangler/kv_commands/#overview