index.ts 12.9 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'
J
Jan Potoms 已提交
39
import { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
40

41
const exists = promisify(existsOrig)
42

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

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

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

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

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.exportTrailingSlash
J
JJ Kasper 已提交
132
  const isLikeServerless = nextConfig.target !== 'server'
133

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

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

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

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

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

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

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

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

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

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

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

  // Initialize the output directory
196
  const outDir = options.outdir
197 198 199 200 201 202 203

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

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

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

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

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

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

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

260
  const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
261

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

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

271
  log(`  launching ${threads} workers`)
272 273 274 275 276
  const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {
    dev: false,
    dir,
    outDir,
    distDir,
J
Joe Haddad 已提交
277
    buildId,
278
  })
279 280
  if (!exportPathMap['/404'] && !exportPathMap['/404.html']) {
    exportPathMap['/404'] = exportPathMap['/404.html'] = {
J
Joe Haddad 已提交
281
      page: '/_error',
282
    }
283
  }
284
  const exportPaths = Object.keys(exportPathMap)
285 286
  const filteredPaths = exportPaths.filter(
    // Remove API routes
J
Joe Haddad 已提交
287
    (route) => !exportPathMap[route].page.match(API_ROUTE)
288
  )
289 290 291 292

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

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
  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`
      )
    }
  }

317 318 319
  // Warn if the user defines a path for an API page
  if (hasApiRoutes) {
    log(
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
      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\`.`
        ) +
        `\nLearn more: https://err.sh/zeit/next.js/api-routes-static-export`
336 337
    )
  }
338

339
  const progress = !options.silent && createProgress(filteredPaths.length)
340
  const pagesDataDir = options.buildExport
J
JJ Kasper 已提交
341 342
    ? outDir
    : join(outDir, '_next/data', buildId)
A
Arunoda Susiripala 已提交
343

J
Joe Haddad 已提交
344
  const ampValidations: AmpPageStatus = {}
J
JJ Kasper 已提交
345 346
  let hadValidationError = false

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

J
Jan Potoms 已提交
359 360 361 362 363 364
  const worker = new Worker(require.resolve('./worker'), {
    maxRetries: 0,
    numWorkers: threads,
    enableWorkerThreads: nextConfig.experimental.workerThreads,
    exposedMethods: ['default'],
  }) as Worker & { default: Function }
365 366 367 368 369

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

  let renderError = false
370

371
  await Promise.all(
J
Joe Haddad 已提交
372
    filteredPaths.map(async (path) => {
373 374 375 376 377 378
      const result = await worker.default({
        path,
        pathMap: exportPathMap[path],
        distDir,
        buildId,
        outDir,
379
        pagesDataDir,
380 381 382
        renderOpts,
        serverRuntimeConfig,
        subFolders,
J
JJ Kasper 已提交
383
        buildExport: options.buildExport,
J
Joe Haddad 已提交
384
        serverless: isTargetLikeServerless(nextConfig.target),
385 386 387 388 389
      })

      for (const validation of result.ampValidations || []) {
        const { page, result } = validation
        ampValidations[page] = result
J
Joe Haddad 已提交
390 391
        hadValidationError =
          hadValidationError ||
392
          (Array.isArray(result?.errors) && result.errors.length > 0)
393
      }
J
Joe Haddad 已提交
394
      renderError = renderError || !!result.error
J
JJ Kasper 已提交
395 396 397 398 399 400 401 402

      if (
        options.buildExport &&
        typeof result.fromBuildExportRevalidate !== 'undefined'
      ) {
        configuration.initialPageRevalidationMap[path] =
          result.fromBuildExportRevalidate
      }
403 404
      if (progress) progress()
    })
405
  )
406

407
  worker.end()
J
JJ Kasper 已提交
408

J
JJ Kasper 已提交
409 410 411
  // copy prerendered routes to outDir
  if (!options.buildExport && prerenderManifest) {
    await Promise.all(
J
Joe Haddad 已提交
412
      Object.keys(prerenderManifest.routes).map(async (route) => {
413
        route = normalizePagePath(route)
J
JJ Kasper 已提交
414
        const orig = join(distPagesDir, route)
415 416 417 418 419 420
        const htmlDest = join(
          outDir,
          `${route}${
            subFolders && route !== '/index' ? `${sep}index` : ''
          }.html`
        )
421 422 423 424
        const ampHtmlDest = join(
          outDir,
          `${route}.amp${subFolders ? `${sep}index` : ''}.html`
        )
425
        const jsonDest = join(pagesDataDir, `${route}.json`)
J
JJ Kasper 已提交
426

427 428 429 430
        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)
431 432

        if (await exists(`${orig}.amp.html`)) {
433 434
          await promises.mkdir(dirname(ampHtmlDest), { recursive: true })
          await promises.copyFile(`${orig}.amp.html`, ampHtmlDest)
435
        }
J
JJ Kasper 已提交
436 437 438 439
      })
    )
  }

J
JJ Kasper 已提交
440 441 442 443
  if (Object.keys(ampValidations).length) {
    console.log(formatAmpMessages(ampValidations))
  }
  if (hadValidationError) {
444 445 446
    throw new Error(
      `AMP Validation caused the export to fail. https://err.sh/zeit/next.js/amp-export-validation`
    )
J
JJ Kasper 已提交
447 448
  }

449 450 451
  if (renderError) {
    throw new Error(`Export encountered errors`)
  }
452 453
  // Add an empty line to the console for the better readability.
  log('')
454

J
Joe Haddad 已提交
455 456 457 458 459 460 461 462 463 464
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: true,
    }),
    'utf8'
  )

465 466 467
  if (telemetry) {
    await telemetry.flush()
  }
468
}