marco-prontera / vite-plugin-css-injected-by-js

A Vite plugin that takes the CSS and adds it to the page through the JS. For those who want a single JS file.
MIT License
427 stars 26 forks source link

Checking the existence style with id in the header #127

Closed chsgrch closed 1 year ago

chsgrch commented 1 year ago

https://github.com/marco-prontera/vite-plugin-css-injected-by-js/blob/4048c06146f9c8e478ef2568b0b04f8172d31501/src/utils.ts#L15

It would be good to check if the style exists in the head block before adding it to the head because when working with micro fronts style are added twice

marco-prontera commented 1 year ago

We can't cover any use case, for that reason you can customize the injection function with injectCode or injectCodeFunction parameters explained in the readme. If you need help, write here. Hope it helps

chsgrch commented 1 year ago

We can't cover any use case, for that reason you can customize the injection function with injectCode or injectCodeFunction parameters explained in the readme. If you need help, write here. Hope it helps

Thanks for the answer, I implemented it like this


      relativeCSSInjection: true,
      styleId: () => `kit-${pkg?.version}--${Math.floor(1000 + Math.random() * 9000)}`,
      injectCodeFunction: function injectCodeCustomRunTimeFunction(cssCode, options) {
        try {
          if (typeof document != 'undefined' && document.getElementById(options?.styleId)) {
            return
          }
          if (typeof document != 'undefined') {
            const elementStyle = document.createElement('style')
            elementStyle.setAttribute('id', options?.styleId)
            elementStyle.appendChild(document.createTextNode(cssCode))
            document.head.appendChild(elementStyle)
          }
        } catch (e) {
          console.error('vite-plugin-css-injected-by-js', e)
        }
      }
    })