RefreshRuntimeModule.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
  2. const RuntimeModule = require('webpack/lib/RuntimeModule');
  3. const Template = require('webpack/lib/Template');
  4. const { refreshGlobal } = require('../globals');
  5. const getRefreshGlobal = require('../utils/getRefreshGlobal');
  6. class ReactRefreshRuntimeModule extends RuntimeModule {
  7. constructor() {
  8. // Second argument is the `stage` for this runtime module -
  9. // we'll use the same stage as Webpack's HMR runtime module for safety.
  10. super('react refresh', 5);
  11. }
  12. /**
  13. * @returns {string} runtime code
  14. */
  15. generate() {
  16. const { runtimeTemplate } = this.compilation;
  17. return Template.asString([
  18. `${RuntimeGlobals.interceptModuleExecution}.push(${runtimeTemplate.basicFunction('options', [
  19. `${runtimeTemplate.supportsConst() ? 'const' : 'var'} originalFactory = options.factory;`,
  20. `options.factory = ${runtimeTemplate.basicFunction(
  21. 'moduleObject, moduleExports, webpackRequire',
  22. [
  23. `${refreshGlobal}.init();`,
  24. 'try {',
  25. Template.indent(
  26. 'originalFactory.call(this, moduleObject, moduleExports, webpackRequire);'
  27. ),
  28. '} finally {',
  29. Template.indent(`${refreshGlobal}.cleanup(options.id);`),
  30. '}',
  31. ]
  32. )}`,
  33. ])})`,
  34. '',
  35. getRefreshGlobal(runtimeTemplate),
  36. ]);
  37. }
  38. }
  39. module.exports = ReactRefreshRuntimeModule;