Vite-ssg 套件是個若你使用 Vite 開發但又不想使用其他現代 SSG 框架如 Nuxt 的一個便利選擇。這邊筆記下若你想對輸出完成後的檔案做一些如變更 html 名稱、自動壓縮檔案…等自動化操作,該如何設定。
內容
套件
https://github.com/antfu-collective/vite-ssg
在 vite 的設定檔中,新增 ssgOptions.onFInished() 。這個 callback 內搭配 node:path 的 resolve 和 join,再搭配 archiver 套件一同使用,就可完成。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
{ ssgOptions: { async onFinished() { const distDir = resolve(__dirname, 'dist') const outputDir = resolve(__dirname, 'dist-zip') const timestamp = new Date().toISOString().slice(0, 16).replace(/[-T:]/g, '') const renamedHtml = `${brand}.html` const zipName = `${brand}-${timestamp}.zip` const zipPath = join(outputDir, zipName) // Step 1: Rename index.html const indexPath = join(distDir, 'index.html') const targetPath = join(distDir, `${brand}.html`) if (fs.existsSync(indexPath)) { fs.renameSync(indexPath, targetPath) console.log(`✔ index.html renamed to ${renamedHtml}.html`) } else { console.warn('⚠ index.html not found, rename skipped.') } // Step 2: Prepare dist-zip folder if (!fs.existsSync(outputDir)) { fs.mkdirSync(outputDir, { recursive: true }) } // Step 3: Zip dist folder to dist-zip/${brand}.zip const output = fs.createWriteStream(zipPath) const archive = archiver('zip', { zlib: { level: 9 } }) output.on('close', () => { console.log(`✅ Zip created: dist-zip/${zipName} (${archive.pointer()} bytes)`) }) archive.on('error', err => { throw err }) archive.pipe(output) archive.glob('**/*', { cwd: distDir, ignore: ['.vite/**', '__MACOSX/**', 'robots.txt'] }) await archive.finalize() }, }, } |