vue3如何批量设置每个vue页面的defineOptions的name
@TOC
1.思路
通过遍历src/views下的文件,找到.vue文件,截取文件路径的最后两位或全部路径,使用驼峰命名
2.创建脚本
可以通过脚本批量修改 .vue 文件
创建脚本 auto-set-component-name.mjs
import fs from "fs"
import path from "path"
import { fileURLToPath } from "url"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// 🔧 配置区 ============================================
const targetDir = path.join(__dirname, "src/views")
const PATH_DEPTH = Infinity // 自由修改数字:2→最后两级,3→最后三级,Infinity→全部路径
// =====================================================
const toPascalCase = (str) => {
return str
.replace(/[-_](.)/g, (_, c) => c.toUpperCase())
.replace(/(^\w)/, m => m.toUpperCase())
.replace(/\.vue$/, '')
}
const processDirectory = (dir) => {
const files = fs.readdirSync(dir, { withFileTypes: true })
files.forEach(file => {
const fullPath = path.join(dir, file.name)
file.isDirectory() ? processDirectory(fullPath) : processVueFile(fullPath)
})
}
const processVueFile = (filePath) => {
if (path.extname(filePath) !== '.vue') return
const relativePath = path.relative(targetDir, filePath)
const pathSegments = relativePath
.split(path.sep)
.slice(-PATH_DEPTH) // 🔥 核心修改点:根据配置截取路径段
.map(segment => toPascalCase(segment))
const componentName = pathSegments.join('')
let content = fs.readFileSync(filePath, 'utf8')
// 修复正则表达式:支持任意顺序的 setup 属性
const scriptSetupRegex = /<script\s+((?:.(?!\/script>))*?\bsetup\b[^>]*)>/gmi
if (!content.includes('defineOptions')) {
content = content.replace(scriptSetupRegex, (match, attrs) => {
return `<script ${attrs}>
defineOptions({
name: '${componentName}'
})`
})
fs.writeFileSync(filePath, content)
console.log(`✅ 成功注入 name: ${componentName} → ${filePath}`)
}
}
processDirectory(targetDir)
console.log('🎉 所有 Vue 组件 name 注入完成!')
3.运行脚本
node auto-set-component-name.mjs