inject-img-url.mjs 2.37 KB
/**
 * Inject IMG_URL from imageBase into js when sibling wxml uses {{ IMG_URL }}.
 */
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')

function walk(dir, acc = []) {
	for (const name of fs.readdirSync(dir, { withFileTypes: true })) {
		if (name.name === 'node_modules' || name.name === 'miniprogram_npm') continue
		const p = path.join(dir, name.name)
		if (name.isDirectory()) walk(p, acc)
		else if (name.name.endsWith('.wxml')) acc.push(p)
	}
	return acc
}

function resolveJs(wxmlPath) {
	const dir = path.dirname(wxmlPath)
	const base = path.basename(wxmlPath, '.wxml')
	const candidates = [
		path.join(dir, `${base}.js`),
		path.join(dir, 'index.js'),
	]
	for (const c of candidates) {
		if (fs.existsSync(c)) return c
	}
	return null
}

function importLineFor(jsPath) {
	const rel = path
		.relative(path.dirname(jsPath), path.join(root, 'utils/imageBase.js'))
		.split(path.sep)
		.join('/')
	return `import { IMG_URL } from '${rel.startsWith('.') ? rel : './' + rel}'`
}

function hasImgUrlInData(js) {
	return /data\s*:\s*\{[\s\S]*?\bIMG_URL\b/.test(js)
}

function inject(jsPath) {
	let js = fs.readFileSync(jsPath, 'utf8')
	if (hasImgUrlInData(js)) {
		if (!js.includes('imageBase.js')) {
			// already has IMG_URL from local const — ok if in data
			return false
		}
		return false
	}

	const importLine = importLineFor(jsPath)
	if (!js.includes('imageBase.js')) {
		js = `${importLine}\n${js}`
	}

	if (/data\s*:\s*\{/.test(js)) {
		js = js.replace(/data\s*:\s*\{/, 'data: {\n    IMG_URL,')
	} else {
		// Component({ ... }) without data
		const m = js.match(/Component\s*\(\s*\{/)
		if (m) {
			js = js.replace(
				/Component\s*\(\s*\{/,
				'Component({\n  data: {\n    IMG_URL,\n  },'
			)
		} else {
			console.warn('no data block:', path.relative(root, jsPath))
			return false
		}
	}

	fs.writeFileSync(jsPath, js)
	return true
}

let changed = 0
const missing = []
for (const wxml of walk(root)) {
	const content = fs.readFileSync(wxml, 'utf8')
	if (!/\{\{\s*IMG_URL\s*\}\}/.test(content)) continue
	const jsPath = resolveJs(wxml)
	if (!jsPath) {
		missing.push(path.relative(root, wxml))
		continue
	}
	if (inject(jsPath)) {
		changed++
		console.log(path.relative(root, jsPath))
	}
}

console.log('changed:', changed)
if (missing.length) console.log('missing js:', missing.join('\n'))