license.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import type {
  2. NormalizedOutputOptions,
  3. OutputBundle,
  4. OutputChunk,
  5. } from 'rollup';
  6. import type { PluginOption } from 'vite';
  7. import { EOL } from 'node:os';
  8. import { dateUtil, readPackageJSON } from '@vben/node-utils';
  9. /**
  10. * 用于注入版权信息
  11. * @returns
  12. */
  13. async function viteLicensePlugin(
  14. root = process.cwd(),
  15. ): Promise<PluginOption | undefined> {
  16. const {
  17. description = '',
  18. homepage = '',
  19. version = '',
  20. } = await readPackageJSON(root);
  21. return {
  22. apply: 'build',
  23. enforce: 'post',
  24. generateBundle: {
  25. handler: (_options: NormalizedOutputOptions, bundle: OutputBundle) => {
  26. const date = dateUtil().format('YYYY-MM-DD ');
  27. const copyrightText = `/*!
  28. * Vben Admin
  29. * Version: ${version}
  30. * Author: vben
  31. * Copyright (C) 2024 Vben
  32. * License: MIT License
  33. * Description: ${description}
  34. * Date Created: ${date}
  35. * Homepage: ${homepage}
  36. * Contact: ann.vben@gmail.com
  37. */
  38. `.trim();
  39. for (const [, fileContent] of Object.entries(bundle)) {
  40. if (fileContent.type === 'chunk' && fileContent.isEntry) {
  41. const chunkContent = fileContent as OutputChunk;
  42. // 插入版权信息
  43. const content = chunkContent.code;
  44. const updatedContent = `${copyrightText}${EOL}${content}`;
  45. // 更新bundle
  46. (fileContent as OutputChunk).code = updatedContent;
  47. }
  48. }
  49. },
  50. order: 'post',
  51. },
  52. name: 'vite:license',
  53. };
  54. }
  55. export { viteLicensePlugin };