Last active
September 16, 2024 21:35
-
-
Save ksk1015/cf959f43bd2a09a679dc1e3ae77b09c0 to your computer and use it in GitHub Desktop.
esbuildでビルドされたCSSをJSに埋め込む
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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