scan-component-paths.mjs 1.75 KB
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const skipDirs = new Set(['node_modules', 'miniprogram_npm', '.git', 'dist'])
const exts = ['', '.js', '.json', '.wxml', '.wxss', '.sass', '/index.js']

function resolveComponent(fromJson, spec) {
  if (!spec.startsWith('.')) return { ok: true }
  let target = path.resolve(path.dirname(fromJson), spec)
  if (path.extname(target)) return { ok: fs.existsSync(target), target }
  for (const ext of exts) {
    const p = target + (ext.startsWith('/') ? ext : ext)
    if (fs.existsSync(p)) return { ok: true, target: p }
  }
  return { ok: false, target }
}

function walk(dir, files = []) {
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
    if (skipDirs.has(e.name)) continue
    const full = path.join(dir, e.name)
    if (e.isDirectory()) walk(full, files)
    else if (e.name.endsWith('.json') && !e.name.includes('project')) files.push(full)
  }
  return files
}

const broken = []
for (const file of walk(root)) {
  let json
  try {
    json = JSON.parse(fs.readFileSync(file, 'utf8'))
  } catch {
    continue
  }
  const comps = json.usingComponents
  if (!comps || typeof comps !== 'object') continue
  for (const [name, spec] of Object.entries(comps)) {
    if (typeof spec !== 'string' || !spec.startsWith('.')) continue
    const { ok } = resolveComponent(file, spec)
    if (!ok) {
      broken.push({
        page: path.relative(root, file).replace(/\\/g, '/'),
        name,
        spec
      })
    }
  }
}

broken.sort((a, b) => a.page.localeCompare(b.page))
console.log(`BROKEN_COMPONENT_PATHS=${broken.length}`)
for (const b of broken) {
  console.log(`${b.page} [${b.name}] -> ${b.spec}`)
}