migrate-root-images-cdn.mjs
1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
* 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)