index.ts 11.8 KB
Newer Older
1
import chalk from 'chalk'
J
Joe Haddad 已提交
2 3 4 5
import findUp from 'find-up'
import {
  copyFile as copyFileOrig,
  existsSync,
6
  exists as existsOrig,
7
  mkdir as mkdirOrig,
J
Joe Haddad 已提交
8 9 10
  readFileSync,
  writeFileSync,
} from 'fs'
11
import Worker from 'jest-worker'
J
Joe Haddad 已提交
12
import { cpus } from 'os'
13
import { dirname, join, resolve, sep } from 'path'
J
Joe Haddad 已提交
14 15 16
import { promisify } from 'util'
import { AmpPageStatus, formatAmpMessages } from '../build/output/index'
import createSpinner from '../build/spinner'
17 18 19
import { API_ROUTE } from '../lib/constants'
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
import { normalizePagePath } from '../next-server/server/normalize-page-path'
38
import { loadEnvConfig } from '../lib/load-env-config'
39

J
JJ Kasper 已提交
40
const copyFile = promisify(copyFileOrig)
41
const mkdir = promisify(mkdirOrig)
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 90 91 92 93 94 95 96 97 98
type ExportPathMap = {
  [page: string]: { page: string; query?: { [key: string]: string } }
}

export default async function(
  dir: string,
  options: any,
  configuration?: any
): Promise<void> {
  function log(message: string) {
    if (options.silent) {
      return
    }
99 100 101
    console.log(message)
  }

102
  dir = resolve(dir)
103
  const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir)
104
  const threads = options.threads || Math.max(cpus().length - 1, 1)
105
  const distDir = join(dir, nextConfig.distDir)
106 107 108 109

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

  if (telemetry) {
110
    telemetry.record(
111
      eventCliSession(PHASE_EXPORT, distDir, {
112 113 114 115 116 117
        cliCommand: 'export',
        isSrcDir: null,
        hasNowJson: !!(await findUp('now.json', { cwd: dir })),
        isCustomServer: null,
      })
    )
118 119
  }

120
  const subFolders = nextConfig.exportTrailingSlash
J
JJ Kasper 已提交
121
  const isLikeServerless = nextConfig.target !== 'server'
122

123
  log(`> using build directory: ${distDir}`)
124

125
  if (!existsSync(distDir)) {
126 127 128
    throw new Error(
      `Build directory ${distDir} does not exist. Make sure you run "next build" before running "next start" or "next export".`
    )
129 130
  }

131
  const buildId = readFileSync(join(distDir, BUILD_ID_FILE), 'utf8')
132
  const pagesManifest =
133 134 135 136 137 138
    !options.pages &&
    require(join(
      distDir,
      isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
      PAGES_MANIFEST
    ))
139

J
JJ Kasper 已提交
140 141 142 143 144 145 146 147 148 149 150 151 152
  let prerenderManifest
  try {
    prerenderManifest = require(join(distDir, PRERENDER_MANIFEST))
  } catch (_) {}

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

J
JJ Kasper 已提交
153
  const pages = options.pages || Object.keys(pagesManifest)
J
Joe Haddad 已提交
154
  const defaultPathMap: ExportPathMap = {}
155
  let hasApiRoutes = false
156 157

  for (const page of pages) {
158 159
    // _document and _app are not real pages
    // _error is exported as 404.html later on
160
    // API Routes are Node.js functions
161 162 163 164 165 166 167

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

    if (page === '/_document' || page === '/_app' || page === '/_error') {
168 169 170
      continue
    }

171 172 173 174
    // 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`.
175
    if (prerenderManifest?.dynamicRoutes[page]) {
176 177 178
      continue
    }

179 180
    defaultPathMap[page] = { page }
  }
181 182

  // Initialize the output directory
183
  const outDir = options.outdir
184 185 186 187 188 189 190

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

191
  await recursiveDelete(join(outDir))
192
  await mkdir(join(outDir, '_next', buildId), { recursive: true })
193

J
Joe Haddad 已提交
194 195 196 197 198 199 200 201 202 203
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: false,
    }),
    'utf8'
  )

204
  // Copy static directory
205
  if (!options.buildExport && existsSync(join(dir, 'static'))) {
206
    log('  copying "static" directory')
207
    await recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
208 209
  }

210
  // Copy .next/static directory
211
  if (existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))) {
212
    log('  copying "static build" directory')
213
    await recursiveCopy(
214 215
      join(distDir, CLIENT_STATIC_FILES_PATH),
      join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
216 217 218
    )
  }

219
  // Get the exportPathMap from the config file
220
  if (typeof nextConfig.exportPathMap !== 'function') {
221 222 223
    console.log(
      `> No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`
    )
J
Joe Haddad 已提交
224
    nextConfig.exportPathMap = async (defaultMap: ExportPathMap) => {
225 226
      return defaultMap
    }
227 228
  }

229 230 231 232
  // Start the rendering process
  const renderOpts = {
    dir,
    buildId,
233
    nextExport: true,
234
    env: loadEnvConfig(dir),
235
    assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
236
    distDir,
237 238
    dev: false,
    staticMarkup: false,
239
    hotReloader: null,
240
    canonicalBase: nextConfig.amp?.canonicalBase || '',
J
Joe Haddad 已提交
241
    isModern: nextConfig.experimental.modern,
242
    ampValidatorPath: nextConfig.experimental.amp?.validator || undefined,
243 244
    ampSkipValidation: nextConfig.experimental.amp?.skipValidation || false,
    ampOptimizerConfig: nextConfig.experimental.amp?.optimizer || undefined,
245 246
  }

247
  const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
248

249
  if (Object.keys(publicRuntimeConfig).length > 0) {
J
Joe Haddad 已提交
250
    ;(renderOpts as any).runtimeConfig = publicRuntimeConfig
251 252
  }

253
  // We need this for server rendering the Link component.
J
Joe Haddad 已提交
254 255
  ;(global as any).__NEXT_DATA__ = {
    nextExport: true,
256 257
  }

258
  log(`  launching ${threads} workers`)
259 260 261 262 263
  const exportPathMap = await nextConfig.exportPathMap(defaultPathMap, {
    dev: false,
    dir,
    outDir,
    distDir,
J
Joe Haddad 已提交
264
    buildId,
265
  })
266 267
  if (!exportPathMap['/404'] && !exportPathMap['/404.html']) {
    exportPathMap['/404'] = exportPathMap['/404.html'] = {
J
Joe Haddad 已提交
268
      page: '/_error',
269
    }
270
  }
271
  const exportPaths = Object.keys(exportPathMap)
272 273 274 275
  const filteredPaths = exportPaths.filter(
    // Remove API routes
    route => !exportPathMap[route].page.match(API_ROUTE)
  )
276 277 278 279

  if (filteredPaths.length !== exportPaths.length) {
    hasApiRoutes = true
  }
280 281 282 283

  // Warn if the user defines a path for an API page
  if (hasApiRoutes) {
    log(
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
      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`
300 301
    )
  }
302

303
  const progress = !options.silent && createProgress(filteredPaths.length)
304
  const pagesDataDir = options.buildExport
J
JJ Kasper 已提交
305 306
    ? outDir
    : join(outDir, '_next/data', buildId)
A
Arunoda Susiripala 已提交
307

J
Joe Haddad 已提交
308
  const ampValidations: AmpPageStatus = {}
J
JJ Kasper 已提交
309 310
  let hadValidationError = false

311 312
  const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
  // Copy public directory
313
  if (!options.buildExport && existsSync(publicDir)) {
314
    log('  copying "public" directory')
315
    await recursiveCopy(publicDir, outDir, {
J
Joe Haddad 已提交
316
      filter(path) {
317
        // Exclude paths used by pages
318
        return !exportPathMap[path]
J
Joe Haddad 已提交
319
      },
320
    })
321
  }
322

J
Joe Haddad 已提交
323 324 325 326 327
  const worker: Worker & { default: Function } = new Worker(
    require.resolve('./worker'),
    {
      maxRetries: 0,
      numWorkers: threads,
328
      enableWorkerThreads: nextConfig.experimental.workerThreads,
J
Joe Haddad 已提交
329 330 331
      exposedMethods: ['default'],
    }
  ) as any
332 333 334 335 336

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

  let renderError = false
337

338
  await Promise.all(
339 340 341 342 343 344 345
    filteredPaths.map(async path => {
      const result = await worker.default({
        path,
        pathMap: exportPathMap[path],
        distDir,
        buildId,
        outDir,
346
        pagesDataDir,
347 348 349
        renderOpts,
        serverRuntimeConfig,
        subFolders,
J
JJ Kasper 已提交
350
        buildExport: options.buildExport,
J
Joe Haddad 已提交
351
        serverless: isTargetLikeServerless(nextConfig.target),
352 353 354 355 356
      })

      for (const validation of result.ampValidations || []) {
        const { page, result } = validation
        ampValidations[page] = result
J
Joe Haddad 已提交
357 358
        hadValidationError =
          hadValidationError ||
359
          (Array.isArray(result?.errors) && result.errors.length > 0)
360
      }
J
Joe Haddad 已提交
361
      renderError = renderError || !!result.error
J
JJ Kasper 已提交
362 363 364 365 366 367 368 369

      if (
        options.buildExport &&
        typeof result.fromBuildExportRevalidate !== 'undefined'
      ) {
        configuration.initialPageRevalidationMap[path] =
          result.fromBuildExportRevalidate
      }
370 371
      if (progress) progress()
    })
372
  )
373

374
  worker.end()
J
JJ Kasper 已提交
375

J
JJ Kasper 已提交
376 377 378 379
  // copy prerendered routes to outDir
  if (!options.buildExport && prerenderManifest) {
    await Promise.all(
      Object.keys(prerenderManifest.routes).map(async route => {
380
        route = normalizePagePath(route)
J
JJ Kasper 已提交
381
        const orig = join(distPagesDir, route)
382 383 384 385 386 387
        const htmlDest = join(
          outDir,
          `${route}${
            subFolders && route !== '/index' ? `${sep}index` : ''
          }.html`
        )
388 389 390 391
        const ampHtmlDest = join(
          outDir,
          `${route}.amp${subFolders ? `${sep}index` : ''}.html`
        )
392
        const jsonDest = join(pagesDataDir, `${route}.json`)
J
JJ Kasper 已提交
393

394 395
        await mkdir(dirname(htmlDest), { recursive: true })
        await mkdir(dirname(jsonDest), { recursive: true })
J
JJ Kasper 已提交
396 397
        await copyFile(`${orig}.html`, htmlDest)
        await copyFile(`${orig}.json`, jsonDest)
398 399 400 401 402

        if (await exists(`${orig}.amp.html`)) {
          await mkdir(dirname(ampHtmlDest), { recursive: true })
          await copyFile(`${orig}.amp.html`, ampHtmlDest)
        }
J
JJ Kasper 已提交
403 404 405 406
      })
    )
  }

J
JJ Kasper 已提交
407 408 409 410
  if (Object.keys(ampValidations).length) {
    console.log(formatAmpMessages(ampValidations))
  }
  if (hadValidationError) {
411 412 413
    throw new Error(
      `AMP Validation caused the export to fail. https://err.sh/zeit/next.js/amp-export-validation`
    )
J
JJ Kasper 已提交
414 415
  }

416 417 418
  if (renderError) {
    throw new Error(`Export encountered errors`)
  }
419 420
  // Add an empty line to the console for the better readability.
  log('')
421

J
Joe Haddad 已提交
422 423 424 425 426 427 428 429 430 431
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: true,
    }),
    'utf8'
  )

432 433 434
  if (telemetry) {
    await telemetry.flush()
  }
435
}