Nuxt/packages/nitro/src/build.ts

54 lines
1.9 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-05 11:28:39 +00:00
import { emptyDir } 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 { hl, prettyPath, renderTemplate, compileTemplateToJS } from './utils'
import { SLSOptions } from './config'
2020-11-04 12:34:18 +00:00
export async function build (options: SLSOptions) {
2020-11-05 11:28:39 +00:00
console.log('\n')
consola.info(`Generating bundle for ${hl(options.target)}`)
2020-11-04 12:34:18 +00:00
const hooks = new Hookable()
hooks.addHooks(options.hooks)
2020-11-04 12:34:18 +00:00
await hooks.callHook('options', options)
2020-11-04 12:34:18 +00:00
2020-11-05 21:24:36 +00:00
emptyDir(options.slsDir)
2020-11-04 12:34:18 +00:00
options.rollupConfig = getRollupConfig(options)
await hooks.callHook('rollup:before', options)
const build = await rollup(options.rollupConfig)
2020-11-04 12:34:18 +00:00
const { output } = await build.write(options.rollupConfig.output as OutputOptions)
2020-11-04 12:34:18 +00:00
const size = prettyBytes(output[0].code.length)
const zSize = prettyBytes(await gzipSize(output[0].code))
consola.success('Generated', prettyPath((options.rollupConfig.output as any).file),
2020-11-04 12:34:18 +00:00
chalk.gray(`(Size: ${size} Gzip: ${zSize})`)
)
for (const tmpl of options.templates) {
let dst = tmpl.dst
if (typeof dst === 'function') {
dst = dst(options)
}
const dstPath = resolve(options.targetDir, dst)
await renderTemplate(tmpl.src, dstPath, { options })
2020-11-04 12:34:18 +00:00
consola.info('Compiled', prettyPath(dstPath))
}
await hooks.callHook('done', options)
2020-11-04 12:34:18 +00:00
}
export async function compileHTMLTemplate (options: SLSOptions) {
const htmlTemplateFile = resolve(options.buildDir, `views/${{ 2: 'app', 3: 'document' }[options.nuxt]}.template.html`)
2020-11-04 12:34:18 +00:00
const htmlTemplateFileJS = htmlTemplateFile.replace(/.html$/, '.js').replace('app.', 'document.')
await compileTemplateToJS(htmlTemplateFile, htmlTemplateFileJS)
consola.info('Generated', prettyPath(htmlTemplateFileJS))
}