publish-preview.mjs 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. import {
  2. cpSync,
  3. existsSync,
  4. mkdirSync,
  5. readdirSync,
  6. readFileSync,
  7. renameSync,
  8. writeFileSync,
  9. rmSync,
  10. } from 'node:fs';
  11. import { fileURLToPath } from 'node:url';
  12. const source = new URL('../dist/build/h5/', import.meta.url);
  13. const destination = new URL('../../server/public/water-mini/', import.meta.url);
  14. if (!existsSync(new URL('index.html', source)))
  15. throw new Error('Run npm run build:h5 before publishing the local preview.');
  16. mkdirSync(fileURLToPath(destination), { recursive: true });
  17. // Publish assets before switching HTML; keep previous hashed assets for already-open pages.
  18. const html = readFileSync(new URL('index.html', source), 'utf8');
  19. for (const match of html.matchAll(/(?:src|href)="(\/water-mini\/[^"?#]+)"/g)) {
  20. const relative = match[1].slice('/water-mini/'.length);
  21. if (!existsSync(new URL(relative, source))) throw new Error('Missing build asset: ' + relative);
  22. }
  23. for (const entry of readdirSync(source)) {
  24. if (entry !== 'index.html')
  25. cpSync(new URL(entry, source), new URL(entry, destination), { recursive: true });
  26. }
  27. const temporaryIndex = new URL('index.html.' + process.pid + '.tmp', destination);
  28. try {
  29. writeFileSync(temporaryIndex, html);
  30. renameSync(temporaryIndex, new URL('index.html', destination));
  31. } finally {
  32. rmSync(temporaryIndex, { force: true });
  33. }
  34. console.log('Local preview: http://127.0.0.1:8787/water-mini/index.html');