migrate-root-images-cdn.mjs 1.81 KB
/**
 * One-off: migrate /images/ in wxml to {{ IMG_URL }}images/
 * Run: node scripts/migrate-root-images-cdn.mjs
 */
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
}

const relativeRootPaths = new Map([
	[
		path.join(root, 'components/navigationBar/navigationBar.wxml'),
		['../../images/back.png', '{{ IMG_URL }}images/back.png'],
	],
	[
		path.join(root, 'components/SearchInput/SearchInput.wxml'),
		['../../images/search.png', '{{ IMG_URL }}images/search.png'],
	],
	[
		path.join(root, 'pages/accountItems/accountItems.wxml'),
		['../../images/search.png', '{{ IMG_URL }}images/search.png'],
	],
	[
		path.join(root, 'pages/merchantList/merchantList.wxml'),
		['../../images/search.png', '{{ IMG_URL }}images/search.png'],
	],
])

let wxmlChanged = 0
for (const file of walk(root)) {
	let content = fs.readFileSync(file, 'utf8')
	const before = content
	content = content.replace(/src="\/images\//g, 'src="{{ IMG_URL }}images/')
	content = content.replace(/src='\/images\//g, "src='{{ IMG_URL }}images/")
	content = content.replace(/left-icon="\/images\//g, 'left-icon="{{ IMG_URL }}images/')
	const rel = relativeRootPaths.get(file)
	if (rel) {
		for (const [from, to] of rel) {
			content = content.split(from).join(to)
		}
	}
	if (content !== before) {
		fs.writeFileSync(file, content)
		wxmlChanged++
		console.log('wxml:', path.relative(root, file))
	}
}

console.log('wxml files changed:', wxmlChanged)