refactor: simplify usage with single target

This commit is contained in:
Pooya Parsa 2020-11-05 14:38:15 +01:00
parent d4624abfb9
commit 8f5534c90a
4 changed files with 63 additions and 86 deletions

View File

@ -8,43 +8,41 @@ import chalk from 'chalk'
import { emptyDir } from 'fs-extra' import { emptyDir } from 'fs-extra'
import { getRollupConfig } from './rollup/config' import { getRollupConfig } from './rollup/config'
import { hl, prettyPath, renderTemplate, compileTemplateToJS } from './utils' import { hl, prettyPath, renderTemplate, compileTemplateToJS } from './utils'
import { getTargetConfig, SLSConfig } from './config' import { SLSOptions } from './config'
export async function build (baseConfig, target) { export async function build (options: SLSOptions) {
console.log('\n') console.log('\n')
consola.info(`Generating bundle for ${hl(target.target)}`) consola.info(`Generating bundle for ${hl(options.target)}`)
const config: any = getTargetConfig(baseConfig, target)
const hooks = new Hookable() const hooks = new Hookable()
hooks.addHooks(config.hooks) hooks.addHooks(options.hooks)
await hooks.callHook('config', config) await hooks.callHook('options', options)
emptyDir(config.targetDir) emptyDir(options.targetDir)
config.rollupConfig = getRollupConfig(config) options.rollupConfig = getRollupConfig(options)
await hooks.callHook('rollup:before', config) await hooks.callHook('rollup:before', options)
const build = await rollup(config.rollupConfig) const build = await rollup(options.rollupConfig)
const { output } = await build.write(config.rollupConfig.output as OutputOptions) const { output } = await build.write(options.rollupConfig.output as OutputOptions)
const size = prettyBytes(output[0].code.length) const size = prettyBytes(output[0].code.length)
const zSize = prettyBytes(await gzipSize(output[0].code)) const zSize = prettyBytes(await gzipSize(output[0].code))
consola.success('Generated', prettyPath((config.rollupConfig.output as any).file), consola.success('Generated', prettyPath((options.rollupConfig.output as any).file),
chalk.gray(`(Size: ${size} Gzip: ${zSize})`) chalk.gray(`(Size: ${size} Gzip: ${zSize})`)
) )
for (const tmpl of config.templates) { for (const tmpl of options.templates) {
const dstPath = resolve(config.targetDir, tmpl.dst) const dstPath = resolve(options.targetDir, tmpl.dst)
await renderTemplate(tmpl.src, dstPath, { config }) await renderTemplate(tmpl.src, dstPath, { options })
consola.info('Compiled', prettyPath(dstPath)) consola.info('Compiled', prettyPath(dstPath))
} }
await hooks.callHook('done', config) await hooks.callHook('done', options)
} }
export async function compileHTMLTemplate (baseConfig: SLSConfig) { export async function compileHTMLTemplate (options: SLSOptions) {
const htmlTemplateFile = resolve(baseConfig.buildDir, `views/${{ 2: 'app', 3: 'document' }[baseConfig.nuxt]}.template.html`) const htmlTemplateFile = resolve(options.buildDir, `views/${{ 2: 'app', 3: 'document' }[options.nuxt]}.template.html`)
const htmlTemplateFileJS = htmlTemplateFile.replace(/.html$/, '.js').replace('app.', 'document.') const htmlTemplateFileJS = htmlTemplateFile.replace(/.html$/, '.js').replace('app.', 'document.')
await compileTemplateToJS(htmlTemplateFile, htmlTemplateFileJS) await compileTemplateToJS(htmlTemplateFile, htmlTemplateFileJS)
consola.info('Generated', prettyPath(htmlTemplateFileJS)) consola.info('Generated', prettyPath(htmlTemplateFileJS))

View File

@ -3,77 +3,61 @@ import defu from 'defu'
import { NuxtOptions } from '@nuxt/types' import { NuxtOptions } from '@nuxt/types'
import { tryImport, LIB_DIR } from './utils' import { tryImport, LIB_DIR } from './utils'
export interface SLSConfig { export interface SLSOptions {
node: false node: false
target: 'vercel' | 'cloudflare' | 'node' | 'sw' | string
entry: string entry: string
outDir: string outDir: string
slsDir: string slsDir: string
outName: string outName: string
logStartup: boolean logStartup: boolean
inlineChunks: boolean
buildDir: string buildDir: string
publicDir: string publicDir: string
staticDir: string staticDir: string
targetDir: string
rootDir: string rootDir: string
targets: ((SLSConfig & { target: string }) | string)[] templates: { src: string, dst: string }[]
target: string static: string[]
templates: string[]
renderer: string renderer: string
nuxt: 2 | 3 nuxt: 2 | 3
analyze: boolean analyze: boolean
minify: boolean minify: boolean
rollupConfig?: any
hooks: { [key: string]: any } // TODO: export from hookable
} }
export function getBaseConfig (options: NuxtOptions): SLSConfig { export interface SLSConfig extends Partial<SLSOptions> {}
const baseConfig = {
rootDir: options.rootDir, export function getoptions (nuxtOptions: NuxtOptions): SLSOptions {
buildDir: options.buildDir, const defaults: SLSConfig = {
publicDir: options.generate.dir, rootDir: nuxtOptions.rootDir,
slsDir: null, buildDir: nuxtOptions.buildDir,
targets: [], publicDir: nuxtOptions.generate.dir,
outName: 'index.js',
templates: [], templates: [],
static: [ static: [],
'/about'
],
nuxt: 2, nuxt: 2,
target: null,
minify: null,
analyze: null,
logStartup: true, logStartup: true,
...options.serverless inlineChunks: false
} }
baseConfig.buildDir = resolve(baseConfig.rootDir, baseConfig.buildDir || '.nuxt') let target = nuxtOptions.serverless.target || process.env.SLS_TARGET || 'node'
baseConfig.publicDir = resolve(baseConfig.rootDir, baseConfig.publicDir || 'dist') if (typeof target === 'function') {
baseConfig.slsDir = resolve(baseConfig.rootDir, baseConfig.slsDir || '.sls') target = target(nuxtOptions)
}
baseConfig.targets = baseConfig.targets.map(t => typeof t === 'string' ? { target: t } : t) let targetDefaults = tryImport(LIB_DIR, `./targets/${target}`) || tryImport(nuxtOptions.rootDir, target)
if (baseConfig.target && !baseConfig.targets.find(t => t.target === baseConfig.target)) { targetDefaults = targetDefaults.default || targetDefaults
baseConfig.targets.push({ target: baseConfig.target }) if (!targetDefaults) {
throw new Error('Cannot resolve target: ' + target)
} }
return baseConfig const options: SLSOptions = defu(nuxtOptions.serverless, targetDefaults, defaults, { target })
}
options.buildDir = resolve(options.rootDir, options.buildDir || '.nuxt')
export function getTargetConfig (baseConfig: SLSConfig, target: SLSConfig) { options.publicDir = resolve(options.rootDir, options.publicDir || 'dist')
const _targetDefaults = tryImport(LIB_DIR, `./targets/${target.target}`) || options.slsDir = resolve(options.rootDir, options.slsDir || '.sls')
tryImport(baseConfig.rootDir, target.target) options.targetDir = resolve(options.slsDir, target)
if (!_targetDefaults) {
throw new Error('Cannot resolve target: ' + target.target) return options
}
// TODO: Merge hooks
return defu(
// Target specific config by user
target,
// Global user config
baseConfig,
// Target defaults
_targetDefaults,
// Generic defaults
{
targetDir: resolve(baseConfig.slsDir, target.target),
outName: 'index.js'
}
)
} }

View File

@ -1,6 +1,6 @@
import type { Module } from '@nuxt/types' import type { Module } from '@nuxt/types'
import { build, compileHTMLTemplate } from './build' import { build, compileHTMLTemplate } from './build'
import { getBaseConfig } from './config' import { getoptions } from './config'
export default <Module> function slsModule () { export default <Module> function slsModule () {
const { nuxt } = this const { nuxt } = this
@ -10,37 +10,32 @@ export default <Module> function slsModule () {
} }
// Config // Config
const baseConfig = getBaseConfig(nuxt.options) const options = getoptions(nuxt.options)
if (baseConfig.minify !== false) { if (options.minify !== false) {
nuxt.options.build._minifyServer = true nuxt.options.build._minifyServer = true
} }
nuxt.options.build.standalone = true nuxt.options.build.standalone = true
nuxt.hook('generate:cache:ignore', (ignore) => { nuxt.hook('generate:cache:ignore', (ignore) => {
ignore.push(baseConfig.slsDir) ignore.push(options.slsDir)
}) })
nuxt.hook('generate:page', (page) => { nuxt.hook('generate:page', (page) => {
// TODO: Use ssrContext // TODO: Use ssrContext
if (!baseConfig.static.includes(page.route)) { if (!options.static.includes(page.route)) {
page.exclude = true page.exclude = true
} }
}) })
nuxt.hook('generate:done', () => buildSLS(baseConfig)) nuxt.hook('generate:done', () => buildSLS(options))
} }
async function buildSLS (baseConfig) { async function buildSLS (options) {
// Compile html template // Compile html template
await compileHTMLTemplate(baseConfig) await compileHTMLTemplate(options)
// Bundle for each target // Bundle target
for (const target of baseConfig.targets) { await build(options)
if (baseConfig.target && target.target !== baseConfig.target) {
continue
}
await build(baseConfig, target)
}
} }

View File

@ -9,13 +9,13 @@ import json from '@rollup/plugin-json'
import replace from '@rollup/plugin-replace' import replace from '@rollup/plugin-replace'
import analyze from 'rollup-plugin-analyzer' import analyze from 'rollup-plugin-analyzer'
import { SLSConfig } from '../config' import { SLSOptions } from '../config'
import { RUNTIME_DIR } from '../utils' import { RUNTIME_DIR } from '../utils'
import dynamicRequire from './dynamic-require' import dynamicRequire from './dynamic-require'
export type RollupConfig = InputOptions & { output: OutputOptions } export type RollupConfig = InputOptions & { output: OutputOptions }
export const getRollupConfig = (config: SLSConfig) => { export const getRollupConfig = (config: SLSOptions) => {
const mocks = [ const mocks = [
// @nuxt/devalue // @nuxt/devalue
'consola', 'consola',