How to dynamically import only the JS from a component and still split its assets?

426 views Asked by At

I have got a component which is being imported dynamically, by an entry script file:


let button: HTMLButtonElement;

button = document.querySelector("#myButton") as HTMLButtonElement;

button.addEventListener('click', async () => {
  
  const { 
    default: Greeter 
  } = await import(
    /* webpackChunkName: "greeter" */ 
    '../shared/greeter/greeter'
  );

  new Greeter('Hello, govner!');
});

When the user clicks a button, all the component scripts and styles are loaded.

While this works, it's not good becase I need the component styles to be rendered statically, so the page style is not broken, until the user clicks the button.

The solution would be importing the component styles, along with this entry script file:

import './index.scss';
import './greeter.scss';

What it produces:

  • component styles are loaded statically, along with the rest of the page;
  • when/if they hit the button, then they'll have a component with behaviors.

Although, it compiles both stylesheets into only one file: index.[contentHash].css.

Not good! Reasons being:

  • file size;
  • not possible to achieve cache busting, properly.

What I expect:

  • split stylesheets;
  • automatically inject component corresponding stylesheet, into HTML;
  • dynamically load component script.

This would make it possible to:

  • have smaller files;
  • do cache busting only on updated style chunks.
0

There are 0 answers