index.ts 10.4 KB
Newer Older
1
import chalk from 'chalk'
J
Joe Haddad 已提交
2 3 4 5 6 7 8
import findUp from 'find-up'
import {
  copyFile as copyFileOrig,
  existsSync,
  readFileSync,
  writeFileSync,
} from 'fs'
9
import Worker from 'jest-worker'
10
import mkdirpModule from 'mkdirp'
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 17 18
import { API_ROUTE } from '../lib/constants'
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'
J
Joe Haddad 已提交
34 35
import { eventVersion } from '../telemetry/events'
import { Telemetry } from '../telemetry/storage'
36 37

const mkdirp = promisify(mkdirpModule)
J
JJ Kasper 已提交
38
const copyFile = promisify(copyFileOrig)
39

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

  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 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94
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
    }
95 96 97
    console.log(message)
  }

98
  dir = resolve(dir)
99
  const nextConfig = configuration || loadConfig(PHASE_EXPORT, dir)
100
  const threads = options.threads || Math.max(cpus().length - 1, 1)
101
  const distDir = join(dir, nextConfig.distDir)
102 103 104 105

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

  if (telemetry) {
106 107 108 109 110 111 112 113
    telemetry.record(
      eventVersion({
        cliCommand: 'export',
        isSrcDir: null,
        hasNowJson: !!(await findUp('now.json', { cwd: dir })),
        isCustomServer: null,
      })
    )
114 115
  }

116
  const subFolders = nextConfig.exportTrailingSlash
J
JJ Kasper 已提交
117
  const isLikeServerless = nextConfig.target !== 'server'
118

119
  log(`> using build directory: ${distDir}`)
120

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

127
  const buildId = readFileSync(join(distDir, BUILD_ID_FILE), 'utf8')
128
  const pagesManifest =
129 130 131 132 133 134
    !options.pages &&
    require(join(
      distDir,
      isLikeServerless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY,
      PAGES_MANIFEST
    ))
135

J
JJ Kasper 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148
  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 已提交
149
  const pages = options.pages || Object.keys(pagesManifest)
J
Joe Haddad 已提交
150
  const defaultPathMap: ExportPathMap = {}
151 152

  for (const page of pages) {
153 154
    // _document and _app are not real pages
    // _error is exported as 404.html later on
155
    // API Routes are Node.js functions
156 157 158 159
    if (
      page === '/_document' ||
      page === '/_app' ||
      page === '/_error' ||
160
      page.match(API_ROUTE)
161
    ) {
162 163 164
      continue
    }

165 166 167 168
    // 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`.
169
    if (prerenderManifest?.dynamicRoutes[page]) {
170 171 172
      continue
    }

173 174
    defaultPathMap[page] = { page }
  }
175 176

  // Initialize the output directory
177
  const outDir = options.outdir
178 179 180 181 182 183 184

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

185
  await recursiveDelete(join(outDir))
186 187
  await mkdirp(join(outDir, '_next', buildId))

J
Joe Haddad 已提交
188 189 190 191 192 193 194 195 196 197
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: false,
    }),
    'utf8'
  )

198
  // Copy static directory
199
  if (!options.buildExport && existsSync(join(dir, 'static'))) {
200
    log('  copying "static" directory')
201
    await recursiveCopy(join(dir, 'static'), join(outDir, 'static'))
202 203
  }

204
  // Copy .next/static directory
205
  if (existsSync(join(distDir, CLIENT_STATIC_FILES_PATH))) {
206
    log('  copying "static build" directory')
207
    await recursiveCopy(
208 209
      join(distDir, CLIENT_STATIC_FILES_PATH),
      join(outDir, '_next', CLIENT_STATIC_FILES_PATH)
210 211 212
    )
  }

213
  // Get the exportPathMap from the config file
214
  if (typeof nextConfig.exportPathMap !== 'function') {
215 216 217
    console.log(
      `> No "exportPathMap" found in "${CONFIG_FILE}". Generating map from "./pages"`
    )
J
Joe Haddad 已提交
218
    nextConfig.exportPathMap = async (defaultMap: ExportPathMap) => {
219 220
      return defaultMap
    }
221 222
  }

223 224 225 226
  // Start the rendering process
  const renderOpts = {
    dir,
    buildId,
227
    nextExport: true,
228
    assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
229
    distDir,
230 231
    dev: false,
    staticMarkup: false,
232
    hotReloader: null,
233
    canonicalBase: nextConfig.amp?.canonicalBase || '',
J
Joe Haddad 已提交
234
    isModern: nextConfig.experimental.modern,
235
    ampValidator: nextConfig.experimental.amp?.validator || undefined,
236 237
  }

238
  const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
239

240
  if (Object.keys(publicRuntimeConfig).length > 0) {
J
Joe Haddad 已提交
241
    ;(renderOpts as any).runtimeConfig = publicRuntimeConfig
242 243
  }

244
  // We need this for server rendering the Link component.
J
Joe Haddad 已提交
245 246
  ;(global as any).__NEXT_DATA__ = {
    nextExport: true,
247 248
  }

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

  // Warn if the user defines a path for an API page
  if (hasApiRoutes) {
    log(
      chalk.yellow(
        '  API pages are not supported by next export. https://err.sh/zeit/next.js/api-routes-static-export'
      )
    )
  }
277

278
  const progress = !options.silent && createProgress(filteredPaths.length)
279
  const pagesDataDir = options.buildExport
J
JJ Kasper 已提交
280 281
    ? outDir
    : join(outDir, '_next/data', buildId)
A
Arunoda Susiripala 已提交
282

J
Joe Haddad 已提交
283
  const ampValidations: AmpPageStatus = {}
J
JJ Kasper 已提交
284 285
  let hadValidationError = false

286 287
  const publicDir = join(dir, CLIENT_PUBLIC_FILES_PATH)
  // Copy public directory
288
  if (!options.buildExport && existsSync(publicDir)) {
289
    log('  copying "public" directory')
290
    await recursiveCopy(publicDir, outDir, {
J
Joe Haddad 已提交
291
      filter(path) {
292
        // Exclude paths used by pages
293
        return !exportPathMap[path]
J
Joe Haddad 已提交
294
      },
295
    })
296
  }
297

J
Joe Haddad 已提交
298 299 300 301 302
  const worker: Worker & { default: Function } = new Worker(
    require.resolve('./worker'),
    {
      maxRetries: 0,
      numWorkers: threads,
303
      enableWorkerThreads: nextConfig.experimental.workerThreads,
J
Joe Haddad 已提交
304 305 306
      exposedMethods: ['default'],
    }
  ) as any
307 308 309 310 311

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

  let renderError = false
312

313
  await Promise.all(
314 315 316 317 318 319 320
    filteredPaths.map(async path => {
      const result = await worker.default({
        path,
        pathMap: exportPathMap[path],
        distDir,
        buildId,
        outDir,
321
        pagesDataDir,
322 323 324
        renderOpts,
        serverRuntimeConfig,
        subFolders,
J
JJ Kasper 已提交
325
        buildExport: options.buildExport,
J
Joe Haddad 已提交
326
        serverless: isTargetLikeServerless(nextConfig.target),
327 328 329 330 331
      })

      for (const validation of result.ampValidations || []) {
        const { page, result } = validation
        ampValidations[page] = result
J
Joe Haddad 已提交
332 333
        hadValidationError =
          hadValidationError ||
334
          (Array.isArray(result?.errors) && result.errors.length > 0)
335
      }
J
Joe Haddad 已提交
336
      renderError = renderError || !!result.error
J
JJ Kasper 已提交
337 338 339 340 341 342 343 344

      if (
        options.buildExport &&
        typeof result.fromBuildExportRevalidate !== 'undefined'
      ) {
        configuration.initialPageRevalidationMap[path] =
          result.fromBuildExportRevalidate
      }
345 346
      if (progress) progress()
    })
347
  )
348

349
  worker.end()
J
JJ Kasper 已提交
350

J
JJ Kasper 已提交
351 352 353 354
  // copy prerendered routes to outDir
  if (!options.buildExport && prerenderManifest) {
    await Promise.all(
      Object.keys(prerenderManifest.routes).map(async route => {
J
JJ Kasper 已提交
355
        route = route === '/' ? '/index' : route
J
JJ Kasper 已提交
356
        const orig = join(distPagesDir, route)
357 358 359 360 361 362
        const htmlDest = join(
          outDir,
          `${route}${
            subFolders && route !== '/index' ? `${sep}index` : ''
          }.html`
        )
363
        const jsonDest = join(pagesDataDir, `${route}.json`)
J
JJ Kasper 已提交
364 365 366 367 368 369 370 371 372

        await mkdirp(dirname(htmlDest))
        await mkdirp(dirname(jsonDest))
        await copyFile(`${orig}.html`, htmlDest)
        await copyFile(`${orig}.json`, jsonDest)
      })
    )
  }

J
JJ Kasper 已提交
373 374 375 376
  if (Object.keys(ampValidations).length) {
    console.log(formatAmpMessages(ampValidations))
  }
  if (hadValidationError) {
377 378 379
    throw new Error(
      `AMP Validation caused the export to fail. https://err.sh/zeit/next.js/amp-export-validation`
    )
J
JJ Kasper 已提交
380 381
  }

382 383 384
  if (renderError) {
    throw new Error(`Export encountered errors`)
  }
385 386
  // Add an empty line to the console for the better readability.
  log('')
387

J
Joe Haddad 已提交
388 389 390 391 392 393 394 395 396 397
  writeFileSync(
    join(distDir, EXPORT_DETAIL),
    JSON.stringify({
      version: 1,
      outDirectory: outDir,
      success: true,
    }),
    'utf8'
  )

398 399 400
  if (telemetry) {
    await telemetry.flush()
  }
401
}