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