sync-manifest-plugins.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import type { Plugin } from 'vite'
  2. import fs from 'fs'
  3. import path from 'path'
  4. interface ManifestType {
  5. plus?: {
  6. distribute?: {
  7. plugins?: Record<string, any>
  8. }
  9. }
  10. 'app-plus'?: {
  11. distribute?: {
  12. plugins?: Record<string, any>
  13. }
  14. }
  15. }
  16. export default function syncManifestPlugin(): Plugin {
  17. return {
  18. name: 'sync-manifest',
  19. apply: 'build',
  20. enforce: 'post',
  21. writeBundle: {
  22. order: 'post',
  23. handler() {
  24. const srcManifestPath = path.resolve(process.cwd(), './src/manifest.json')
  25. const distAppPath = path.resolve(process.cwd(), './dist/dev/app/manifest.json')
  26. try {
  27. // 读取源文件
  28. const srcManifest = JSON.parse(fs.readFileSync(srcManifestPath, 'utf8')) as ManifestType
  29. // 确保目标目录存在
  30. const distAppDir = path.dirname(distAppPath)
  31. if (!fs.existsSync(distAppDir)) {
  32. fs.mkdirSync(distAppDir, { recursive: true })
  33. }
  34. // 读取目标文件(如果存在)
  35. let distManifest: ManifestType = {}
  36. if (fs.existsSync(distAppPath)) {
  37. distManifest = JSON.parse(fs.readFileSync(distAppPath, 'utf8'))
  38. }
  39. // 如果源文件存在 plugins
  40. if (srcManifest['app-plus']?.distribute?.plugins) {
  41. // 确保目标文件中有必要的对象结构
  42. if (!distManifest.plus) distManifest.plus = {}
  43. if (!distManifest.plus.distribute) distManifest.plus.distribute = {}
  44. // 复制 plugins 内容
  45. distManifest.plus.distribute.plugins = srcManifest['app-plus'].distribute.plugins
  46. // 写入更新后的内容
  47. fs.writeFileSync(distAppPath, JSON.stringify(distManifest, null, 2))
  48. console.log('✅ Manifest plugins 同步成功')
  49. }
  50. } catch (error) {
  51. console.error('❌ 同步 manifest plugins 失败:', error)
  52. }
  53. },
  54. },
  55. }
  56. }