Nuxt/packages/nitro/src/build.ts

74 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-11-04 12:34:18 +00:00
import { resolve } from 'path'
import consola from 'consola'
import { rollup, OutputOptions } from 'rollup'
import Hookable from 'hookable'
import prettyBytes from 'pretty-bytes'
import gzipSize from 'gzip-size'
import chalk from 'chalk'
2020-11-04 19:01:53 +00:00
import { copy, emptyDir, existsSync, mkdirp } from 'fs-extra'
2020-11-04 12:34:18 +00:00
import { getRollupConfig } from './rollup/config'
2020-11-04 13:15:38 +00:00
import { getTargetConfig } from './config'
import { hl, prettyPath, renderTemplate, compileTemplateToJS } from './utils'
2020-11-04 12:34:18 +00:00
export async function build (baseConfig, target) {
consola.info(`Generating bundle for ${hl(target.target)}`)
2020-11-04 13:15:38 +00:00
const config: any = getTargetConfig(baseConfig, target)
2020-11-04 12:34:18 +00:00
const hooks = new Hookable()
hooks.addHooks(config.hooks)
await hooks.callHook('config', config)
emptyDir(config.outDir)
config.rollupConfig = getRollupConfig(config)
await hooks.callHook('rollup:before', config)
const build = await rollup(config.rollupConfig)
const { output } = await build.write(config.rollupConfig.output as OutputOptions)
const size = prettyBytes(output[0].code.length)
const zSize = prettyBytes(await gzipSize(output[0].code))
consola.success('Generated', prettyPath((config.rollupConfig.output as any).file),
chalk.gray(`(Size: ${size} Gzip: ${zSize})`)
)
for (const tmpl of config.templates) {
const dstPath = resolve(config.outDir, tmpl.dst)
await renderTemplate(tmpl.src, dstPath, { config })
consola.info('Compiled', prettyPath(dstPath))
}
await hooks.callHook('done', config)
}
export async function compileHTMLTemplate (baseConfig) {
const htmlTemplateFile = resolve(baseConfig.buildDir, `views/${{ 2: 'app', 3: 'document' }[baseConfig.nuxt]}.template.html`)
const htmlTemplateFileJS = htmlTemplateFile.replace(/.html$/, '.js').replace('app.', 'document.')
await compileTemplateToJS(htmlTemplateFile, htmlTemplateFileJS)
consola.info('Generated', prettyPath(htmlTemplateFileJS))
}
export function ensureDist (baseConfig) {
if (!existsSync(resolve(baseConfig.buildDir, 'dist/server'))) {
return consola.error('Please use `nuxt build` first to build project!')
} else {
consola.success('Using existing nuxt build from', prettyPath(baseConfig.buildDir))
}
}
2020-11-04 19:01:53 +00:00
export async function generatePublic (baseConfig) {
await emptyDir(baseConfig.publicDir)
await mkdirp(baseConfig.publicDir)
await copy(
baseConfig.staticDir,
baseConfig.publicDir
)
await copy(
resolve(baseConfig.buildDir, 'dist/client'),
resolve(baseConfig.publicDir, '_nuxt')
)
}