Dev

[Vite + React] Preload๋กœ ํฐํŠธ ์ตœ์ ํ™”ํ•˜๊ธฐ

์–‘๋‚˜๋‹ˆ 2024. 5. 7. 19:58

1. index.html์—์„œ link ํƒœ๊ทธ์— preload ์ถ”๊ฐ€

-> ๊ฐ€์žฅ ๊ฐ„ํŽธํ•˜๊ณ  ๋ณดํŽธ์ ์ธ ๋ฐฉ๋ฒ•. ํ”„๋กœ์ ํŠธ ๊ทœ๋ชจ๊ฐ€ ์ž‘๊ฑฐ๋‚˜ ํฐํŠธ ํŒŒ์ผ์ด ํ•œ๋‘๊ฐœ๋ผ๋ฉด ์ˆ˜๋™์œผ๋กœ link ํƒœ๊ทธ๋ฅผ ์ถ”๊ฐ€ํ•˜๋ฉด ๋จ

// index.html
<head>
        <link
			rel="preload"
			href="src/assets/fonts/PretendardVariable.woff2"
			as="font"
			type="font/woff2"
			crossorigin="anonymous"
		/>
</head>

 

2. build ์‹œ ๋™์ ์œผ๋กœ html ์ฃผ์ž…ํ•˜๊ธฐ

createHtmlPlugin ์‚ฌ์šฉ์œ„ํ•ด vite-plugin-html ์„ค์น˜

npm install -D vite-plugin-html

 

ํฐํŠธ ํด๋”์—์„œ ํ”„๋ฆฌ๋กœ๋“œํ•  ํฐํŠธ ์„ ํƒ

// src/utils/fontPreload.ts

import { readdirSync } from 'fs'
import { resolve } from 'path'

import { HtmlTagDescriptor } from 'vite'

const fontsDirectory = resolve(__dirname, '../../src/assets/fonts')
console.log('fontsDirectory', fontsDirectory)

const fontFiles = readdirSync(fontsDirectory).filter(
	(file) => file.endsWith('.woff2'),
)

export const injectFontsToHead: HtmlTagDescriptor[] = fontFiles.map((fontFile) => ({
		injectTo: 'head',
		tag: 'link',
		attrs: {
			rel: 'preload',
			href: `src/assets/fonts/${fontFile}`,
			as: 'font',
			type: 'font/woff2',
			crossOrigin: 'anonymous',
		}
}))

 

vite.config.ts์—์„œ src/util ํด๋”์— ์ ‘๊ทผํ•˜๋ ค๋ฉด tsconfig.node.json ํŒŒ์ผ์˜ include๋ถ€๋ถ„์— ํ•ด๋‹น ํŒŒ์ผ์„ ์ถ”๊ฐ€ํ•ด์•ผํ•จ

// tsconfig.node.json
{
	"compilerOptions": {
		...
	},
	"include": ["vite.config.ts", "src/utils/font.ts"]
}

 

vite.config.ts์—์„œ injectFontsToHead ์ฝ”๋“œ ์ฃผ์ž…

// vite.config.ts

import { createHtmlPlugin } from 'vite-plugin-html'
import { injectFontsToHead } from './src/utils/font'

export default defineConfig({
	plugins: [..., createHtmlPlugin({ inject: { tags: injectFontsToHead } })],
})

 

 

๋‘ ๋ฐฉ๋ฒ• ์‚ฌ์ด์— ์„ฑ๋Šฅ ์ฐจ์ด๋Š” ์—†๋Š” ๊ฒƒ ๊ฐ™๊ณ (๋‘ ๋ฐฉ๋ฒ• ๋ชจ๋‘ 17~30ms ๋‚ด๋กœ ๋ถˆ๋Ÿฌ์˜ด) ํ”„๋กœ์ ํŠธ ๊ด€๋ฆฌ ๋ฐฉ๋ฒ•์— ๋”ฐ๋ผ ์„ ํƒํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™๋‹ค.

vite ์„ค์ •์„ ๊ฑด๋“œ๋Š” ๊ฑด ๊ท€์ฐฎ์ง€๋งŒ ํ”„๋กœ์ ํŠธ๊ฐ€ ํฌ๊ณ  ์ž์ฃผ ์—…๋ฐ์ดํŠธ ๋œ๋‹ค๋ฉด ์ž๋™ํ™”ํ•ด์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒŒ ํŽธํ•  ์ˆ˜๋„ ์žˆ์„ ๊ฒƒ ๊ฐ™๋‹ค.

 

์ค‘์š”ํ•œ ๊ฑด ๊ผญ ์ฒซ ํ™”๋ฉด์— ํ•„์ˆ˜์ ์ธ ํฐํŠธ๋งŒ ํ”„๋ฆฌ๋กœ๋”ฉํ•˜๋Š” ๊ฒƒ!

 


์ฐธ๊ณ  https://velog.io/@oo009pbh/Vite๋ฅผ-ํ†ตํ•ด-๋‹ค์šด๋ฐ›์€-ํฐํŠธ๋ฅผ-preloading-ํ•ด๋ณด์ž