index.ts 13.8 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
import { getPagePath } from '../next-server/server/require'
45

46
const exists = promisify(existsOrig)
47

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

  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 已提交
90 91 92 93
type ExportPathMap = {
  [page: string]: { page: string; query?: { [key: string]: string } }
}

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

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

114
  dir = resolve(dir)
115 116 117 118

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

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

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

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

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

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

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

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

156
  let prerenderManifest: PrerenderManifest | undefined = undefined
J
JJ Kasper 已提交
157 158 159 160
  try {
    prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
  } catch (_) {}

161
  const excludedPrerenderRoutes = new Set<string>()
J
JJ Kasper 已提交
162
  const pages = options.pages || Object.keys(pagesManifest)
J
Joe Haddad 已提交
163
  const defaultPathMap: ExportPathMap = {}
164
  let hasApiRoutes = false
165 166

  for (const page of pages) {
167 168
    // _document and _app are not real pages
    // _error is exported as 404.html later on
169
    // API Routes are Node.js functions
170 171 172 173 174 175 176

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

    if (page === '/_document' || page === '/_app' || page === '/_error') {
177 178 179
      continue
    }

180 181 182 183
    // 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`.
184
    if (prerenderManifest?.dynamicRoutes[page]) {
185
      excludedPrerenderRoutes.add(page)
186 187 188
      continue
    }

189 190
    defaultPathMap[page] = { page }
  }
191 192

  // Initialize the output directory
193
  const outDir = options.outdir
194 195 196

  if (outDir === join(dir, 'public')) {
    throw new Error(
197
      `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`
198 199 200
    )
  }

201
  await recursiveDelete(join(outDir))
202
  await promises.mkdir(join(outDir, '_next', buildId), { recursive: true })
203

J
Joe Haddad 已提交
204 205 206 207 208 209 210 211 212 213
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: false,
    }),
    'utf8'
  )

214
  // Copy static directory
215
  if (!options.buildExport && existsSync(join(dir, 'static'))) {
216
    log('  copying "static" directory')
217
    await recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
218 219
  }

220
  // Copy .next/static directory
221
  if (existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))) {
222
    log('  copying "static build" directory')
223
    await recursiveCopy(
224 225
      join(distDir, CLIENT_STATIC_FILES_PATH),
      join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
226 227 228
    )
  }

229
  // Get the exportPathMap from the config file
230
  if (typeof nextConfig.exportPathMap !== 'function') {
231 232 233
    console.log(
      `> No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`
    )
J
Joe Haddad 已提交
234
    nextConfig.exportPathMap = async (defaultMap: ExportPathMap) => {
235 236
      return defaultMap
    }
237 238
  }

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

256
  const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
257

258
  if (Object.keys(publicRuntimeConfig).length > 0) {
J
Joe Haddad 已提交
259
    ;(renderOpts as any).runtimeConfig = publicRuntimeConfig
260 261
  }

262
  // We need this for server rendering the Link component.
J
Joe Haddad 已提交
263 264
  ;(global as any).__NEXT_DATA__ = {
    nextExport: true,
265 266
  }

267
  log(`  launching ${threads} workers`)
268 269 270 271 272
  const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {
    dev: false,
    dir,
    outDir,
    distDir,
J
Joe Haddad 已提交
273
    buildId,
274
  })
275

276 277
  if (!exportPathMap['/404'] && !exportPathMap['/404.html']) {
    exportPathMap['/404'] = exportPathMap['/404.html'] = {
J
Joe Haddad 已提交
278
      page: '/_error',
279
    }
280
  }
281 282 283 284

  // make sure to prevent duplicates
  const exportPaths = [
    ...new Set(
285 286
      Object.keys(exportPathMap).map((path) =>
        denormalizePagePath(normalizePagePath(path))
287 288 289 290
      )
    ),
  ]

291 292
  const filteredPaths = exportPaths.filter(
    // Remove API routes
J
Joe Haddad 已提交
293
    (route) => !exportPathMap[route].page.match(API_ROUTE)
294
  )
295 296 297 298

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

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  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`
      )
    }
  }

323 324 325
  // Warn if the user defines a path for an API page
  if (hasApiRoutes) {
    log(
326
      chalk.bold.red(`Warning`) +
327 328 329 330 331 332 333 334 335 336 337 338 339 340
        ': ' +
        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\`.`
        ) +
341
        `\nLearn more: https://err.sh/vercel/next.js/api-routes-static-export`
342 343
    )
  }
344

345
  const progress = !options.silent && createProgress(filteredPaths.length)
346
  const pagesDataDir = options.buildExport
J
JJ Kasper 已提交
347 348
    ? outDir
    : join(outDir, '_next/data', buildId)
A
Arunoda Susiripala 已提交
349

J
Joe Haddad 已提交
350
  const ampValidations: AmpPageStatus = {}
J
JJ Kasper 已提交
351 352
  let hadValidationError = false

353 354
  const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
  // Copy public directory
355
  if (!options.buildExport && existsSync(publicDir)) {
356
    log('  copying "public" directory')
357
    await recursiveCopy(publicDir, outDir, {
J
Joe Haddad 已提交
358
      filter(path) {
359
        // Exclude paths used by pages
360
        return !exportPathMap[path]
J
Joe Haddad 已提交
361
      },
362
    })
363
  }
364

J
Jan Potoms 已提交
365 366 367 368 369
  const worker = new Worker(require.resolve('./worker'), {
    maxRetries: 0,
    numWorkers: threads,
    enableWorkerThreads: nextConfig.experimental.workerThreads,
    exposedMethods: ['default'],
370
  }) as Worker & { default: typeof exportPage }
371 372 373 374 375

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

  let renderError = false
376
  const errorPaths: string[] = []
377

378
  await Promise.all(
J
Joe Haddad 已提交
379
    filteredPaths.map(async (path) => {
380 381 382 383 384
      const result = await worker.default({
        path,
        pathMap: exportPathMap[path],
        distDir,
        outDir,
385
        pagesDataDir,
386 387 388
        renderOpts,
        serverRuntimeConfig,
        subFolders,
J
JJ Kasper 已提交
389
        buildExport: options.buildExport,
J
Joe Haddad 已提交
390
        serverless: isTargetLikeServerless(nextConfig.target),
P
Prateek Bhatnagar 已提交
391
        optimizeFonts: nextConfig.experimental.optimizeFonts,
392 393 394
      })

      for (const validation of result.ampValidations || []) {
395 396
        const { page, result: ampValidationResult } = validation
        ampValidations[page] = ampValidationResult
J
Joe Haddad 已提交
397 398
        hadValidationError =
          hadValidationError ||
399 400
          (Array.isArray(ampValidationResult?.errors) &&
            ampValidationResult.errors.length > 0)
401
      }
J
Joe Haddad 已提交
402
      renderError = renderError || !!result.error
403
      if (!!result.error) errorPaths.push(path)
J
JJ Kasper 已提交
404 405 406 407 408 409 410 411

      if (
        options.buildExport &&
        typeof result.fromBuildExportRevalidate !== 'undefined'
      ) {
        configuration.initialPageRevalidationMap[path] =
          result.fromBuildExportRevalidate
      }
412 413
      if (progress) progress()
    })
414
  )
415

416
  worker.end()
J
JJ Kasper 已提交
417

J
JJ Kasper 已提交
418 419 420
  // copy prerendered routes to outDir
  if (!options.buildExport && prerenderManifest) {
    await Promise.all(
J
Joe Haddad 已提交
421
      Object.keys(prerenderManifest.routes).map(async (route) => {
422 423 424 425 426 427 428 429 430 431 432 433 434
        const { srcRoute } = prerenderManifest!.routes[route]
        const pageName = srcRoute || route
        const pagePath = getPagePath(pageName, distDir, isLikeServerless)
        const distPagesDir = join(
          pagePath,
          // strip leading / and then recurse number of nested dirs
          // to place from base folder
          pageName
            .substr(1)
            .split('/')
            .map(() => '..')
            .join('/')
        )
435
        route = normalizePagePath(route)
436

J
JJ Kasper 已提交
437
        const orig = join(distPagesDir, route)
438 439 440 441 442 443
        const htmlDest = join(
          outDir,
          `${route}${
            subFolders && route !== '/index' ? `${sep}index` : ''
          }.html`
        )
444 445 446 447
        const ampHtmlDest = join(
          outDir,
          `${route}.amp${subFolders ? `${sep}index` : ''}.html`
        )
448
        const jsonDest = join(pagesDataDir, `${route}.json`)
J
JJ Kasper 已提交
449

450 451 452 453
        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)
454 455

        if (await exists(`${orig}.amp.html`)) {
456 457
          await promises.mkdir(dirname(ampHtmlDest), { recursive: true })
          await promises.copyFile(`${orig}.amp.html`, ampHtmlDest)
458
        }
J
JJ Kasper 已提交
459 460 461 462
      })
    )
  }

J
JJ Kasper 已提交
463 464 465 466
  if (Object.keys(ampValidations).length) {
    console.log(formatAmpMessages(ampValidations))
  }
  if (hadValidationError) {
467
    throw new Error(
468
      `AMP Validation caused the export to fail. https://err.sh/vercel/next.js/amp-export-validation`
469
    )
J
JJ Kasper 已提交
470 471
  }

472
  if (renderError) {
473 474 475 476 477
    throw new Error(
      `Export encountered errors on following paths:\n\t${errorPaths
        .sort()
        .join('\n\t')}`
    )
478
  }
479 480
  // Add an empty line to the console for the better readability.
  log('')
481

J
Joe Haddad 已提交
482 483 484 485 486 487 488 489 490 491
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: true,
    }),
    'utf8'
  )

492 493 494
  if (telemetry) {
    await telemetry.flush()
  }
495
}