Skip to content

Commit

Permalink
feat: minify injected css when building
Browse files Browse the repository at this point in the history
resolves #20
  • Loading branch information
danielroe committed Feb 29, 2024
1 parent b9ad9fd commit e906ada
Show file tree
Hide file tree
Showing 6 changed files with 49 additions and 162 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"chalk": "^5.3.0",
"css-tree": "^2.3.1",
"defu": "^6.1.4",
"esbuild": "^0.20.1",
"fontaine": "^0.4.1",
"globby": "^14.0.1",
"h3": "^1.11.1",
Expand Down
16 changes: 10 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ export default defineNuxtModule<ModuleOptions>({
})

addBuildPlugin(FontFamilyInjectionPlugin({
dev: nuxt.options.dev,
async resolveFontFace (fontFamily, fallbackOptions) {
const override = options.families?.find(f => f.name === fontFamily)

Expand Down
16 changes: 14 additions & 2 deletions src/plugins/transform.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createUnplugin } from 'unplugin'
import { parse, walk } from 'css-tree'
import MagicString from 'magic-string'
import { transform } from 'esbuild'

import type { Awaitable, NormalizedFontFaceData } from '../types'
import { extractEndOfFirstChild, extractFontFamilies, extractGeneric, type GenericCSSFamily } from '../css/parse'
Expand All @@ -13,6 +14,7 @@ export interface FontFaceResolution {

interface FontFamilyInjectionPluginOptions {
resolveFontFace: (fontFamily: string, fallbackOptions?: { fallbacks: string[], generic?: GenericCSSFamily }) => Awaitable<undefined | FontFaceResolution>
dev: boolean
}

const SKIP_RE = /\/node_modules\/(vite-plugin-vue-inspector)\//
Expand Down Expand Up @@ -44,10 +46,20 @@ export const FontFamilyInjectionPlugin = (options: FontFamilyInjectionPluginOpti
const fallbackDeclarations = await generateFontFallbacks(fontFamily, font, fallbackMap)
const declarations = [generateFontFace(fontFamily, font), ...fallbackDeclarations]

for (const declaration of declarations) {
for (let declaration of declarations) {
if (!injectedDeclarations.has(declaration)) {
injectedDeclarations.add(declaration)
s.prepend(declaration + '\n')
if (!options.dev) {
// TODO: resolve options from user's vite config
declaration = await transform(declaration, {
loader: 'css',
charset: 'utf8',
minify: true
}).then(r => r.code || declaration).catch(() => declaration)
} else {
declaration += '\n'
}
s.prepend(declaration)
}
}

Expand Down
Loading

0 comments on commit e906ada

Please sign in to comment.