Skip to content

Commit 21f6bf5

Browse files
committed
wip: collect inline require statements and convert them to top level imports
1 parent 2b84f8a commit 21f6bf5

File tree

1 file changed

+43
-9
lines changed

1 file changed

+43
-9
lines changed

src/formatGeneratedModule.ts

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,36 @@ import { FormatModule } from "relay-compiler";
22
import * as ts from "typescript";
33
import addAnyTypeCast from "./addAnyTypeCast";
44

5+
const createRequireRegex = () => /require\("(.*)"\)/g;
6+
const escapeRegexString = (str: string) =>
7+
str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&");
8+
9+
// collects all require calls and converts them to top level imports
10+
const requireToImport = (content: string) => {
11+
const requirePaths = new Set<string>();
12+
const regex = createRequireRegex();
13+
let result: null | RegExpExecArray = null;
14+
while (true) {
15+
result = regex.exec(content);
16+
if (result === null) {
17+
break;
18+
}
19+
requirePaths.add(result[1]);
20+
}
21+
22+
for (const requirePath of requirePaths) {
23+
const [baseName] = requirePath.replace("./", "").split(".");
24+
content =
25+
`import ${baseName} from "${requirePath.replace(".ts", "")}";\n` +
26+
content.replace(
27+
new RegExp(escapeRegexString(`require('${requirePath}')`), "g"),
28+
baseName
29+
);
30+
}
31+
32+
return content;
33+
};
34+
535
export const formatterFactory = (
636
compilerOptions: ts.CompilerOptions = {}
737
): FormatModule => ({
@@ -11,27 +41,31 @@ export const formatterFactory = (
1141
concreteText,
1242
typeText,
1343
hash,
14-
sourceHash
44+
sourceHash,
1545
}) => {
1646
const documentTypeImport = documentType
1747
? `import { ${documentType} } from "relay-runtime";`
1848
: "";
1949
const docTextComment = docText ? "\n/*\n" + docText.trim() + "\n*/\n" : "";
20-
let nodeStatement = `const node: ${documentType ||
21-
"never"} = ${concreteText};`;
50+
let nodeStatement = `const node: ${
51+
documentType || "never"
52+
} = ${concreteText};`;
2253
if (compilerOptions.noImplicitAny) {
2354
nodeStatement = addAnyTypeCast(nodeStatement).trim();
2455
}
25-
return `/* tslint:disable */
26-
/* eslint-disable */
27-
// @ts-nocheck
28-
${hash ? `/* ${hash} */\n` : ""}
29-
${documentTypeImport}
30-
${typeText || ""}
56+
const rawContent = `${typeText || ""}
3157
3258
${docTextComment}
3359
${nodeStatement}
3460
(node as any).hash = '${sourceHash}';
3561
export default node;
3662
`;
63+
64+
const content = `/* tslint:disable */
65+
/* eslint-disable */
66+
// @ts-nocheck
67+
${hash ? `/* ${hash} */\n` : ""}
68+
${documentTypeImport}
69+
${requireToImport(rawContent)}`;
70+
return content;
3771
};

0 commit comments

Comments
 (0)