theKashey / used-styles

πŸ“All the critical styles you've used to render a page.
MIT License
138 stars 10 forks source link

Cloudflare workers compatibility #40

Closed maraisr closed 5 months ago

maraisr commented 2 years ago

Hello πŸ‘‹πŸ»

We are wanting to use this library with Cloudflare workers, and thes during SSR we cannot scan the directory.

https://github.com/theKashey/used-styles/blob/cb432b143517d877a21ccf280fca3752420ae04d/src/scanForStyles.ts#L18

https://github.com/theKashey/used-styles/blob/cb432b143517d877a21ccf280fca3752420ae04d/src/scanForStyles.ts#L157

So was hoping we can extract the core functionality into a series of helpers so that during node, for sure you can scan a file system, and in workers one can use Workers KV to read the css files (or local fetch within context of Pages).

loadStyleDefinitions doesn't require to be in that file.


So mainly about 2 main moments.

  1. split functionality from runtime
  2. allow non-tree shaken bundles to load correctly.
    • we noticed that webpack5 doesn't treeshake in dev mode, as such loading this file in workers context cannot bind fs.
wellyshen commented 2 years ago

Hey @theKashey, I have tested this library with Clouldflare worker, and it works great. All we need is to use loadStyleDefinitions and pass the client assets through Couldfare KV for dev/prod. So I'm trying to split the loadStyleDefinitions from discoverProjectStyles (which relies on fs that doesn't run on worker). And plan to use conditional exports for the worker users. But I'm wondering how to export different build files by lib-builder? Can't find related documents for that πŸ€”

theKashey commented 2 years ago

Frankly speaking - have no idea how to conditionally target package for a 'worker'. Probably it will be node + browser + default (not node and not browser). But you know - if something is not clear, and ESM/node exports are 'not clear' - let's not use it. And this is why I am not using them.

You might look into two solutions:

wellyshen commented 2 years ago

Hmm... the wired thing is even though we did isolate, once a module containing fs related things is exported that isn't used in the project, the worker still initializes it and fails to run.

For now, I will fork this library and modify it for running on the worker.

theKashey commented 2 years ago

That is actually a really good solution to unblock yourself as well as being able to verify assumption and provide a way forward for the 'mainstream'