Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Inject css (sometimes it doesn't work) #1

Closed
crashmax-dev opened this issue Aug 15, 2022 · 0 comments · Fixed by #3 or #10
Closed

Inject css (sometimes it doesn't work) #1

crashmax-dev opened this issue Aug 15, 2022 · 0 comments · Fixed by #3 or #10
Labels
bug Something isn't working enhancement New feature or request

Comments

@crashmax-dev
Copy link
Collaborator

crashmax-dev commented Aug 15, 2022

vitejs/vite#1579 (comment)

vitejs/vite#1579 (comment)

import fs from 'fs'
import { resolve } from 'path'
import type { ResolvedConfig, PluginOption } from 'vite'

const fileRegex = /\.(css)$/

const injectCode = (code: string) =>
  `function styleInject(css,ref){if(ref===void 0){ref={}}var insertAt=ref.insertAt;if(!css||typeof document==="undefined"){return}var head=document.head||document.getElementsByTagName("head")[0];var style=document.createElement("style");style.type="text/css";if(insertAt==="top"){if(head.firstChild){head.insertBefore(style,head.firstChild)}else{head.appendChild(style)}}else{head.appendChild(style)}if(style.styleSheet){style.styleSheet.cssText=css}else{style.appendChild(document.createTextNode(css))}};styleInject(\`${code}\`)`
const template = `console.warn("__INJECT__")`

let viteConfig: ResolvedConfig
const css: string[] = []

export default function injectCss(): PluginOption {
  return {
    name: 'inject-css',
    apply: 'build',
    configResolved(resolvedConfig) {
      viteConfig = resolvedConfig
    },
    transform(code, id) {
      if (fileRegex.test(id)) {
        css.push(code)
        return {
          code: ''
        }
      }

      if (id.includes(viteConfig.build.lib.entry)) {
        return {
          code: code + template
        }
      }

      return null
    },
    async writeBundle(options, bundle) {
      for (const file of Object.entries(bundle)) {
        const { root } = viteConfig
        const outDir = viteConfig.build.outDir || 'dist'
        const fileName = file[0]
        const filePath = resolve(root, outDir, fileName)

        try {
          let data = fs.readFileSync(filePath, {
            encoding: 'utf8'
          })

          if (data.includes(template)) {
            data = data.replace(template, injectCode(css.join('\n')))
          }

          fs.writeFileSync(filePath, data)
        } catch (e) {
          console.error(e)
        }
      }
    }
  }
}
@crashmax-dev crashmax-dev reopened this Aug 16, 2022
@crashmax-dev crashmax-dev added the bug Something isn't working label Aug 18, 2022
@crashmax-dev crashmax-dev changed the title Inject css Inject css (sometimes it doesn't work) Aug 18, 2022
@crashmax-dev crashmax-dev added the enhancement New feature or request label Aug 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working enhancement New feature or request
Projects
None yet
1 participant