74 lines
2.2 KiB
JavaScript
74 lines
2.2 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 将静态资源复制到 dist/,便于直接部署到任意静态主机。
|
||
* 产出: dist/index.html, dist/config.json, dist/lib/, dist/image/
|
||
* 构建时注入 __CACHE_VERSION__ 为时间戳,用于防微信/浏览器强缓存,保证发版后页面可更新。
|
||
*/
|
||
const fs = require('fs');
|
||
const path = require('path');
|
||
|
||
const ROOT = path.resolve(__dirname);
|
||
const DIST = path.join(ROOT, 'dist');
|
||
|
||
function copyFile(src, dest) {
|
||
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
||
fs.copyFileSync(src, dest);
|
||
}
|
||
|
||
function copyDir(srcDir, destDir) {
|
||
if (!fs.existsSync(srcDir)) return;
|
||
fs.mkdirSync(destDir, { recursive: true });
|
||
for (const name of fs.readdirSync(srcDir)) {
|
||
const s = path.join(srcDir, name);
|
||
const d = path.join(destDir, name);
|
||
if (fs.statSync(s).isDirectory()) copyDir(s, d);
|
||
else copyFile(s, d);
|
||
}
|
||
}
|
||
|
||
/** 清空目录内容(不删目录本身),避免 EPERM(如宝塔 wwwroot 下 dist 无法 rmSync) */
|
||
function emptyDir(dir) {
|
||
if (!fs.existsSync(dir)) return;
|
||
for (const name of fs.readdirSync(dir)) {
|
||
const p = path.join(dir, name);
|
||
try {
|
||
if (fs.statSync(p).isDirectory()) {
|
||
fs.rmSync(p, { recursive: true });
|
||
} else {
|
||
fs.unlinkSync(p);
|
||
}
|
||
} catch (e) {
|
||
if (e.code !== 'EPERM' && e.code !== 'EACCES') throw e;
|
||
}
|
||
}
|
||
}
|
||
|
||
function main() {
|
||
if (fs.existsSync(DIST)) {
|
||
try {
|
||
fs.rmSync(DIST, { recursive: true });
|
||
} catch (e) {
|
||
if (e.code === 'EPERM' || e.code === 'EACCES') {
|
||
emptyDir(DIST);
|
||
} else {
|
||
throw e;
|
||
}
|
||
}
|
||
}
|
||
fs.mkdirSync(DIST, { recursive: true });
|
||
|
||
const cacheVersion = String(Date.now());
|
||
let indexHtml = fs.readFileSync(path.join(ROOT, 'index.html'), 'utf8');
|
||
indexHtml = indexHtml.replace(/__CACHE_VERSION__/g, cacheVersion);
|
||
fs.writeFileSync(path.join(DIST, 'index.html'), indexHtml, 'utf8');
|
||
|
||
copyFile(path.join(ROOT, 'config.json'), path.join(DIST, 'config.json'));
|
||
copyFile(path.join(ROOT, 'api.config.json'), path.join(DIST, 'api.config.json'));
|
||
copyDir(path.join(ROOT, 'lib'), path.join(DIST, 'lib'));
|
||
copyDir(path.join(ROOT, 'image'), path.join(DIST, 'image'));
|
||
|
||
console.log('已构建到 dist/(前端静态),可直接部署。');
|
||
}
|
||
|
||
main();
|