index.ts 14.1 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
import { promisify } from 'util'
import { AmpPageStatus, formatAmpMessages } from '../build/output/index'
15
import * as Log from '../build/output/log'
J
Joe Haddad 已提交
16
import createSpinner from '../build/spinner'
17
import { API_ROUTE, SSG_FALLBACK_EXPORT_ERROR } from '../lib/constants'
18 19
import { recursiveCopy } from '../lib/recursive-copy'
import { recursiveDelete } from '../lib/recursive-delete'
20 21
import {
  BUILD_ID_FILE,
J
Joe Haddad 已提交
22 23 24
  CLIENT_PUBLIC_FILES_PATH,
  CLIENT_STATIC_FILES_PATH,
  CONFIG_FILE,
J
Joe Haddad 已提交
25
  EXPORT_DETAIL,
J
Joe Haddad 已提交
26 27
  PAGES_MANIFEST,
  PHASE_EXPORT,
J
JJ Kasper 已提交
28 29
  PRERENDER_MANIFEST,
  SERVERLESS_DIRECTORY,
J
Joe Haddad 已提交
30
  SERVER_DIRECTORY,
31
} from '../next-server/lib/constants'
J
Joe Haddad 已提交
32 33 34
import loadConfig, {
  isTargetLikeServerless,
} from '../next-server/server/config'
35
import { eventCliSession } from '../telemetry/events'
J
Joe Haddad 已提交
36
import { Telemetry } from '../telemetry/storage'
37 38 39 40
import {
  normalizePagePath,
  denormalizePagePath,
} from '../next-server/server/normalize-page-path'
41
import { loadEnvConfig } from '../lib/load-env-config'
42
import { PrerenderManifest } from '../build'
43
import type exportPage from './worker'
J
Jan Potoms 已提交
44
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
45
import { getPagePath } from '../next-server/server/require'
46

47
const exists = promisify(existsOrig)
48

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

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

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

export default async function exportApp(
J
Joe Haddad 已提交
105
  dir: string,
J
Jan Potoms 已提交
106
  options: ExportOptions,
J
Joe Haddad 已提交
107 108
  configuration?: any
): Promise<void> {
109
  dir = resolve(dir)
110 111 112 113

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

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

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

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

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

134 135 136
  if (!options.silent && !options.buildExport) {
    Log.info(`using build directory: ${distDir}`)
  }
137

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

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

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

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

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

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

    if (page === '/_document' || page === '/_app' || page === '/_error') {
174 175 176
      continue
    }

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

186 187
    defaultPathMap[page] = { page }
  }
188 189

  // Initialize the output directory
190
  const outDir = options.outdir
191 192 193

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

198
  await recursiveDelete(join(outDir))
199
  await promises.mkdir(join(outDir, '_next', buildId), { recursive: true })
200

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

211
  // Copy static directory
212
  if (!options.buildExport && existsSync(join(dir, 'static'))) {
213 214 215
    if (!options.silent) {
      Log.info('Copying "static" directory')
    }
216
    await recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
217 218
  }

219
  // Copy .next/static directory
220 221 222 223 224 225 226
  if (
    !options.buildExport &&
    existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))
  ) {
    if (!options.silent) {
      Log.info('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 238 239
    if (!options.silent) {
      Log.info(
        `No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`
      )
    }
J
Joe Haddad 已提交
240
    nextConfig.exportPathMap = async (defaultMap: ExportPathMap) => {
241 242
      return defaultMap
    }
243 244
  }

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

262
  const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
263

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

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

273 274 275
  if (!options.silent && !options.buildExport) {
    Log.info(`Launching ${threads} workers`)
  }
276 277 278 279 280
  const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {
    dev: false,
    dir,
    outDir,
    distDir,
J
Joe Haddad 已提交
281
    buildId,
282
  })
283

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

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

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

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

308
  if (prerenderManifest && !options.buildExport) {
309
    const fallbackEnabledPages = new Set()
310 311 312 313 314 315 316 317

    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) {
318
        fallbackEnabledPages.add(key)
319 320 321
      }
    }

322
    if (fallbackEnabledPages.size) {
323
      throw new Error(
324 325 326
        `Found pages with \`fallback\` enabled:\n${[
          ...fallbackEnabledPages,
        ].join('\n')}\n${SSG_FALLBACK_EXPORT_ERROR}\n`
327 328 329 330
      )
    }
  }

331 332
  // Warn if the user defines a path for an API page
  if (hasApiRoutes) {
333 334
    if (!options.silent) {
      Log.warn(
335 336 337
        chalk.yellow(
          `Statically exporting a Next.js application via \`next export\` disables API routes.`
        ) +
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
          `\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\`.`
          ) +
          `\n` +
          chalk.yellow(
            `Learn more: https://err.sh/vercel/next.js/api-routes-static-export`
          )
      )
    }
354
  }
355

356 357 358 359 360 361
  const progress =
    !options.silent &&
    createProgress(
      filteredPaths.length,
      `${Log.prefixes.info} ${options.statusMessage}`
    )
362
  const pagesDataDir = options.buildExport
J
JJ Kasper 已提交
363 364
    ? outDir
    : join(outDir, '_next/data', buildId)
A
Arunoda Susiripala 已提交
365

J
Joe Haddad 已提交
366
  const ampValidations: AmpPageStatus = {}
J
JJ Kasper 已提交
367 368
  let hadValidationError = false

369 370
  const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
  // Copy public directory
371
  if (!options.buildExport && existsSync(publicDir)) {
372 373 374
    if (!options.silent) {
      Log.info('Copying "public" directory')
    }
375
    await recursiveCopy(publicDir, outDir, {
J
Joe Haddad 已提交
376
      filter(path) {
377
        // Exclude paths used by pages
378
        return !exportPathMap[path]
J
Joe Haddad 已提交
379
      },
380
    })
381
  }
382

J
Jan Potoms 已提交
383 384 385 386 387
  const worker = new Worker(require.resolve('./worker'), {
    maxRetries: 0,
    numWorkers: threads,
    enableWorkerThreads: nextConfig.experimental.workerThreads,
    exposedMethods: ['default'],
388
  }) as Worker & { default: typeof exportPage }
389 390 391 392 393

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

  let renderError = false
394
  const errorPaths: string[] = []
395

396
  await Promise.all(
J
Joe Haddad 已提交
397
    filteredPaths.map(async (path) => {
398 399 400 401 402
      const result = await worker.default({
        path,
        pathMap: exportPathMap[path],
        distDir,
        outDir,
403
        pagesDataDir,
404 405 406
        renderOpts,
        serverRuntimeConfig,
        subFolders,
J
JJ Kasper 已提交
407
        buildExport: options.buildExport,
J
Joe Haddad 已提交
408
        serverless: isTargetLikeServerless(nextConfig.target),
P
Prateek Bhatnagar 已提交
409
        optimizeFonts: nextConfig.experimental.optimizeFonts,
410 411 412
      })

      for (const validation of result.ampValidations || []) {
413 414
        const { page, result: ampValidationResult } = validation
        ampValidations[page] = ampValidationResult
J
Joe Haddad 已提交
415 416
        hadValidationError =
          hadValidationError ||
417 418
          (Array.isArray(ampValidationResult?.errors) &&
            ampValidationResult.errors.length > 0)
419
      }
J
Joe Haddad 已提交
420
      renderError = renderError || !!result.error
421
      if (!!result.error) errorPaths.push(path)
J
JJ Kasper 已提交
422 423 424 425 426 427 428 429

      if (
        options.buildExport &&
        typeof result.fromBuildExportRevalidate !== 'undefined'
      ) {
        configuration.initialPageRevalidationMap[path] =
          result.fromBuildExportRevalidate
      }
430 431
      if (progress) progress()
    })
432
  )
433

434
  worker.end()
J
JJ Kasper 已提交
435

J
JJ Kasper 已提交
436 437 438
  // copy prerendered routes to outDir
  if (!options.buildExport && prerenderManifest) {
    await Promise.all(
J
Joe Haddad 已提交
439
      Object.keys(prerenderManifest.routes).map(async (route) => {
440 441 442 443 444 445 446 447 448 449 450 451 452
        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('/')
        )
453
        route = normalizePagePath(route)
454

J
JJ Kasper 已提交
455
        const orig = join(distPagesDir, route)
456 457 458 459 460 461
        const htmlDest = join(
          outDir,
          `${route}${
            subFolders && route !== '/index' ? `${sep}index` : ''
          }.html`
        )
462 463 464 465
        const ampHtmlDest = join(
          outDir,
          `${route}.amp${subFolders ? `${sep}index` : ''}.html`
        )
466
        const jsonDest = join(pagesDataDir, `${route}.json`)
J
JJ Kasper 已提交
467

468 469 470 471
        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)
472 473

        if (await exists(`${orig}.amp.html`)) {
474 475
          await promises.mkdir(dirname(ampHtmlDest), { recursive: true })
          await promises.copyFile(`${orig}.amp.html`, ampHtmlDest)
476
        }
J
JJ Kasper 已提交
477 478 479 480
      })
    )
  }

J
JJ Kasper 已提交
481 482 483 484
  if (Object.keys(ampValidations).length) {
    console.log(formatAmpMessages(ampValidations))
  }
  if (hadValidationError) {
485
    throw new Error(
486
      `AMP Validation caused the export to fail. https://err.sh/vercel/next.js/amp-export-validation`
487
    )
J
JJ Kasper 已提交
488 489
  }

490
  if (renderError) {
491 492 493 494 495
    throw new Error(
      `Export encountered errors on following paths:\n\t${errorPaths
        .sort()
        .join('\n\t')}`
    )
496
  }
497

J
Joe Haddad 已提交
498 499 500 501 502 503 504 505 506 507
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: true,
    }),
    'utf8'
  )

508 509 510
  if (telemetry) {
    await telemetry.flush()
  }
511
}