nomadro/apps/miniprogram/tt/scripts/copy-static.mjs
2026-09-30 15:58:57 +08:00

105 lines
2.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Taro copy.patterns 偶发不落盘;构建后强制把 icons / assets 拷进 dist。
*/
import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'
import { spawnSync } from 'child_process'
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const out = 'dist'
function rmrf(p) {
if (!fs.existsSync(p)) return
fs.rmSync(p, { recursive: true, force: true })
}
function copyDir(from, to, { wipe = false } = {}) {
if (!fs.existsSync(from)) {
console.warn(`[copy-static] skip missing: ${from}`)
return 0
}
if (wipe) rmrf(to)
fs.mkdirSync(to, { recursive: true })
let n = 0
for (const name of fs.readdirSync(from)) {
const src = path.join(from, name)
const dest = path.join(to, name)
const st = fs.statSync(src)
if (st.isDirectory()) n += copyDir(src, dest)
else {
fs.copyFileSync(src, dest)
n += 1
}
}
return n
}
function stripMaps(dir) {
if (!fs.existsSync(dir)) return 0
let n = 0
for (const name of fs.readdirSync(dir)) {
const p = path.join(dir, name)
const st = fs.statSync(p)
if (st.isDirectory()) n += stripMaps(p)
else if (name.endsWith('.map')) {
fs.unlinkSync(p)
n += 1
}
}
return n
}
/** 真机兼容:webp → png(保留原 webp) */
function convertIconsWebpToPng(iconsDir) {
if (!fs.existsSync(iconsDir)) return 0
const py = `
from pathlib import Path
try:
from PIL import Image
except ImportError:
raise SystemExit(2)
root = Path(r'''${iconsDir.replace(/\\/g, '/')}''')
n = 0
for src in root.glob('*.webp'):
dst = src.with_suffix('.png')
im = Image.open(src)
if im.mode not in ('RGB', 'RGBA'):
im = im.convert('RGBA')
im.save(dst, format='PNG', optimize=True)
n += 1
print(n)
`
const r = spawnSync('python', ['-c', py], { encoding: 'utf8' })
if (r.status === 2) {
console.warn('[copy-static] Pillow missing — skip webp→png')
return 0
}
if (r.status !== 0) {
console.warn('[copy-static] webp→png failed:', r.stderr || r.stdout)
return 0
}
return Number((r.stdout || '').trim()) || 0
}
const icons = copyDir(
path.join(root, 'src/public/icons'),
path.join(root, out, 'icons'),
{ wipe: true },
)
const pngs = convertIconsWebpToPng(path.join(root, out, 'icons'))
const assets = copyDir(
path.join(root, 'src/assets'),
path.join(root, out, 'assets'),
{ wipe: true },
)
const bookImgs = copyDir(
path.join(root, 'src/packageBook/assets/book-images'),
path.join(root, out, 'packageBook/assets/book-images'),
{ wipe: true },
)
const maps = stripMaps(path.join(root, out))
console.log(
`[copy-static] ${out}: icons=${icons} png=${pngs} assets=${assets} bookImgs=${bookImgs} mapsRemoved=${maps}`,
)