sync-manifest-plugins.ts 2.0 KB

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