Nuxt/packages/nitro/src/build.ts

52 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 { getTargetConfig, SLSConfig } from './config'
2020-11-04 12:34:18 +00:00
export async function build (baseConfig, target) {
2020-11-05 11:28:39 +00:00
console.log('\n')
2020-11-04 12:34:18 +00:00
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)
2020-11-05 11:28:39 +00:00
emptyDir(config.targetDir)
2020-11-04 12:34:18 +00:00
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) {
2020-11-05 11:28:39 +00:00
const dstPath = resolve(config.targetDir, tmpl.dst)
2020-11-04 12:34:18 +00:00
await renderTemplate(tmpl.src, dstPath, { config })
consola.info('Compiled', prettyPath(dstPath))
}
await hooks.callHook('done', config)
}
export async function compileHTMLTemplate (baseConfig: SLSConfig) {
2020-11-04 12:34:18 +00:00
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))
}