-
Notifications
You must be signed in to change notification settings - Fork 26.7k
/
index.ts
349 lines (304 loc) · 9.38 KB
/
index.ts
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import chalk from 'chalk'
import { copyFile as copyFileOrig, existsSync, readFileSync } from 'fs'
import Worker from 'jest-worker'
import mkdirpModule from 'mkdirp'
import { cpus } from 'os'
import { dirname, join, resolve } from 'path'
import { promisify } from 'util'
import { AmpPageStatus, formatAmpMessages } from '../build/output/index'
import createSpinner from '../build/spinner'
import { API_ROUTE } from '../lib/constants'
import { recursiveCopy } from '../lib/recursive-copy'
import { recursiveDelete } from '../lib/recursive-delete'
import {
BUILD_ID_FILE,
CLIENT_PUBLIC_FILES_PATH,
CLIENT_STATIC_FILES_PATH,
CONFIG_FILE,
PAGES_MANIFEST,
PHASE_EXPORT,
PRERENDER_MANIFEST,
SERVER_DIRECTORY,
SERVERLESS_DIRECTORY,
} from '../next-server/lib/constants'
import loadConfig, {
isTargetLikeServerless,
} from '../next-server/server/config'
import { eventVersion } from '../telemetry/events'
import { Telemetry } from '../telemetry/storage'
const mkdirp = promisify(mkdirpModule)
const copyFile = promisify(copyFileOrig)
const createProgress = (total: number, label = 'Exporting') => {
let curProgress = 0
let progressSpinner = createSpinner(`${label} (${curProgress}/${total})`, {
spinner: {
frames: [
'[ ]',
'[= ]',
'[== ]',
'[=== ]',
'[ ===]',
'[ ==]',
'[ =]',
'[ ]',
'[ =]',
'[ ==]',
'[ ===]',
'[====]',
'[=== ]',
'[== ]',
'[= ]',
],
interval: 80,
},
})
return () => {
curProgress++
const newText = `${label} (${curProgress}/${total})`
if (progressSpinner) {
progressSpinner.text = newText
} else {
console.log(newText)
}
if (curProgress === total && progressSpinner) {
progressSpinner.stop()
console.log(newText)
}
}
}
type ExportPathMap = {
[page: string]: { page: string; query?: { [key: string]: string } }
}
export default async function(
dir: string,
options: any,
configuration?: any
): Promise<void> {
function log(message: string) {
if (options.silent) {
return
}
console.log(message)
}
dir = resolve(dir)
const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir)
const threads = options.threads || Math.max(cpus().length - 1, 1)
const distDir = join(dir, nextConfig.distDir)
if (!options.buildExport) {
const telemetry = new Telemetry({ distDir })
telemetry.record(eventVersion({ cliCommand: 'export', isSrcDir: null }))
}
const subFolders = nextConfig.exportTrailingSlash
const isLikeServerless = nextConfig.target !== 'server'
if (!options.buildExport && isLikeServerless) {
throw new Error(
'Cannot export when target is not server. https://err.sh/zeit/next.js/next-export-serverless'
)
}
log(`> using build directory: ${distDir}`)
if (!existsSync(distDir)) {
throw new Error(
`Build directory ${distDir} does not exist. Make sure you run "next build" before running "next start" or "next export".`
)
}
const buildId = readFileSync(join(distDir, BUILD_ID_FILE), 'utf8')
const pagesManifest =
!options.pages && require(join(distDir, SERVER_DIRECTORY, PAGES_MANIFEST))
let prerenderManifest
try {
prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
} catch (_) {}
const distPagesDir = join(
distDir,
isLikeServerless
? SERVERLESS_DIRECTORY
: join(SERVER_DIRECTORY, 'static', buildId),
'pages'
)
const pages = options.pages || Object.keys(pagesManifest)
const defaultPathMap: ExportPathMap = {}
for (const page of pages) {
// _document and _app are not real pages
// _error is exported as 404.html later on
// API Routes are Node.js functions
if (
page === '/_document' ||
page === '/_app' ||
page === '/_error' ||
page.match(API_ROUTE)
) {
continue
}
defaultPathMap[page] = { page }
}
// Initialize the output directory
const outDir = options.outdir
if (outDir === join(dir, 'public')) {
throw new Error(
`The 'public' directory is reserved in Next.js and can not be used as the export out directory. https://err.sh/zeit/next.js/can-not-output-to-public`
)
}
await recursiveDelete(join(outDir))
await mkdirp(join(outDir, '_next', buildId))
// Copy static directory
if (!options.buildExport && existsSync(join(dir, 'static'))) {
log(' copying "static" directory')
await recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
}
// Copy .next/static directory
if (existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))) {
log(' copying "static build" directory')
await recursiveCopy(
join(distDir, CLIENT_STATIC_FILES_PATH),
join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
)
}
// Get the exportPathMap from the config file
if (typeof nextConfig.exportPathMap !== 'function') {
console.log(
`> No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`
)
nextConfig.exportPathMap = async (defaultMap: ExportPathMap) => {
return defaultMap
}
}
// Start the rendering process
const renderOpts = {
dir,
buildId,
nextExport: true,
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
distDir,
dev: false,
staticMarkup: false,
hotReloader: null,
canonicalBase: (nextConfig.amp && nextConfig.amp.canonicalBase) || '',
isModern: nextConfig.experimental.modern,
}
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
if (Object.keys(publicRuntimeConfig).length > 0) {
;(renderOpts as any).runtimeConfig = publicRuntimeConfig
}
// We need this for server rendering the Link component.
;(global as any).__NEXT_DATA__ = {
nextExport: true,
}
log(` launching ${threads} workers`)
const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false,
dir,
outDir,
distDir,
buildId,
})
if (!exportPathMap['/404']) {
exportPathMap['/404.html'] = exportPathMap['/404.html'] || {
page: '/_error',
}
}
const exportPaths = Object.keys(exportPathMap)
const filteredPaths = exportPaths.filter(
// Remove API routes
route => !exportPathMap[route].page.match(API_ROUTE)
)
const hasApiRoutes = exportPaths.length !== filteredPaths.length
// Warn if the user defines a path for an API page
if (hasApiRoutes) {
log(
chalk.yellow(
' API pages are not supported by next export. https://err.sh/zeit/next.js/api-routes-static-export'
)
)
}
const progress = !options.silent && createProgress(filteredPaths.length)
const sprDataDir = options.buildExport
? outDir
: join(outDir, '_next/data', buildId)
const ampValidations: AmpPageStatus = {}
let hadValidationError = false
const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
// Copy public directory
if (!options.buildExport && existsSync(publicDir)) {
log(' copying "public" directory')
await recursiveCopy(publicDir, outDir, {
filter(path) {
// Exclude paths used by pages
return !exportPathMap[path]
},
})
}
const worker: Worker & { default: Function } = new Worker(
require.resolve('./worker'),
{
maxRetries: 0,
numWorkers: threads,
enableWorkerThreads: true,
exposedMethods: ['default'],
}
) as any
worker.getStdout().pipe(process.stdout)
worker.getStderr().pipe(process.stderr)
let renderError = false
await Promise.all(
filteredPaths.map(async path => {
const result = await worker.default({
path,
pathMap: exportPathMap[path],
distDir,
buildId,
outDir,
sprDataDir,
renderOpts,
serverRuntimeConfig,
subFolders,
buildExport: options.buildExport,
serverless: isTargetLikeServerless(nextConfig.target),
})
for (const validation of result.ampValidations || []) {
const { page, result } = validation
ampValidations[page] = result
hadValidationError =
hadValidationError ||
(Array.isArray(result && result.errors) && result.errors.length > 0)
}
renderError = renderError || !!result.error
if (
options.buildExport &&
typeof result.fromBuildExportRevalidate !== 'undefined'
) {
configuration.initialPageRevalidationMap[path] =
result.fromBuildExportRevalidate
}
if (progress) progress()
})
)
worker.end()
// copy prerendered routes to outDir
if (!options.buildExport && prerenderManifest) {
await Promise.all(
Object.keys(prerenderManifest.routes).map(async route => {
route = route === '/' ? '/index' : route
const orig = join(distPagesDir, route)
const htmlDest = join(outDir, `${route}.html`)
const jsonDest = join(sprDataDir, `${route}.json`)
await mkdirp(dirname(htmlDest))
await mkdirp(dirname(jsonDest))
await copyFile(`${orig}.html`, htmlDest)
await copyFile(`${orig}.json`, jsonDest)
})
)
}
if (Object.keys(ampValidations).length) {
console.log(formatAmpMessages(ampValidations))
}
if (hadValidationError) {
throw new Error(
`AMP Validation caused the export to fail. https://err.sh/zeit/next.js/amp-export-validation`
)
}
if (renderError) {
throw new Error(`Export encountered errors`)
}
// Add an empty line to the console for the better readability.
log('')
}