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
import { normalizePagePath } from '../next-server/server/normalize-page-path'
37
import { loadEnvConfig } from '../lib/load-env-config'
38
import { PrerenderManifest } from '../build'
39
import type exportPage from './worker'
J
Jan Potoms 已提交
40
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
41

42
const exists = promisify(existsOrig)
43

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

  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 已提交
86 87 88 89
type ExportPathMap = {
  [page: string]: { page: string; query?: { [key: string]: string } }
}

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

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

110
  dir = resolve(dir)
111 112 113 114

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

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

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

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

132
  const subFolders = nextConfig.exportTrailingSlash
J
JJ Kasper 已提交
133
  const isLikeServerless = nextConfig.target !== 'server'
134

135
  log(`> using build directory: ${distDir}`)
136

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

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

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

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

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

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

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

    if (page === '/_document' || page === '/_app' || page === '/_error') {
181 182 183
      continue
    }

184 185 186 187
    // 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`.
188
    if (prerenderManifest?.dynamicRoutes[page]) {
189
      excludedPrerenderRoutes.add(page)
190 191 192
      continue
    }

193 194
    defaultPathMap[page] = { page }
  }
195 196

  // Initialize the output directory
197
  const outDir = options.outdir
198 199 200

  if (outDir === join(dir, 'public')) {
    throw new Error(
201
      `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`
202 203 204
    )
  }

205
  await recursiveDelete(join(outDir))
206
  await promises.mkdir(join(outDir, '_next', buildId), { recursive: true })
207

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

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

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

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

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

261
  const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
262

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

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

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

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

  // make sure to prevent duplicates
  const exportPaths = [
    ...new Set(
      Object.keys(exportPathMap).map(
        (path) => normalizePagePath(path).replace(/^\/index$/, '') || '/'
      )
    ),
  ]

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

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

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
  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`
      )
    }
  }

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

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

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

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

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

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

  let renderError = false
381
  const errorPaths: string[] = []
382

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

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

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

421
  worker.end()
J
JJ Kasper 已提交
422

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

441 442 443 444
        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)
445 446

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

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

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

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

483 484 485
  if (telemetry) {
    await telemetry.flush()
  }
486
}