Files
cz-app/scripts/extract-vue-styles.mjs
2026-09-14 17:09:25 +08:00

69 lines
1.9 KiB
JavaScript

import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'src')
function walk(dir, files = []) {
for (const name of fs.readdirSync(dir)) {
const full = path.join(dir, name)
if (fs.statSync(full).isDirectory())
walk(full, files)
else if (name.endsWith('.vue'))
files.push(full)
}
return files
}
function extractVue(vuePath) {
const content = fs.readFileSync(vuePath, 'utf8')
const base = path.basename(vuePath, '.vue')
const dir = path.dirname(vuePath)
const scssPath = path.join(dir, `${base}.scss`)
const patterns = [
{
regex: /<style scoped lang="scss">\r?\n([\s\S]*?)<\/style>/,
replacement: () => `<style scoped lang="scss">\n@import './${base}.scss';\n</style>`,
},
{
regex: /<style lang="scss">\r?\n([\s\S]*?)<\/style>/,
replacement: () => `<style lang="scss">\n@import './${base}.scss';\n</style>`,
},
{
regex: /<style scoped>\r?\n([\s\S]*?)<\/style>/,
replacement: () => `<style scoped lang="scss">\n@import './${base}.scss';\n</style>`,
},
{
regex: /<style>\r?\n([\s\S]*?)<\/style>/,
replacement: () => `<style lang="scss">\n@import './${base}.scss';\n</style>`,
},
]
for (const { regex, replacement } of patterns) {
const match = content.match(regex)
if (!match)
continue
const styleBody = match[1].trimEnd()
if (styleBody.includes(`@import './${base}.scss'`))
return false
fs.writeFileSync(scssPath, `${styleBody}\n`, 'utf8')
const next = content.replace(regex, replacement())
fs.writeFileSync(vuePath, next, 'utf8')
return true
}
return false
}
const vueFiles = walk(root)
let count = 0
for (const file of vueFiles) {
if (extractVue(file))
count += 1
}
console.log(`Extracted styles from ${count} Vue files.`)