copy-file-plugin.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _fs = require("fs");
  6. var _loaderUtils3 = _interopRequireDefault(require("next/dist/compiled/loader-utils3"));
  7. var _webpack = require("next/dist/compiled/webpack/webpack");
  8. function _interopRequireDefault(obj) {
  9. return obj && obj.__esModule ? obj : {
  10. default: obj
  11. };
  12. }
  13. const PLUGIN_NAME = "CopyFilePlugin";
  14. class CopyFilePlugin {
  15. constructor({ filePath , cacheKey , name , info }){
  16. this.filePath = filePath;
  17. this.cacheKey = cacheKey;
  18. this.name = name;
  19. this.info = info;
  20. }
  21. apply(compiler) {
  22. compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation)=>{
  23. const cache = compilation.getCache("CopyFilePlugin");
  24. const hook = compilation.hooks.processAssets;
  25. hook.tapPromise({
  26. name: PLUGIN_NAME,
  27. // @ts-ignore TODO: Remove ignore when webpack 5 is stable
  28. stage: _webpack.webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONS
  29. }, async ()=>{
  30. if (cache) {
  31. const cachedResult = await cache.getPromise(this.filePath, this.cacheKey);
  32. if (cachedResult) {
  33. const { file , source } = cachedResult;
  34. compilation.emitAsset(file, source, {
  35. ...this.info
  36. });
  37. return;
  38. }
  39. }
  40. const content = await _fs.promises.readFile(this.filePath, "utf8");
  41. const file = _loaderUtils3.default.interpolateName({
  42. resourcePath: this.filePath
  43. }, this.name, {
  44. content,
  45. context: compiler.context
  46. });
  47. const source = new _webpack.sources.RawSource(content);
  48. if (cache) {
  49. await cache.storePromise(this.filePath, this.cacheKey, {
  50. file,
  51. source
  52. });
  53. }
  54. // @ts-ignore
  55. compilation.emitAsset(file, source, {
  56. ...this.info
  57. });
  58. });
  59. });
  60. }
  61. }
  62. exports.CopyFilePlugin = CopyFilePlugin;
  63. //# sourceMappingURL=copy-file-plugin.js.map