inject-img-url.mjs
2.37 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* 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'))