rsnext/packages/next/build/index.ts

211 lines
6.2 KiB
TypeScript
Raw Normal View History

2019-04-03 02:22:04 +02:00
import path from 'path'
import fs from 'fs'
2019-03-24 14:21:30 +01:00
import nanoid from 'next/dist/compiled/nanoid/index.js'
import loadConfig from 'next-server/next-config'
import { PHASE_PRODUCTION_BUILD } from 'next-server/constants'
import getBaseWebpackConfig from './webpack-config'
import { generateBuildId } from './generate-build-id'
import { writeBuildId } from './write-build-id'
import { isWriteable } from './is-writeable'
import { runCompiler, CompilerResult } from './compiler'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { createPagesMapping, createEntrypoints } from './entries'
import formatWebpackMessages from '../client/dev-error-overlay/format-webpack-messages'
import chalk from 'chalk'
function collectPages(
directory: string,
pageExtensions: string[]
): Promise<string[]> {
return recursiveReadDir(
directory,
new RegExp(`\\.(?:${pageExtensions.join('|')})$`)
)
Serverless Next.js (#5927) **This does not change existing behavior.** building to serverless is completely opt-in. - Implements `target: 'serverless'` in `next.config.js` - Removes `next build --lambdas` (was only available on next@canary so far) This implements the concept of build targets. Currently there will be 2 build targets: - server (This is the target that already existed / the default, no changes here) - serverless (New target aimed at compiling pages to serverless handlers) The serverless target will output a single file per `page` in the `pages` directory: - `pages/index.js` => `.next/serverless/index.js` - `pages/about.js` => `.next/serverless/about.js` So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature: ```ts (req: http.IncomingMessage, res: http.ServerResponse) => void ``` So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`: ```js const http = require('http') // Note that `.default` is needed because the exported module is an esmodule const handler = require('./.next/serverless/about.js').default const server = new http.Server((req, res) => handler(req, res)) server.listen(3000, () => console.log('Listening on http://localhost:3000')) ``` Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically. The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future. One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846 So to summarize: - every page becomes a serverless function - the serverless function has 0 dependencies (they're all inlined) - "just" uses the `req` and `res` coming from Node.js - opt-in using `target: 'serverless'` in `next.config.js` - Does not load next.config.js when executing the function TODO: - [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded. - [x] Setting `assetPrefix` at build time for serverless target - [x] Support custom /_app - [x] Support custom /_document - [x] Support custom /_error - [x] Add `next.config.js` property for `target` Need discussion: - [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar. - [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
}
function printTreeView(list: string[]) {
list
.sort((a, b) => (a > b ? 1 : -1))
.forEach((item, i) => {
const corner =
i === 0
? list.length === 1
? '─'
: '┌'
: i === list.length - 1
? '└'
: '├'
console.log(` \x1b[90m${corner}\x1b[39m ${item}`)
})
console.log()
}
2019-04-03 02:22:04 +02:00
function flatten<T>(arr: T[][]): T[] {
return arr.reduce((acc, val) => acc.concat(val), [] as T[])
}
function getPossibleFiles(pageExtensions: string[], pages: string[]) {
const res = pages.map(page =>
[page].concat(pageExtensions.map(e => `${page}.${e}`))
)
return flatten<string>(res)
}
export default async function build(
dir: string,
conf = null,
2019-04-03 02:22:04 +02:00
{ pages: _pages = [] as string[] } = {}
): Promise<void> {
if (!(await isWriteable(dir))) {
throw new Error(
'> Build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable'
)
}
const debug =
process.env.__NEXT_BUILDER_EXPERIMENTAL_DEBUG === 'true' ||
process.env.__NEXT_BUILDER_EXPERIMENTAL_DEBUG === '1'
console.log('Creating an optimized production build ...')
console.log()
const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const buildId = debug
? 'unoptimized-build'
: await generateBuildId(config.generateBuildId, nanoid)
2019-04-03 02:22:04 +02:00
const distDir = path.join(dir, config.distDir)
const pagesDir = path.join(dir, 'pages')
const pages =
Array.isArray(_pages) && _pages.length
? _pages
: process.env.__NEXT_BUILDER_EXPERIMENTAL_PAGE
? [process.env.__NEXT_BUILDER_EXPERIMENTAL_PAGE]
: []
Serverless Next.js (#5927) **This does not change existing behavior.** building to serverless is completely opt-in. - Implements `target: 'serverless'` in `next.config.js` - Removes `next build --lambdas` (was only available on next@canary so far) This implements the concept of build targets. Currently there will be 2 build targets: - server (This is the target that already existed / the default, no changes here) - serverless (New target aimed at compiling pages to serverless handlers) The serverless target will output a single file per `page` in the `pages` directory: - `pages/index.js` => `.next/serverless/index.js` - `pages/about.js` => `.next/serverless/about.js` So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature: ```ts (req: http.IncomingMessage, res: http.ServerResponse) => void ``` So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`: ```js const http = require('http') // Note that `.default` is needed because the exported module is an esmodule const handler = require('./.next/serverless/about.js').default const server = new http.Server((req, res) => handler(req, res)) server.listen(3000, () => console.log('Listening on http://localhost:3000')) ``` Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically. The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future. One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846 So to summarize: - every page becomes a serverless function - the serverless function has 0 dependencies (they're all inlined) - "just" uses the `req` and `res` coming from Node.js - opt-in using `target: 'serverless'` in `next.config.js` - Does not load next.config.js when executing the function TODO: - [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded. - [x] Setting `assetPrefix` at build time for serverless target - [x] Support custom /_app - [x] Support custom /_document - [x] Support custom /_error - [x] Add `next.config.js` property for `target` Need discussion: - [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar. - [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
const __selectivePageBuilding = pages ? Boolean(pages.length) : false
let pagePaths
if (__selectivePageBuilding) {
2019-04-03 02:22:04 +02:00
if (config.target !== 'serverless') {
throw new Error(
'Cannot use selective page building without the serverless target.'
)
}
const explodedPages = flatten<string>(pages.map(p => p.split(','))).map(
p => {
let resolvedPage: string | undefined
if (path.isAbsolute(p)) {
resolvedPage = getPossibleFiles(config.pageExtensions, [
path.join(pagesDir, p),
p,
]).find(f => fs.existsSync(f))
} else {
resolvedPage = getPossibleFiles(config.pageExtensions, [
path.join(pagesDir, p),
path.join(dir, p),
]).find(f => fs.existsSync(f))
}
return { original: p, resolved: resolvedPage || null }
}
)
const missingPage = explodedPages.find(({ resolved }) => !resolved)
if (missingPage) {
throw new Error(`Unable to identify page: ${missingPage.original}`)
}
pagePaths = explodedPages.map(
page => '/' + path.relative(pagesDir, page.resolved!)
)
} else {
pagePaths = await collectPages(pagesDir, config.pageExtensions)
}
const mappedPages = createPagesMapping(pagePaths, config.pageExtensions)
const entrypoints = createEntrypoints(
mappedPages,
config.target,
buildId,
__selectivePageBuilding,
config
)
const configs = await Promise.all([
getBaseWebpackConfig(dir, {
debug,
buildId,
isServer: false,
config,
target: config.target,
entrypoints: entrypoints.client,
__selectivePageBuilding,
}),
getBaseWebpackConfig(dir, {
debug,
buildId,
isServer: true,
config,
target: config.target,
entrypoints: entrypoints.server,
__selectivePageBuilding,
}),
])
let result: CompilerResult = { warnings: [], errors: [] }
Serverless Next.js (#5927) **This does not change existing behavior.** building to serverless is completely opt-in. - Implements `target: 'serverless'` in `next.config.js` - Removes `next build --lambdas` (was only available on next@canary so far) This implements the concept of build targets. Currently there will be 2 build targets: - server (This is the target that already existed / the default, no changes here) - serverless (New target aimed at compiling pages to serverless handlers) The serverless target will output a single file per `page` in the `pages` directory: - `pages/index.js` => `.next/serverless/index.js` - `pages/about.js` => `.next/serverless/about.js` So what is inside `.next/serverless/about.js`? All the code needed to render that specific page. It has the Node.js `http.Server` request handler function signature: ```ts (req: http.IncomingMessage, res: http.ServerResponse) => void ``` So how do you use it? Generally you **don't** want to use the below example, but for illustration purposes it's shown how the handler is called using a plain `http.Server`: ```js const http = require('http') // Note that `.default` is needed because the exported module is an esmodule const handler = require('./.next/serverless/about.js').default const server = new http.Server((req, res) => handler(req, res)) server.listen(3000, () => console.log('Listening on http://localhost:3000')) ``` Generally you'll upload this handler function to an external service like [Now v2](https://zeit.co/now-2), the `@now/next` builder will be updated to reflect these changes. This means that it'll be no longer neccesary for `@now/next` to do some of the guesswork in creating smaller handler functions. As Next.js will output the smallest possible serverless handler function automatically. The function has 0 dependencies so no node_modules are required to run it, and is generally very small. 45Kb zipped is the baseline, but I'm sure we can make it even smaller in the future. One important thing to note is that the function won't try to load `next.config.js`, so `publicRuntimeConfig` / `serverRuntimeConfig` are not supported. Reasons are outlined here: #5846 So to summarize: - every page becomes a serverless function - the serverless function has 0 dependencies (they're all inlined) - "just" uses the `req` and `res` coming from Node.js - opt-in using `target: 'serverless'` in `next.config.js` - Does not load next.config.js when executing the function TODO: - [x] Compile next/dynamic / `import()` into the function file, so that no extra files have to be uploaded. - [x] Setting `assetPrefix` at build time for serverless target - [x] Support custom /_app - [x] Support custom /_document - [x] Support custom /_error - [x] Add `next.config.js` property for `target` Need discussion: - [ ] Since the serverless target won't support `publicRuntimeConfig` / `serverRuntimeConfig` as they're runtime values. I think we should support build-time env var replacement with webpack.DefinePlugin or similar. - [ ] Serving static files with the correct cache-control, as there is no static file serving in the serverless target
2018-12-28 11:39:12 +01:00
if (config.target === 'serverless') {
if (config.publicRuntimeConfig)
throw new Error(
'Cannot use publicRuntimeConfig with target=serverless https://err.sh/zeit/next.js/serverless-publicRuntimeConfig'
)
const clientResult = await runCompiler(configs[0])
// Fail build if clientResult contains errors
if (clientResult.errors.length > 0) {
result = {
warnings: [...clientResult.warnings],
errors: [...clientResult.errors],
}
} else {
const serverResult = await runCompiler(configs[1])
result = {
warnings: [...clientResult.warnings, ...serverResult.warnings],
errors: [...clientResult.errors, ...serverResult.errors],
}
}
} else {
result = await runCompiler(configs)
}
result = formatWebpackMessages(result)
if (result.errors.length > 0) {
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (result.errors.length > 1) {
result.errors.length = 1
}
const error = result.errors.join('\n\n')
console.error(chalk.red('Failed to compile.\n'))
console.error(error)
console.error()
if (error.indexOf('private-next-pages') > -1) {
throw new Error(
'> webpack config.resolve.alias was incorrectly overriden. https://err.sh/zeit/next.js/invalid-resolve-alias'
)
}
throw new Error('> Build failed because of webpack errors')
} else if (result.warnings.length > 0) {
console.warn(chalk.yellow('Compiled with warnings.\n'))
console.warn(result.warnings.join('\n\n'))
console.warn()
} else {
console.log(chalk.green('Compiled successfully.\n'))
}
printTreeView(Object.keys(mappedPages))
await writeBuildId(distDir, buildId, __selectivePageBuilding)
}