当前位置: 首页 > news >正文

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

相关文章:

  • Web Workers 技术解析与应用
  • # 基于 OpenCV 的人脸识别实战:从基础到进阶
  • 贪心进阶学习笔记
  • Elasticsearch简介及索引库操作
  • 全新开源PHP轻量级活码管理系统|支持二维码动态更新与自动失效机制
  • 【力扣hot100题】(064)在排序数组中查找元素的第一个和最后一个位置
  • 【Tauri2】015——前端的事件、方法和invoke函数
  • Docker常用操作教程
  • java发送http请求
  • 数字化转型:重构生存逻辑,不止系统升级
  • AI面试实践手册|牛客网
  • Flutter 打包APK的几种方式
  • 架构思维: 全链路日志深度解析
  • 【LeetCode】在每个树行中找最大值(DFS 深度优先搜索)
  • QT6 C++视频播放器实现(基于QGraphicsVideo)
  • 数据结构----------顺序查找,折半查找和分块查找(java实现)
  • 解决conda命令报错CondaSSLError(mac也适用)
  • 机器视觉3D中激光偏镜的优点
  • 基于α-β剪枝的含禁手AI五子棋
  • MySQL的存储引擎有哪些,它们之间有什么区别?
  • 南宁国贸网站建设/域名解析ip
  • 动态页面怎么做/泉州seo代理计费
  • 企业网站案例分析/什么是sem
  • 企业网站的作用/免费网站在线观看人数在哪直播
  • 注册公司注册/seo怎么做教程
  • 坂田杨美企业网站建设/谷歌app下载