tc39 / proposal-module-expressions

https://tc39.es/proposal-module-expressions/
MIT License
438 stars 18 forks source link

Use case: co-locating server and client code #80

Open nicolo-ribaudo opened 1 year ago

nicolo-ribaudo commented 1 year ago

Different frameworks are moving towards co-location of code that runs on the server and on the client. Some examples are React with "use server"/"use client", Qwik with server$, and Solid with server$.

They all use functions, that can have confusing behaviors because they can close over variables "from the server to the client" and vice versa. Module expression would give a clear boundary:

// Rendered on server
function MyButton() {
  return (
    <button onClick={module {
      // Running on client
      export default () => alert("Clicked!");
    }>
      {fs.readFileSync("./btn-text")}
    </button>
  );
}

This might be another good use case for the shorthand syntax (https://github.com/tc39/proposal-module-expressions/issues/59)

(cc @ryansolid thanks for the idea!)

voxpelli commented 1 year ago

Related: https://github.com/tc39/proposal-module-expressions/issues/61

littledan commented 1 year ago

Honestly I think this would be better with module declarations. It would certainly be nice to have for us in Bloomberg for this purpose. https://github.com/tc39/proposal-module-declarations/issues/14

guybedford commented 1 year ago

Afaict, this use case would effectively require a toString() returning the source of the module? That seems doable and not a security concern (since the security concern is the reverse - creating modules from strings), but just needs to be specified?

guybedford commented 1 year ago

Perhaps this use case also requires context extraction, ie URL extraction? That's where it might get more difficult to specify short of a getImportMeta().