license.ts 1.9 KB

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