refactor: vite config and re-optimize chunks

Signed-off-by: Innei <i@innei.in>
This commit is contained in:
Innei
2024-10-05 00:37:08 +08:00
parent 8c6753d4a6
commit e05d2bab75
17 changed files with 358 additions and 240 deletions
+39
View File
@@ -0,0 +1,39 @@
import path from "node:path"
import fs from "fs-extra"
import type { Plugin } from "vite"
export default function customAssetOutput(options: {
dependencies: Record<string, { sourceDir: string; targetDir: string }>
}): Plugin {
const { dependencies = {} } = options
return {
name: "vite-plugin-custom-asset-output",
async generateBundle(_, bundle) {
for (const [dependencyName, config] of Object.entries(dependencies)) {
const { sourceDir, targetDir } = config
for (const fileName in bundle) {
const file = bundle[fileName]
if (
file.type === "asset" &&
file.name &&
file.name.startsWith(`${dependencyName}/${sourceDir}`)
) {
const newFileName = file.name.replace(`${dependencyName}/${sourceDir}`, targetDir)
file.fileName = newFileName
await fs.ensureDir(path.dirname(newFileName))
bundle[newFileName] = file
delete bundle[fileName]
}
}
}
},
}
}
+33
View File
@@ -0,0 +1,33 @@
import type { Plugin, UserConfig } from "vite"
export function createDependencyChunksPlugin(dependencies: string[] | string[][]): Plugin {
return {
name: "dependency-chunks",
config(config: UserConfig) {
config.build = config.build || {}
config.build.rollupOptions = config.build.rollupOptions || {}
config.build.rollupOptions.output = config.build.rollupOptions.output || {}
const { output } = config.build.rollupOptions
const outputConfig = Array.isArray(output) ? output[0] : output
outputConfig.manualChunks = outputConfig.manualChunks || {}
outputConfig.assetFileNames = "assets/[name].[hash][extname]"
outputConfig.chunkFileNames = (chunkInfo) => {
return chunkInfo.name.startsWith("vendor/") ? "[name].[hash].js" : "assets/[name].[hash].js"
}
const manualChunks = Array.isArray(output) ? output[0].manualChunks : output.manualChunks
if (typeof manualChunks !== "object") return
dependencies.forEach((dep, index) => {
if (Array.isArray(dep)) {
const chunkName = `vendor/a${index}`
manualChunks[chunkName] = dep
} else {
manualChunks[`vendor/${dep}`] = [dep]
}
})
},
}
}
+29
View File
@@ -0,0 +1,29 @@
import type { PluginOption } from "vite"
import type { env as EnvType } from "../../packages/shared/src/env"
export function htmlInjectPlugin(env: typeof EnvType): PluginOption {
return {
name: "html-transform",
enforce: "post",
transformIndexHtml(html) {
return html.replace(
"<!-- FOLLOW VITE BUILD INJECT -->",
`<script id="env_injection" type="module">
${function injectEnv(env: any) {
for (const key in env) {
if (env[key] === undefined) continue
globalThis["__followEnv"] ??= {}
globalThis["__followEnv"][key] = env[key]
}
}.toString()}
injectEnv(${JSON.stringify({
VITE_API_URL: env.VITE_API_URL,
VITE_WEB_URL: env.VITE_WEB_URL,
VITE_IMGPROXY_URL: env.VITE_IMGPROXY_URL,
})})
</script>`,
)
},
}
}
+24
View File
@@ -0,0 +1,24 @@
import { readFileSync } from "node:fs"
import type { Plugin } from "vite"
export function customI18nHmrPlugin(): Plugin {
return {
name: "custom-i18n-hmr",
handleHotUpdate({ file, server }) {
if (file.endsWith(".json") && file.includes("locales")) {
server.ws.send({
type: "custom",
event: "i18n-update",
data: {
file,
content: readFileSync(file, "utf-8"),
},
})
// return empty array to prevent the default HMR
return []
}
},
}
}
+64
View File
@@ -0,0 +1,64 @@
import fs from "node:fs"
import path, { dirname } from "node:path"
import { fileURLToPath } from "node:url"
import { set } from "lodash-es"
import type { Plugin } from "vite"
export function localesPlugin(): Plugin {
return {
name: "locales-merge",
enforce: "post",
generateBundle(_options, bundle) {
const __dirname = dirname(fileURLToPath(import.meta.url))
const localesDir = path.resolve(__dirname, "../../locales")
const namespaces = fs.readdirSync(localesDir).filter((dir) => dir !== ".DS_Store")
const languageResources = {}
namespaces.forEach((namespace) => {
const namespacePath = path.join(localesDir, namespace)
const files = fs.readdirSync(namespacePath).filter((file) => file.endsWith(".json"))
files.forEach((file) => {
const lang = path.basename(file, ".json")
const filePath = path.join(namespacePath, file)
const content = JSON.parse(fs.readFileSync(filePath, "utf-8"))
if (!languageResources[lang]) {
languageResources[lang] = {}
}
const obj = {}
const keys = Object.keys(content as object)
for (const accessorKey of keys) {
set(obj, accessorKey, (content as any)[accessorKey])
}
languageResources[lang][namespace] = obj
})
})
Object.entries(languageResources).forEach(([lang, resources]) => {
const fileName = `locales/${lang}.js`
const content = `export default ${JSON.stringify(resources)};`
this.emitFile({
type: "asset",
fileName,
source: content,
})
})
// Remove original JSON chunks
Object.keys(bundle).forEach((key) => {
if (key.startsWith("locales/") && key.endsWith(".json")) {
delete bundle[key]
}
})
},
}
}
+57
View File
@@ -0,0 +1,57 @@
import type { Plugin } from "vite"
export function shortAliasPlugin(): Plugin {
const aliasMap = new Map<string, string>()
let aliasCounter = 0
function generateShortAlias(): string {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
let result = "_"
let counter = aliasCounter++
do {
result += chars[counter % chars.length]
counter = Math.floor(counter / chars.length)
} while (counter > 0)
return result
}
return {
name: "short-alias",
renderChunk(code, chunk) {
if (chunk.fileName.startsWith("vendor/")) return code
const importRegex = /import\s*(\{[^}]+\})\s*from\s*(['"])([^'"]+)\2/g
return code.replaceAll(importRegex, (match, imports, quote, source) => {
// Only process imports with curly braces
if (!imports.startsWith("{") || !imports.endsWith("}")) {
return match
}
const newImports = imports
.slice(1, -1) // Remove the curly braces
.split(",")
.map((imp) => {
const [original, alias] = imp.trim().split(/\s+as\s+/)
if (alias) {
// If an alias already exists, keep it or shorten it if it's too long
if (alias.length > 3) {
let shortAlias = aliasMap.get(alias)
if (!shortAlias) {
shortAlias = generateShortAlias()
aliasMap.set(alias, shortAlias)
}
return `${original} as ${shortAlias}`
}
return imp.trim()
}
return imp.trim()
})
.join(", ")
return `import {${newImports}} from ${quote}${source}${quote}`
})
},
}
}
+54
View File
@@ -0,0 +1,54 @@
import * as babel from "@babel/core"
import generate from "@babel/generator"
import { parse } from "@babel/parser"
import * as t from "@babel/types"
import type { Plugin } from "vite"
export function twMacro(): Plugin {
return {
name: "vite-plugin-tw-to-raw-string",
transform(code, id) {
// Only Process .tsx .ts .jsx .js files
if (!/\.[jt]sx?$/.test(id)) {
return null
}
// Parse the code using Babel's parser with TypeScript support
const ast = parse(code, {
sourceType: "module",
plugins: ["jsx", "typescript"], // Add typescript support
})
babel.traverse(ast, {
TaggedTemplateExpression(path) {
if (t.isIdentifier(path.node.tag, { name: "tw" })) {
const { quasi } = path.node
if (t.isTemplateLiteral(quasi)) {
// Create a new template literal by combining quasis and expressions
const quasis = quasi.quasis.map((q) => q.value.raw)
// Replace the tagged template expression with the new template literal as a string
path.replaceWith(
t.templateLiteral(
quasis.map((q, i) =>
t.templateElement({ raw: q, cooked: q }, i === quasis.length - 1),
),
quasi.expressions,
),
)
}
}
},
})
// Generate the transformed code from the modified AST
// @ts-expect-error
const output = generate.default(ast, {}, code)
return {
code: output.code,
map: null, // Source map generation can be added if necessary
}
},
}
}
+62
View File
@@ -0,0 +1,62 @@
import fs from "node:fs"
import path, { dirname } from "node:path"
import { fileURLToPath } from "node:url"
type LanguageCompletion = Record<string, number>
function getLanguageFiles(dir: string): string[] {
return fs.readdirSync(dir).filter((file) => file.endsWith(".json"))
}
function getNamespaces(localesDir: string): string[] {
return fs
.readdirSync(localesDir)
.filter((file) => fs.statSync(path.join(localesDir, file)).isDirectory())
}
function countKeys(obj: any): number {
let count = 0
for (const key in obj) {
if (typeof obj[key] === "object") {
count += countKeys(obj[key])
} else {
count++
}
}
return count
}
function calculateCompleteness(localesDir: string): LanguageCompletion {
const namespaces = getNamespaces(localesDir)
const languages = new Set<string>()
const keyCount: Record<string, number> = {}
namespaces.forEach((namespace) => {
const namespaceDir = path.join(localesDir, namespace)
const files = getLanguageFiles(namespaceDir)
files.forEach((file) => {
const lang = path.basename(file, ".json")
languages.add(lang)
const content = JSON.parse(fs.readFileSync(path.join(namespaceDir, file), "utf-8"))
keyCount[lang] = (keyCount[lang] || 0) + countKeys(content)
})
})
const enCount = keyCount["en"] || 0
const completeness: LanguageCompletion = {}
languages.forEach((lang) => {
if (lang !== "en") {
const percent = Math.round((keyCount[lang] / enCount) * 100)
completeness[lang] = percent
}
})
return completeness
}
const __dirname = dirname(fileURLToPath(import.meta.url))
const i18n = calculateCompleteness(path.resolve(__dirname, "../../../locales"))
export default i18n