Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vote for variable decorators! #552

Open
stfbd12138 opened this issue Jan 24, 2025 · 0 comments
Open

Vote for variable decorators! #552

stfbd12138 opened this issue Jan 24, 2025 · 0 comments

Comments

@stfbd12138
Copy link

stfbd12138 commented Jan 24, 2025

Have you heard webpack's Hot Module Reloading(HMR) tech?

Suppose you have a module which declared a module-scope variable:

const resource = [];

Later, you want the module to be hot-loadedable. To let it working , webpack suggests that you can:

// Use previous resource object, or create a new one.
const resource = import.meta.hot.data['r'] ?? [];

// Save the data before module is about to reload
import.meta.hot.dispose((data) => void data['r'] = resource);

I don't know about you, I personally feel it's trivial.

Now, if we got the planning const declarator, we can simply it into:

@hotReload(import.meta) // Oh, just one line, simplier and clear!
const resource = [];

where, @hotReload can be implemented as:

export function hotReload(importMeta) {
  return (initializer, context) => {
    // context.kind  --> like other decoarators
    // context.name --> the variable's name
    // initializer --> the variable's initializer function

    if (context.kind !== 'constDeclarator') {
      throw new Errror(`@hotReload can only be attached to const declarator!`);
    }
    const value = importMeta.hot.data[context.name] ?? initializer();
    importMeta.hot.dispose((data) => void data[context.name] = value);
    return value;
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant