webpack/css-loader

Catch errors when constructing CSSStyleSheet with `exportType: "css-style-sheet"`

Closed this issue · 2 comments

Feature Proposal

Allow to catch errors when constructing CSSStyleSheet with exportType: "css-style-sheet", in browsers which don't support it (such as Safari currently). See compatibility table.

Feature Use Case

Developers can choose to fallback to use style element, etc.

import sheet from "./style.css" assert { type: "css" }
import styleText from "./style.css"

if (sheet) {
  shadowRoot.adoptedStyleSheets = [sheet];
} else {
  // Assume that it returns null when construct failed.
  const style = document.createElement("style");
  style.textContent = styleText;
  shadowRoot.appendChild(style);
}

Or, return the sheet as cssText when construct failed:

import sheet from "./style.css" assert { type: "css" }

if (typeof sheet === "string") {
  style.textContent = sheet;
} else {
  shadowRoot.adoptedStyleSheets = [sheet];
}

Or, return as separate variables:

import myStyle from "./style.css" assert { type: "css" }

if (myStyle.cssStyleSheet) {
  shadowRoot.adoptedStyleSheets = [sheet];
} else {
  style.textContent = myStyle.cssText;
}

Please paste the results of npx webpack-cli info here, and mention other relevant information

  System:
    OS: macOS 12.5
    CPU: (8) arm64 Apple M1
    Memory: 133.88 MB / 8.00 GB
  Binaries:
    Node: 16.15.0 - ~/.nvm/versions/node/v16.15.0/bin/node
    Yarn: 1.22.18 - ~/.nvm/versions/node/v16.15.0/bin/yarn
    npm: 8.5.5 - ~/.nvm/versions/node/v16.15.0/bin/npm
  Browsers:
    Chrome: 108.0.5359.98
    Firefox: 101.0.1
    Safari: 15.6
  Monorepos:
    Yarn Workspaces: 1.22.18
    Lerna: 6.1.0
  Packages:
    null-loader: ^4.0.1 => 4.0.1

Close this, it seems that I can use exportType: "string" and construct CSStyleSheet by myself.

I think it is possible to catch errors only on import(...) (dynamic import), we can implement an option to run fallback, but I am afraid it will not be flexible