-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathafter-generate.js
More file actions
66 lines (55 loc) · 2.48 KB
/
after-generate.js
File metadata and controls
66 lines (55 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
const fs = require("fs");
const path = require("path");
// after-generate.js
//
// re-writes all exampleInfo.tsx files to replace const exampleImage = "my-image.jpg"
// with import exampleImage from "./my-image.jpg"
//
// Performs the inverse operation to before-generate.js
const getFilesInDirectory = async (pathUrl) => {
const entries = await fs.promises.readdir(pathUrl, { withFileTypes: true });
// Get files within the current directory and add a path key to the file objects
const files = entries
.filter((file) => !file.isDirectory())
.map((file) => ({
fileName: file.name,
fileDir: pathUrl,
filePath: path.join(pathUrl, file.name),
}));
// Get folders within the current directory
const folders = entries.filter((folder) => folder.isDirectory());
// Add the found files within the subdirectory to the files array
for (const folder of folders) files.push(...(await getFilesInDirectory(path.join(pathUrl, folder.name))));
return files;
};
function writeFile(targetFileName, fileText, platform) {
if (!["win32", "darwin"].includes(platform)) {
throw Error(`Platform ${platform} is not supported. Please run this script on Windows or macOS`);
}
fs.writeFileSync(targetFileName, fileText);
}
function replaceImportWithConst(targetFileName, exampleInfoText, platform) {
if (!["win32", "darwin"].includes(platform)) {
throw Error(`Platform ${platform} is not supported. Please run this script on Windows or macOS`);
}
console.log(`after-generate: Reverting file ${targetFileName}`);
exampleInfoText = exampleInfoText.replace("const exampleImage = \"", "import exampleImage from \"./");
writeFile(targetFileName, exampleInfoText, platform);
}
(async function () {
const examplesPath = path.join(__dirname, "src", "components", "Examples");
const files = await getFilesInDirectory(examplesPath);
const exampleDefinitionFiles = files.filter((f) => f.fileName === "exampleInfo.tsx");
const platform = process.platform;
// Iterate through all exampleInfo.tsx.
// Replace
// "const exampleImage = "someimage.jpg"
// with
// "import exampleImage from "./someimage.jpg";
exampleDefinitionFiles.forEach((f) => {
// Read the file and store this for later
const exampleInfoText = fs.readFileSync(f.filePath, "utf-8");
// Update the file and save
replaceImportWithConst(f.filePath, exampleInfoText, platform);
});
})();