index.ts 13.4 KB
Newer Older
G
Guy Bedford 已提交
1
import chalk from 'next/dist/compiled/chalk'
G
find-up  
Guy Bedford 已提交
2
import findUp from 'next/dist/compiled/find-up'
J
Joe Haddad 已提交
3
import {
4
  promises,
J
Joe Haddad 已提交
5
  existsSync,
6
  exists as existsOrig,
J
Joe Haddad 已提交
7 8 9
  readFileSync,
  writeFileSync,
} from 'fs'
10
import Worker from 'jest-worker'
J
Joe Haddad 已提交
11
import { cpus } from 'os'
12
import { dirname, join, resolve, sep } from 'path'
J
Joe Haddad 已提交
13 14 15
import { promisify } from 'util'
import { AmpPageStatus, formatAmpMessages } from '../build/output/index'
import createSpinner from '../build/spinner'
16
import { API_ROUTE, SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants'
17 18
import { recursiveCopy } from '../lib/recursive-copy'
import { recursiveDelete } from '../lib/recursive-delete'
19 20
import {
  BUILD_ID_FILE,
J
Joe Haddad 已提交
21 22 23
  CLIENT_PUBLIC_FILES_PATH,
  CLIENT_STATIC_FILES_PATH,
  CONFIG_FILE,
J
Joe Haddad 已提交
24
  EXPORT_DETAIL,
J
Joe Haddad 已提交
25 26
  PAGES_MANIFEST,
  PHASE_EXPORT,
J
JJ Kasper 已提交
27 28
  PRERENDER_MANIFEST,
  SERVERLESS_DIRECTORY,
J
Joe Haddad 已提交
29
  SERVER_DIRECTORY,
30
} from '../next-server/lib/constants'
J
Joe Haddad 已提交
31 32 33
import loadConfig, {
  isTargetLikeServerless,
} from '../next-server/server/config'
34
import { eventCliSession } from '../telemetry/events'
J
Joe Haddad 已提交
35
import { Telemetry } from '../telemetry/storage'
36 37 38 39
import {
  normalizePagePath,
  denormalizePagePath,
} from '../next-server/server/normalize-page-path'
40
import { loadEnvConfig } from '../lib/load-env-config'
41
import { PrerenderManifest } from '../build'
42
import type exportPage from './worker'
J
Jan Potoms 已提交
43
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
44

45
const exists = promisify(existsOrig)
46

J
Joe Haddad 已提交
47
const createProgress = (total: number, label = 'Exporting') => {
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  let curProgress = 0
  let progressSpinner = createSpinner(`${label} (${curProgress}/${total})`, {
    spinner: {
      frames: [
        '[    ]',
        '[=   ]',
        '[==  ]',
        '[=== ]',
        '[ ===]',
        '[  ==]',
        '[   =]',
        '[    ]',
        '[   =]',
        '[  ==]',
        '[ ===]',
        '[====]',
        '[=== ]',
        '[==  ]',
J
Joe Haddad 已提交
66
        '[=   ]',
67
      ],
J
Joe Haddad 已提交
68 69
      interval: 80,
    },
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  })

  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)
    }
  }
}

J
Joe Haddad 已提交
89 90 91 92
type ExportPathMap = {
  [page: string]: { page: string; query?: { [key: string]: string } }
}

J
Jan Potoms 已提交
93 94 95 96 97 98 99 100 101
interface ExportOptions {
  outdir: string
  silent?: boolean
  threads?: number
  pages?: string[]
  buildExport?: boolean
}

export default async function exportApp(
J
Joe Haddad 已提交
102
  dir: string,
J
Jan Potoms 已提交
103
  options: ExportOptions,
J
Joe Haddad 已提交
104 105
  configuration?: any
): Promise<void> {
106
  function log(message: string): void {
J
Joe Haddad 已提交
107 108 109
    if (options.silent) {
      return
    }
110 111 112
    console.log(message)
  }

113
  dir = resolve(dir)
114 115 116 117

  // attempt to load global env values so they are available in next.config.js
  loadEnvConfig(dir)

118
  const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir)
119
  const threads = options.threads || Math.max(cpus().length - 1, 1)
120
  const distDir = join(dir, nextConfig.distDir)
121 122 123 124

  const telemetry = options.buildExport ? null : new Telemetry({ distDir })

  if (telemetry) {
125
    telemetry.record(
126
      eventCliSession(PHASE_EXPORT, distDir, {
127 128 129 130 131 132
        cliCommand: 'export',
        isSrcDir: null,
        hasNowJson: !!(await findUp('now.json', { cwd: dir })),
        isCustomServer: null,
      })
    )
133 134
  }

135
  const subFolders = nextConfig.exportTrailingSlash
J
JJ Kasper 已提交
136
  const isLikeServerless = nextConfig.target !== 'server'
137

138
  log(`> using build directory: ${distDir}`)
139

140
  if (!existsSync(distDir)) {
141 142 143
    throw new Error(
      `Build directory ${distDir} does not exist. Make sure you run "next build" before running "next start" or "next export".`
    )
144 145
  }

146
  const buildId = readFileSync(join(distDir, BUILD_ID_FILE), 'utf8')
147
  const pagesManifest =
148
    !options.pages &&
J
Jan Potoms 已提交
149
    (require(join(
150 151 152
      distDir,
      isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
      PAGES_MANIFEST
J
Jan Potoms 已提交
153
    )) as PagesManifest)
154

155
  let prerenderManifest: PrerenderManifest | undefined = undefined
J
JJ Kasper 已提交
156 157 158 159 160 161 162 163 164 165 166 167
  try {
    prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
  } catch (_) {}

  const distPagesDir = join(
    distDir,
    isLikeServerless
      ? SERVERLESS_DIRECTORY
      : join(SERVER_DIRECTORY, 'static', buildId),
    'pages'
  )

168
  const excludedPrerenderRoutes = new Set<string>()
J
JJ Kasper 已提交
169
  const pages = options.pages || Object.keys(pagesManifest)
J
Joe Haddad 已提交
170
  const defaultPathMap: ExportPathMap = {}
171
  let hasApiRoutes = false
172 173

  for (const page of pages) {
174 175
    // _document and _app are not real pages
    // _error is exported as 404.html later on
176
    // API Routes are Node.js functions
177 178 179 180 181 182 183

    if (page.match(API_ROUTE)) {
      hasApiRoutes = true
      continue
    }

    if (page === '/_document' || page === '/_app' || page === '/_error') {
184 185 186
      continue
    }

187 188 189 190
    // iSSG pages that are dynamic should not export templated version by
    // default. In most cases, this would never work. There is no server that
    // could run `getStaticProps`. If users make their page work lazily, they
    // can manually add it to the `exportPathMap`.
191
    if (prerenderManifest?.dynamicRoutes[page]) {
192
      excludedPrerenderRoutes.add(page)
193 194 195
      continue
    }

196 197
    defaultPathMap[page] = { page }
  }
198 199

  // Initialize the output directory
200
  const outDir = options.outdir
201 202 203

  if (outDir === join(dir, 'public')) {
    throw new Error(
204
      `The 'public' directory is reserved in Next.js and can not be used as the export out directory. https://err.sh/vercel/next.js/can-not-output-to-public`
205 206 207
    )
  }

208
  await recursiveDelete(join(outDir))
209
  await promises.mkdir(join(outDir, '_next', buildId), { recursive: true })
210

J
Joe Haddad 已提交
211 212 213 214 215 216 217 218 219 220
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: false,
    }),
    'utf8'
  )

221
  // Copy static directory
222
  if (!options.buildExport && existsSync(join(dir, 'static'))) {
223
    log('  copying "static" directory')
224
    await recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
225 226
  }

227
  // Copy .next/static directory
228
  if (existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))) {
229
    log('  copying "static build" directory')
230
    await recursiveCopy(
231 232
      join(distDir, CLIENT_STATIC_FILES_PATH),
      join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
233 234 235
    )
  }

236
  // Get the exportPathMap from the config file
237
  if (typeof nextConfig.exportPathMap !== 'function') {
238 239 240
    console.log(
      `> No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`
    )
J
Joe Haddad 已提交
241
    nextConfig.exportPathMap = async (defaultMap: ExportPathMap) => {
242 243
      return defaultMap
    }
244 245
  }

246 247 248 249
  // Start the rendering process
  const renderOpts = {
    dir,
    buildId,
250
    nextExport: true,
251
    assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
252
    distDir,
253
    dev: false,
254
    hotReloader: null,
255
    basePath: nextConfig.experimental.basePath,
256
    canonicalBase: nextConfig.amp?.canonicalBase || '',
J
Joe Haddad 已提交
257
    isModern: nextConfig.experimental.modern,
258
    ampValidatorPath: nextConfig.experimental.amp?.validator || undefined,
259 260
    ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
    ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
261 262
  }

263
  const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
264

265
  if (Object.keys(publicRuntimeConfig).length > 0) {
J
Joe Haddad 已提交
266
    ;(renderOpts as any).runtimeConfig = publicRuntimeConfig
267 268
  }

269
  // We need this for server rendering the Link component.
J
Joe Haddad 已提交
270 271
  ;(global as any).__NEXT_DATA__ = {
    nextExport: true,
272 273
  }

274
  log(`  launching ${threads} workers`)
275 276 277 278 279
  const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {
    dev: false,
    dir,
    outDir,
    distDir,
J
Joe Haddad 已提交
280
    buildId,
281
  })
282

283 284
  if (!exportPathMap['/404'] && !exportPathMap['/404.html']) {
    exportPathMap['/404'] = exportPathMap['/404.html'] = {
J
Joe Haddad 已提交
285
      page: '/_error',
286
    }
287
  }
288 289 290 291

  // make sure to prevent duplicates
  const exportPaths = [
    ...new Set(
292 293
      Object.keys(exportPathMap).map((path) =>
        denormalizePagePath(normalizePagePath(path))
294 295 296 297
      )
    ),
  ]

298 299
  const filteredPaths = exportPaths.filter(
    // Remove API routes
J
Joe Haddad 已提交
300
    (route) => !exportPathMap[route].page.match(API_ROUTE)
301
  )
302 303 304 305

  if (filteredPaths.length !== exportPaths.length) {
    hasApiRoutes = true
  }
306

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  if (prerenderManifest && !options.buildExport) {
    const fallbackTruePages = new Set()

    for (const key of Object.keys(prerenderManifest.dynamicRoutes)) {
      // only error if page is included in path map
      if (!exportPathMap[key] && !excludedPrerenderRoutes.has(key)) {
        continue
      }

      if (prerenderManifest.dynamicRoutes[key].fallback !== false) {
        fallbackTruePages.add(key)
      }
    }

    if (fallbackTruePages.size) {
      throw new Error(
        `Found pages with \`fallback: true\`:\n${[...fallbackTruePages].join(
          '\n'
        )}\n${SSG_FALLBACK_EXPORT_ERROR}\n`
      )
    }
  }

330 331 332
  // Warn if the user defines a path for an API page
  if (hasApiRoutes) {
    log(
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
      chalk.bold.red(`Attention`) +
        ': ' +
        chalk.yellow(
          `Statically exporting a Next.js application via \`next export\` disables API routes.`
        ) +
        `\n` +
        chalk.yellow(
          `This command is meant for static-only hosts, and is` +
            ' ' +
            chalk.bold(`not necessary to make your application static.`)
        ) +
        `\n` +
        chalk.yellow(
          `Pages in your application without server-side data dependencies will be automatically statically exported by \`next build\`, including pages powered by \`getStaticProps\`.`
        ) +
348
        `\nLearn more: https://err.sh/vercel/next.js/api-routes-static-export`
349 350
    )
  }
351

352
  const progress = !options.silent && createProgress(filteredPaths.length)
353
  const pagesDataDir = options.buildExport
J
JJ Kasper 已提交
354 355
    ? outDir
    : join(outDir, '_next/data', buildId)
A
Arunoda Susiripala 已提交
356

J
Joe Haddad 已提交
357
  const ampValidations: AmpPageStatus = {}
J
JJ Kasper 已提交
358 359
  let hadValidationError = false

360 361
  const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
  // Copy public directory
362
  if (!options.buildExport && existsSync(publicDir)) {
363
    log('  copying "public" directory')
364
    await recursiveCopy(publicDir, outDir, {
J
Joe Haddad 已提交
365
      filter(path) {
366
        // Exclude paths used by pages
367
        return !exportPathMap[path]
J
Joe Haddad 已提交
368
      },
369
    })
370
  }
371

J
Jan Potoms 已提交
372 373 374 375 376
  const worker = new Worker(require.resolve('./worker'), {
    maxRetries: 0,
    numWorkers: threads,
    enableWorkerThreads: nextConfig.experimental.workerThreads,
    exposedMethods: ['default'],
377
  }) as Worker & { default: typeof exportPage }
378 379 380 381 382

  worker.getStdout().pipe(process.stdout)
  worker.getStderr().pipe(process.stderr)

  let renderError = false
383
  const errorPaths: string[] = []
384

385
  await Promise.all(
J
Joe Haddad 已提交
386
    filteredPaths.map(async (path) => {
387 388 389 390 391 392
      const result = await worker.default({
        path,
        pathMap: exportPathMap[path],
        distDir,
        buildId,
        outDir,
393
        pagesDataDir,
394 395 396
        renderOpts,
        serverRuntimeConfig,
        subFolders,
J
JJ Kasper 已提交
397
        buildExport: options.buildExport,
J
Joe Haddad 已提交
398
        serverless: isTargetLikeServerless(nextConfig.target),
399 400 401
      })

      for (const validation of result.ampValidations || []) {
402 403
        const { page, result: ampValidationResult } = validation
        ampValidations[page] = ampValidationResult
J
Joe Haddad 已提交
404 405
        hadValidationError =
          hadValidationError ||
406 407
          (Array.isArray(ampValidationResult?.errors) &&
            ampValidationResult.errors.length > 0)
408
      }
J
Joe Haddad 已提交
409
      renderError = renderError || !!result.error
410
      if (!!result.error) errorPaths.push(path)
J
JJ Kasper 已提交
411 412 413 414 415 416 417 418

      if (
        options.buildExport &&
        typeof result.fromBuildExportRevalidate !== 'undefined'
      ) {
        configuration.initialPageRevalidationMap[path] =
          result.fromBuildExportRevalidate
      }
419 420
      if (progress) progress()
    })
421
  )
422

423
  worker.end()
J
JJ Kasper 已提交
424

J
JJ Kasper 已提交
425 426 427
  // copy prerendered routes to outDir
  if (!options.buildExport && prerenderManifest) {
    await Promise.all(
J
Joe Haddad 已提交
428
      Object.keys(prerenderManifest.routes).map(async (route) => {
429
        route = normalizePagePath(route)
J
JJ Kasper 已提交
430
        const orig = join(distPagesDir, route)
431 432 433 434 435 436
        const htmlDest = join(
          outDir,
          `${route}${
            subFolders && route !== '/index' ? `${sep}index` : ''
          }.html`
        )
437 438 439 440
        const ampHtmlDest = join(
          outDir,
          `${route}.amp${subFolders ? `${sep}index` : ''}.html`
        )
441
        const jsonDest = join(pagesDataDir, `${route}.json`)
J
JJ Kasper 已提交
442

443 444 445 446
        await promises.mkdir(dirname(htmlDest), { recursive: true })
        await promises.mkdir(dirname(jsonDest), { recursive: true })
        await promises.copyFile(`${orig}.html`, htmlDest)
        await promises.copyFile(`${orig}.json`, jsonDest)
447 448

        if (await exists(`${orig}.amp.html`)) {
449 450
          await promises.mkdir(dirname(ampHtmlDest), { recursive: true })
          await promises.copyFile(`${orig}.amp.html`, ampHtmlDest)
451
        }
J
JJ Kasper 已提交
452 453 454 455
      })
    )
  }

J
JJ Kasper 已提交
456 457 458 459
  if (Object.keys(ampValidations).length) {
    console.log(formatAmpMessages(ampValidations))
  }
  if (hadValidationError) {
460
    throw new Error(
461
      `AMP Validation caused the export to fail. https://err.sh/vercel/next.js/amp-export-validation`
462
    )
J
JJ Kasper 已提交
463 464
  }

465
  if (renderError) {
466 467 468 469 470
    throw new Error(
      `Export encountered errors on following paths:\n\t${errorPaths
        .sort()
        .join('\n\t')}`
    )
471
  }
472 473
  // Add an empty line to the console for the better readability.
  log('')
474

J
Joe Haddad 已提交
475 476 477 478 479 480 481 482 483 484
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: true,
    }),
    'utf8'
  )

485 486 487
  if (telemetry) {
    await telemetry.flush()
  }
488
}