50 lines
2.1 KiB
JavaScript
50 lines
2.1 KiB
JavaScript
/**
|
|
* 将「当前选用的静态基址」写入 pages.json、index.html。
|
|
* - 目标基址:`STATIC_ASSETS_BASE_URL` 环境变量,否则取 `static-assets-defaults.js` 中 **STATIC_ASSETS_BASE_URL_TEST**。
|
|
* - 若文件中仍是更旧的 CDN 前缀,可一次性指定 `PREV_STATIC_ASSETS_BASE_URL`(要整段替换掉的前缀,须以 / 结尾),例如:
|
|
* `PREV_STATIC_ASSETS_BASE_URL=https://old-host/sqxp-static/ npm run sync-static-public-urls`
|
|
* 不设则仅把「与目标相同」视为已就绪,不做无意义的替换。
|
|
*
|
|
* 生产发版:先设 `STATIC_ASSETS_BASE_URL` 为生产根地址再执行。
|
|
* 用法:在 sqxp-wx 根目录执行 `npm run sync-static-public-urls`
|
|
*/
|
|
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
import { fileURLToPath } from 'node:url'
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
|
const root = path.resolve(__dirname, '..')
|
|
const defaultsPath = path.join(root, 'config/static-assets-defaults.js')
|
|
const raw = fs.readFileSync(defaultsPath, 'utf8')
|
|
const pick = (name) => {
|
|
const m = raw.match(new RegExp(`export const ${name}\\s*=\\s*['"]([^'"]+)['"]`))
|
|
return m?.[1]?.trim() || ''
|
|
}
|
|
const testBase = pick('STATIC_ASSETS_BASE_URL_TEST') || pick('STATIC_ASSETS_BASE_URL_DEFAULT')
|
|
const fromFile = testBase || process.env.VITE_STATIC_ASSETS_BASE_URL || 'https://REPLACE_TEST_STATIC_HOST/shanxia-static/'
|
|
const normalized = (() => {
|
|
const b = (process.env.STATIC_ASSETS_BASE_URL || fromFile).trim()
|
|
return b.endsWith('/') ? b : `${b}/`
|
|
})()
|
|
|
|
const prevRaw = process.env.PREV_STATIC_ASSETS_BASE_URL?.trim()
|
|
const prev = prevRaw
|
|
? prevRaw.endsWith('/') ? prevRaw : `${prevRaw}/`
|
|
: normalized
|
|
|
|
for (const rel of ['pages.json', 'index.html']) {
|
|
const p = path.join(root, rel)
|
|
if (!fs.existsSync(p)) continue
|
|
let s = fs.readFileSync(p, 'utf8')
|
|
if (prev !== normalized) {
|
|
s = s.split(prev).join(normalized)
|
|
}
|
|
fs.writeFileSync(p, s)
|
|
}
|
|
|
|
if (prev === normalized) {
|
|
console.log('Static base:', normalized, '(未设置 PREV_STATIC_ASSETS_BASE_URL,未执行旧前缀替换)')
|
|
} else {
|
|
console.log('Static base set to:', normalized, '(replaced prefix:', prev + ')')
|
|
}
|