Lỗi content-script-type text javascript content-style năm 2024

The


Browser Support

Element

What I found is that if you import "index.css" and modify the index.css file HMR does work properly. This has two obvious problems though:

  1. import "index.css" auto injects the css into the document.head which is undesirable because we want it to only apply to the shadow root.
  2. If you're using tailwindcss you aren't directly modifying the index.css file, so the HMR won't actually trigger.

However, it is enough to get a little hack going. In my app i'm using svelte in the content script that is mounted in a closed shadow root. Ignoring the mounting code, I have a svelte component that looks something like

{@html styleTag}

hello world

Okay so to solve the first issue, I find the style tag that vite injects into the head, and I nullify it's effects on the page by setting styletag.media = 'max-width: 0px' this scopes the innerText of the tag to only apply when the browser has zero width, so basically always disabled. Then I create a style tag with the same contents as the one vite injected into the document.head, then svelte puts it in the shadow root via the {@html styleTag}. This can be pretty trivially adopted for react or w/e framework.

Then for the second issue, I create a VIM autocmd autocmd BufWritePost * silent! !touch src/app.css which does a zero edit change to the css via touch any time any file in my project is written. If you aren't a VIM user, i'm sure there is something equivalent in VSCode.

It's obviously not ideal, but it gets HMR working with shadow root CSS with Tailwind in development which is good enough for me for now.