Skip to content

Instantly share code, notes, and snippets.

@ksk1015
Last active September 16, 2024 21:35
Show Gist options
  • Save ksk1015/cf959f43bd2a09a679dc1e3ae77b09c0 to your computer and use it in GitHub Desktop.
Save ksk1015/cf959f43bd2a09a679dc1e3ae77b09c0 to your computer and use it in GitHub Desktop.
esbuildでビルドされたCSSをJSに埋め込む
import esbuild from 'esbuild'
import { fileURLToPath, URL } from 'node:url'
import fs from 'node:fs'
const entryPoint = fileURLToPath(new URL('../src/app.js', import.meta.url))
const outdir = fileURLToPath(new URL('../dist', import.meta.url))
// ビルドされたcssをjsに埋め込む
function injectCssToJs(outputFilename = (jsFilename) => jsFilename) {
return {
name: 'inject-css-to-js-plugin',
setup(build) {
build.onEnd((result) => {
result.outputFiles
.filter((file) => file.path.endsWith('.css'))
.forEach((cssFile) => {
const jsFilePath = cssFile.path.replace(/\.css$/, '.js')
const jsFile = result.outputFiles.find(
(file) => file.path === jsFilePath
)
if (!jsFile) return
const jsFilename = jsFilePath.split('/').pop()
const outputPath = jsFile.path.replace(
jsFilename,
outputFilename(jsFilename)
)
const injectCode = `(s=>{s.textContent=\`${cssFile.text}\`;document.head.appendChild(s)})(document.createElement('style'));`
fs.writeFileSync(outputPath, injectCode + jsFile.text)
})
})
},
}
}
esbuild
.build({
entryPoints: [entryPoint],
outdir: outdir,
bundle: true,
minify: true,
sourcemap: false,
write: false,
plugins: [injectCssToJs()],
})
.catch(() => {
process.exit(1)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment