index.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. // 修改自https://github.com/kryops/rollup-plugin-gzip
  2. // 因为rollup-plugin-gzip不支持vite
  3. // vite对css打包独立的。所以不能在打包的时候顺带打包css
  4. import { readFile, writeFile } from 'fs';
  5. import { basename } from 'path';
  6. import { promisify } from 'util';
  7. import { gzip } from 'zlib';
  8. import { OutputAsset, OutputChunk, OutputOptions, Plugin } from 'rollup';
  9. import { GzipPluginOptions } from './types';
  10. const isFunction = (arg: unknown): arg is (...args: any[]) => any => typeof arg === 'function';
  11. const isRegExp = (arg: unknown): arg is RegExp =>
  12. Object.prototype.toString.call(arg) === '[object RegExp]';
  13. export type StringMappingOption = (originalString: string) => string;
  14. export type CustomCompressionOption = (
  15. content: string | Buffer
  16. ) => string | Buffer | Promise<string | Buffer>;
  17. const readFilePromise = promisify(readFile);
  18. const writeFilePromise = promisify(writeFile);
  19. // functionality partially copied from rollup
  20. /**
  21. * copied from https://github.com/rollup/rollup/blob/master/src/rollup/index.ts#L450
  22. */
  23. function isOutputChunk(file: OutputAsset | OutputChunk): file is OutputChunk {
  24. return typeof (file as OutputChunk).code === 'string';
  25. }
  26. /**
  27. * Gets the string/buffer content from a file object.
  28. * Important for adding source map comments
  29. *
  30. * Copied partially from rollup.writeOutputFile
  31. * https://github.com/rollup/rollup/blob/master/src/rollup/index.ts#L454
  32. */
  33. function getOutputFileContent(
  34. outputFileName: string,
  35. outputFile: OutputAsset | OutputChunk,
  36. outputOptions: OutputOptions
  37. ): string | Buffer {
  38. if (isOutputChunk(outputFile)) {
  39. let source: string | Buffer;
  40. source = outputFile.code;
  41. if (outputOptions.sourcemap && outputFile.map) {
  42. const url =
  43. outputOptions.sourcemap === 'inline'
  44. ? outputFile.map.toUrl()
  45. : `${basename(outputFileName)}.map`;
  46. // https://github.com/rollup/rollup/blob/master/src/utils/sourceMappingURL.ts#L1
  47. source += `//# source` + `MappingURL=${url}\n`;
  48. }
  49. return source;
  50. } else {
  51. return typeof outputFile.source === 'string'
  52. ? outputFile.source
  53. : // just to be sure, as it is typed string | Uint8Array in rollup 2.0.0
  54. Buffer.from(outputFile.source);
  55. }
  56. }
  57. // actual plugin code
  58. function gzipPlugin(options: GzipPluginOptions = {}): Plugin {
  59. // check for old options
  60. if ('algorithm' in options) {
  61. console.warn(
  62. '[rollup-plugin-gzip] The "algorithm" option is not supported any more! ' +
  63. 'Use "customCompression" instead to specify a different compression algorithm.'
  64. );
  65. }
  66. if ('options' in options) {
  67. console.warn('[rollup-plugin-gzip] The "options" option was renamed to "gzipOptions"!');
  68. }
  69. if ('additional' in options) {
  70. console.warn('[rollup-plugin-gzip] The "additional" option was renamed to "additionalFiles"!');
  71. }
  72. if ('delay' in options) {
  73. console.warn('[rollup-plugin-gzip] The "delay" option was renamed to "additionalFilesDelay"!');
  74. }
  75. const compressGzip: CustomCompressionOption = (fileContent) => {
  76. return new Promise((resolve, reject) => {
  77. gzip(fileContent, options.gzipOptions || {}, (err, result) => {
  78. if (err) {
  79. reject(err);
  80. } else {
  81. resolve(result);
  82. }
  83. });
  84. });
  85. };
  86. const doCompress = options.customCompression || compressGzip;
  87. const mapFileName: StringMappingOption = isFunction(options.fileName)
  88. ? (options.fileName as StringMappingOption)
  89. : (fileName: string) => fileName + (options.fileName || '.gz');
  90. const plugin: Plugin = {
  91. name: 'gzip',
  92. generateBundle(outputOptions, bundle) {
  93. return Promise.all(
  94. Object.keys(bundle)
  95. .map((fileName) => {
  96. const fileEntry = bundle[fileName];
  97. // file name filter option check
  98. const fileNameFilter = options.filter || /\.(js|mjs|json|css|html)$/;
  99. if (isRegExp(fileNameFilter) && !fileName.match(fileNameFilter)) {
  100. return Promise.resolve();
  101. }
  102. if (
  103. isFunction(fileNameFilter) &&
  104. !(fileNameFilter as (x: string) => boolean)(fileName)
  105. ) {
  106. return Promise.resolve();
  107. }
  108. const fileContent = getOutputFileContent(fileName, fileEntry, outputOptions);
  109. // minSize option check
  110. if (options.minSize && options.minSize > fileContent.length) {
  111. return Promise.resolve();
  112. }
  113. return Promise.resolve(doCompress(fileContent))
  114. .then((compressedContent) => {
  115. const compressedFileName = mapFileName(fileName);
  116. bundle[compressedFileName] = {
  117. type: 'asset', // Rollup >= 1.21
  118. name: compressedFileName,
  119. fileName: compressedFileName,
  120. isAsset: true, // Rollup < 1.21
  121. source: compressedContent,
  122. };
  123. })
  124. .catch((err: any) => {
  125. console.error(err);
  126. return Promise.reject('[rollup-plugin-gzip] Error compressing file ' + fileName);
  127. });
  128. })
  129. .concat([
  130. (() => {
  131. if (!options.additionalFiles || !options.additionalFiles.length)
  132. return Promise.resolve();
  133. const compressAdditionalFiles = () =>
  134. Promise.all(
  135. options.additionalFiles!.map((filePath) =>
  136. readFilePromise(filePath)
  137. .then((fileContent) => doCompress(fileContent))
  138. .then((compressedContent) => {
  139. return writeFilePromise(mapFileName(filePath), compressedContent);
  140. })
  141. .catch(() => {
  142. return Promise.reject(
  143. '[rollup-plugin-gzip] Error compressing additional file ' +
  144. filePath +
  145. '. Please check the spelling of your configured additionalFiles. ' +
  146. 'You might also have to increase the value of the additionalFilesDelay option.'
  147. );
  148. })
  149. )
  150. ) as Promise<any>;
  151. // additional files can be processed outside of rollup after a delay
  152. // for older plugins or plugins that write to disk (curcumventing rollup) without awaiting
  153. const additionalFilesDelay = options.additionalFilesDelay || 0;
  154. if (additionalFilesDelay) {
  155. setTimeout(compressAdditionalFiles, additionalFilesDelay);
  156. return Promise.resolve();
  157. } else {
  158. return compressAdditionalFiles();
  159. }
  160. })(),
  161. ])
  162. ) as Promise<any>;
  163. },
  164. };
  165. return plugin;
  166. }
  167. export default gzipPlugin;