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-06 09:51:35 +00:00
|
|
|
import { emptyDir, readFile } from 'fs-extra'
|
2020-11-04 12:34:18 +00:00
|
|
|
import { getRollupConfig } from './rollup/config'
|
2020-11-10 18:19:24 +00:00
|
|
|
import { hl, prettyPath, serializeTemplate, writeFile } from './utils'
|
2020-11-05 13:38:15 +00:00
|
|
|
import { SLSOptions } from './config'
|
2020-11-04 12:34:18 +00:00
|
|
|
|
2020-11-05 13:38:15 +00:00
|
|
|
export async function build (options: SLSOptions) {
|
2020-11-05 11:28:39 +00:00
|
|
|
console.log('\n')
|
2020-11-05 13:38:15 +00:00
|
|
|
consola.info(`Generating bundle for ${hl(options.target)}`)
|
2020-11-04 12:34:18 +00:00
|
|
|
|
|
|
|
const hooks = new Hookable()
|
2020-11-05 13:38:15 +00:00
|
|
|
hooks.addHooks(options.hooks)
|
2020-11-04 12:34:18 +00:00
|
|
|
|
2020-11-05 21:56:40 +00:00
|
|
|
// Compile html template
|
2020-11-06 13:46:17 +00:00
|
|
|
const htmlSrc = resolve(options.buildDir, `views/${{ 2: 'app', 3: 'document' }[2]}.template.html`)
|
2020-11-06 09:51:35 +00:00
|
|
|
const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' }
|
2020-11-05 21:56:40 +00:00
|
|
|
htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.')
|
2020-11-06 09:51:35 +00:00
|
|
|
htmlTemplate.contents = await readFile(htmlTemplate.src, 'utf-8')
|
2020-11-06 11:50:45 +00:00
|
|
|
htmlTemplate.compiled = serializeTemplate(htmlTemplate.contents)
|
2020-11-05 21:56:40 +00:00
|
|
|
await hooks.callHook('template:document', htmlTemplate)
|
2020-11-10 18:19:24 +00:00
|
|
|
await writeFile(htmlTemplate.dst, htmlTemplate.compiled)
|
2020-11-04 12:34:18 +00:00
|
|
|
|
2020-11-11 14:06:20 +00:00
|
|
|
if (options.targetDir.startsWith(options.slsDir)) {
|
|
|
|
emptyDir(options.slsDir)
|
|
|
|
}
|
2020-11-04 12:34:18 +00:00
|
|
|
|
2020-11-05 13:38:15 +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
|
|
|
|
2020-11-05 13:38:15 +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))
|
2020-11-05 13:38:15 +00:00
|
|
|
consola.success('Generated', prettyPath((options.rollupConfig.output as any).file),
|
2020-11-04 12:34:18 +00:00
|
|
|
chalk.gray(`(Size: ${size} Gzip: ${zSize})`)
|
|
|
|
)
|
|
|
|
|
2020-11-05 13:38:15 +00:00
|
|
|
await hooks.callHook('done', options)
|
2020-11-04 12:34:18 +00:00
|
|
|
}
|