systemjs / systemjs

Dynamic ES module loader

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Apply CSS from nested dependency

jackw opened this issue · comments

  • SystemJS Version:
  • Which library are you using?
    • system.js
    • s.js
    • system-node.cjs
  • Which extras are you using?
    • AMD extra
    • Named Exports
    • Named Register
    • Transform
    • Use Default
    • Global
    • Dynamic Import Maps
  • Are you using any custom hooks?

Yes, fetch and resolve.

Question

I'm attempting to migrate a project from systemjs@0.20.19 to 6.14.1. For the most part things are working well although I've hit something that I cannot figure out. Almost everything works except the CSS files that are fetched aren't affecting the styles of the page. I've looked at the module-types extra source code and it wraps the res.text result in var s=new CSSStyleSheet();s.replaceSync(). I saw in the docs that to make use of this I would need to do the following:

System.import('file.css').then(function (module) {
  const styleSheet = module.default; // A CSSStyleSheet object
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, styleSheet]; // now your css is available to be used.
});

However I'm not directly importing the file.css it's part of the waterfall of dependencies that the .js entry point eventually requires. Is there a preferred hook that should be used to get a reference to the stylesheet and apply the styles if I'm not directly importing the file with System.import? I guess the alternative would be to hook instantiate and if it's a css file create a style tag and dump the contents there as happens in earlier versions of Systemjs.

Not too confident this is the way to go but using the system onload hook allows me to do what I need.

systemJSPrototype.onload = function (err: unknown, id: string, deps: string[], isErrSource: boolean) {
  if (id.endsWith('.css') && !err) {
    const module = SystemJS.get(id);
    const styles = module?.default;
    if (styles) {
      document.adoptedStyleSheets = [...document.adoptedStyleSheets, styles];
    }
  }
};