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

Add CSS entrypoints to the manifest #9

Merged
merged 1 commit into from Jun 10, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 34 additions & 1 deletion src/index.ts
Expand Up @@ -2,7 +2,7 @@ import fs from 'fs'
import { AddressInfo } from 'net'
import path from 'path'
import colors from 'picocolors'
import { Plugin, loadEnv, UserConfig, ConfigEnv, ResolvedConfig } from 'vite'
import { Plugin, loadEnv, UserConfig, ConfigEnv, Manifest, ResolvedConfig } from 'vite'

interface PluginConfig {
/**
Expand Down Expand Up @@ -54,6 +54,7 @@ export default function laravel(config?: string|string[]|Partial<PluginConfig>):
const pluginConfig = resolvePluginConfig(config)
let viteDevServerUrl: string
let resolvedConfig: ResolvedConfig
const cssManifest: Manifest = {}

const ziggy = 'vendor/tightenco/ziggy/dist/index.es.js';
const defaultAliases: Record<string, string> = {
Expand Down Expand Up @@ -144,6 +145,38 @@ export default function laravel(config?: string|string[]|Partial<PluginConfig>):
process.on('SIGHUP', clean)
process.on('SIGINT', clean)
process.on('SIGTERM', clean)
},

// The following two hooks are a workaround to help solve a "flash of unstyled content" with Blade.
// They add any CSS entry points into the manifest because Vite does not currently do this.
renderChunk(_, chunk) {
const cssLangs = `\\.(css|less|sass|scss|styl|stylus|pcss|postcss)($|\\?)`
const cssLangRE = new RegExp(cssLangs)

if (! chunk.isEntry || chunk.facadeModuleId === null || ! cssLangRE.test(chunk.facadeModuleId)) {
return null
}

const relativeChunkPath = path.relative(resolvedConfig.root, chunk.facadeModuleId)

cssManifest[relativeChunkPath] = {
/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */
/* @ts-ignore */
file: Array.from(chunk.viteMetadata.importedCss)[0],
src: relativeChunkPath,
isEntry: true,
}

return null
},
writeBundle() {
const manifestPath = path.resolve(resolvedConfig.root, resolvedConfig.build.outDir, 'manifest.json')
const manifest = JSON.parse(fs.readFileSync(manifestPath).toString())
const newManifest = {
...manifest,
...cssManifest,
}
fs.writeFileSync(manifestPath, JSON.stringify(newManifest, null, 2))
}
}
}
Expand Down