-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
executable file
·146 lines (127 loc) · 3.73 KB
/
script.js
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#! /usr/bin/env node
const fs = require('fs');
const path = require('path');
const isProd = process.env.NODE_ENV === 'production';
const { exportPathMap } = require(path.resolve(process.cwd(), 'next.config'));
const fileExtension = process.env.STATIC_EXTENSION || 'js';
const reuseData = process.env.STATIC_REUSE_DATA || 0;
// Settings
const DATA_DIRECTORY = './data';
const TMP_PAGES = 'TMP_PAGES';
async function createEmptyDir() {
// Create directory if it doesn't exist
if (!fs.existsSync(DATA_DIRECTORY)) {
fs.mkdirSync(DATA_DIRECTORY);
} else {
if (!reuseData) {
// remove files from directory
fs.readdir(DATA_DIRECTORY, (err, files) => {
if (err) throw err;
for (const file of files) {
fs.unlink(path.join(DATA_DIRECTORY, file), err => {
if (err) throw err;
});
}
});
}
}
}
function replaceRequirePath(filename, newRequirePath) {
return new Promise((res, rej) => {
fs.readFile(filename, 'utf8', function(err, data) {
if (err) {
rej(err);
}
var result = data.replace(
/(withAPI\([^,]*,[^,]*,)([^\)]*)(\))/gm,
`$1 '${newRequirePath}'$3`
);
fs.writeFile(filename, result, 'utf8', function(err) {
if (err) rej(err);
res(true);
});
});
});
}
function copyToPath(fileToCopy, newFilePath) {
// Create directory if it doesn't exist
if (fs.existsSync(fileToCopy)) {
return new Promise((res, rej) => {
fs.copyFile(fileToCopy, newFilePath, err => {
if (err) rej(err);
res(true);
});
});
}
return false;
}
async function exportData() {
// prep dorectory
await createEmptyDir();
// pages to delete after
const tmpPages = [];
//paths
const exportPaths = await exportPathMap();
const staticPaths = Object.keys(exportPaths).filter(
path => 'static' in exportPaths[path]
);
for (const path of staticPaths) {
console.log(`Static compilation of ${path}`)
const { static, page, query } = exportPaths[path];
const { filename, getInitialProps } = static;
// If the path doesn't exist temporarily create it by copying the page
if (path !== `/` && !fs.existsSync(`pages${path}.${fileExtension}`)) {
const pageToCopy = page === '/' ? 'pages/index.${fileExtension}' : `pages${page}.${fileExtension}`;
const newPath = `pages${path}.${fileExtension}`;
const success = await copyToPath(pageToCopy, newPath);
// add it to tmp pages
if (success) {
tmpPages.push(newPath);
// augment the property passed to withAPI with the filename to be
await replaceRequirePath(newPath, filename);
}
}
if (process.env.STATIC_EXPORT_DATA && !reuseData) {
const data = await getInitialProps({ query });
fs.writeFileSync(
`${DATA_DIRECTORY}/${filename}.json`,
JSON.stringify(data)
);
}
}
// write tmpPages to a file so that export cleanup can delete them
fs.writeFileSync(
`${DATA_DIRECTORY}/${TMP_PAGES}.json`,
JSON.stringify(tmpPages)
);
}
function deleteFile(filepath) {
try {
fs.unlinkSync(filepath);
//file removed
} catch (err) {
console.error(err);
}
}
async function exportCleanup() {
if (fs.existsSync(`${DATA_DIRECTORY}/${TMP_PAGES}.json`)) {
// read tmp pages
const tmpPages = JSON.parse(
fs.readFileSync(`${DATA_DIRECTORY}/${TMP_PAGES}.json`, 'utf8')
);
// delete tmp pages
for (const tmpPagePath of tmpPages) {
deleteFile(tmpPagePath);
}
// delete the tmpp pages file
deleteFile(`${DATA_DIRECTORY}/${TMP_PAGES}.json`);
} else {
console.log('No cleanup file');
}
}
if (process.env.STATIC_EXPORT) {
exportData();
}
if (process.env.STATIC_CLEANUP) {
exportCleanup();
}