ReactHotLoaderTransformer.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import {IdentifierRole, isTopLevelDeclaration} from "../parser/tokenizer";
  2. import Transformer from "./Transformer";
  3. export default class ReactHotLoaderTransformer extends Transformer {
  4. __init() {this.extractedDefaultExportName = null}
  5. constructor( tokens, filePath) {
  6. super();this.tokens = tokens;this.filePath = filePath;ReactHotLoaderTransformer.prototype.__init.call(this);;
  7. }
  8. setExtractedDefaultExportName(extractedDefaultExportName) {
  9. this.extractedDefaultExportName = extractedDefaultExportName;
  10. }
  11. getPrefixCode() {
  12. return `
  13. (function () {
  14. var enterModule = require('react-hot-loader').enterModule;
  15. enterModule && enterModule(module);
  16. })();`
  17. .replace(/\s+/g, " ")
  18. .trim();
  19. }
  20. getSuffixCode() {
  21. const topLevelNames = new Set();
  22. for (const token of this.tokens.tokens) {
  23. if (
  24. !token.isType &&
  25. isTopLevelDeclaration(token) &&
  26. token.identifierRole !== IdentifierRole.ImportDeclaration
  27. ) {
  28. topLevelNames.add(this.tokens.identifierNameForToken(token));
  29. }
  30. }
  31. const namesToRegister = Array.from(topLevelNames).map((name) => ({
  32. variableName: name,
  33. uniqueLocalName: name,
  34. }));
  35. if (this.extractedDefaultExportName) {
  36. namesToRegister.push({
  37. variableName: this.extractedDefaultExportName,
  38. uniqueLocalName: "default",
  39. });
  40. }
  41. return `
  42. ;(function () {
  43. var reactHotLoader = require('react-hot-loader').default;
  44. var leaveModule = require('react-hot-loader').leaveModule;
  45. if (!reactHotLoader) {
  46. return;
  47. }
  48. ${namesToRegister
  49. .map(
  50. ({variableName, uniqueLocalName}) =>
  51. ` reactHotLoader.register(${variableName}, "${uniqueLocalName}", ${JSON.stringify(
  52. this.filePath || "",
  53. )});`,
  54. )
  55. .join("\n")}
  56. leaveModule(module);
  57. })();`;
  58. }
  59. process() {
  60. return false;
  61. }
  62. }