improve config extending

This commit is contained in:
Pooya Parsa 2020-11-06 14:46:17 +01:00
parent 91caf2c470
commit 3fa6717882
6 changed files with 88 additions and 84 deletions

View File

@ -18,7 +18,7 @@ export async function build (options: SLSOptions) {
hooks.addHooks(options.hooks) hooks.addHooks(options.hooks)
// Compile html template // Compile html template
const htmlSrc = resolve(options.buildDir, `views/${{ 2: 'app', 3: 'document' }[options.nuxt]}.template.html`) const htmlSrc = resolve(options.buildDir, `views/${{ 2: 'app', 3: 'document' }[2]}.template.html`)
const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' } const htmlTemplate = { src: htmlSrc, contents: '', dst: '', compiled: '' }
htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.') htmlTemplate.dst = htmlTemplate.src.replace(/.html$/, '.js').replace('app.', 'document.')
htmlTemplate.contents = await readFile(htmlTemplate.src, 'utf-8') htmlTemplate.contents = await readFile(htmlTemplate.src, 'utf-8')

View File

@ -1,86 +1,87 @@
import { resolve } from 'path' import { resolve } from 'path'
import defu from 'defu' import defu from 'defu'
import type { NuxtOptions } from '@nuxt/types' import type { NuxtOptions } from '@nuxt/types'
import { tryImport, resolvePath, detectTarget } from './utils' import Hookable, { configHooksT } from 'hookable'
import { tryImport, resolvePath, detectTarget, extendTarget } from './utils'
import * as TARGETS from './targets' import * as TARGETS from './targets'
export type UnresolvedPath = string | ((SLSOptions) => string) export type UnresolvedPath = string | ((SLSOptions) => string)
export interface Nuxt extends Hookable{
options: NuxtOptions
}
export interface SLSOptions { export interface SLSOptions {
nuxtOptions: NuxtOptions hooks: configHooksT
node: false nuxtHooks: configHooksT
target: string
entry: UnresolvedPath rootDir: string
slsDir: string
outName: string
logStartup: boolean
inlineChunks: boolean
buildDir: string buildDir: string
publicDir: string publicDir: string
staticDir: string routerBase: string
targetDir: string fullStatic: boolean
rootDir: string staticAssets: any
runtimeDir: string
static: string[] entry: UnresolvedPath
renderer: string outName: string
nuxt: 2 | 3 node: false
analyze: boolean target: string
minify: boolean minify: boolean
rollupConfig?: any rollupConfig?: any
fullStatic: boolean, logStartup: boolean
inlineChunks: boolean
renderer: string
analyze: boolean
runtimeDir: string
slsDir: string
targetDir: string
static: string[]
generateIgnore: string[] generateIgnore: string[]
staticAssets: {
base: string
versionBase: string
dir: string
version: string
}
hooks: { [key: string]: any } // TODO: export from hookable
nuxtHooks: { [key: string]: Function } // NuxtOptions['hooks']
} }
export interface SLSConfig extends Omit<Partial<SLSOptions>, 'targetDir'> { export interface SLSConfig extends Omit<Partial<SLSOptions>, 'targetDir'> {
targetDir: UnresolvedPath targetDir?: UnresolvedPath
} }
export type SLSTarget = Partial<SLSConfig> | ((NuxtOptions) => Partial<SLSConfig>) export type SLSTargetFn = (SLSConfig) => SLSConfig
export type SLSTarget = SLSConfig | SLSTargetFn
export function getoptions (nuxtOptions: NuxtOptions): SLSOptions { export function getoptions (nuxt: Nuxt): SLSOptions {
const defaults: SLSConfig = { const defaults: SLSConfig = {
rootDir: nuxtOptions.rootDir, rootDir: nuxt.options.rootDir,
buildDir: nuxtOptions.buildDir, buildDir: nuxt.options.buildDir,
publicDir: nuxtOptions.generate.dir, publicDir: nuxt.options.generate.dir,
fullStatic: nuxtOptions.target === 'static' && !nuxtOptions._legacyGenerate, routerBase: nuxt.options.router.base,
fullStatic: nuxt.options.target === 'static' && !nuxt.options._legacyGenerate,
// @ts-ignore // @ts-ignore
staticAssets: nuxtOptions.generate.staticAssets, staticAssets: nuxt.options.generate.staticAssets,
outName: '_nuxt.js', outName: '_nuxt.js',
runtimeDir: resolve(__dirname, '../runtime'),
static: [],
generateIgnore: [],
nuxt: 2,
logStartup: true, logStartup: true,
inlineChunks: true, inlineChunks: true,
targetDir: null
runtimeDir: resolve(__dirname, '../runtime'),
slsDir: null,
targetDir: null,
static: [],
generateIgnore: []
} }
let target = process.env.NUXT_SLS_TARGET || nuxtOptions.serverless?.target || detectTarget() const target = process.env.NUXT_SLS_TARGET || nuxt.options.serverless?.target || detectTarget()
if (typeof target === 'function') { let targetDefaults = TARGETS[target] || tryImport(nuxt.options.rootDir, target)
target = target(nuxtOptions)
}
let targetDefaults = TARGETS[target] || tryImport(nuxtOptions.rootDir, target)
if (!targetDefaults) { if (!targetDefaults) {
throw new Error('Cannot resolve target: ' + target) throw new Error('Cannot resolve target: ' + target)
} }
targetDefaults = targetDefaults.default || targetDefaults targetDefaults = targetDefaults.default || targetDefaults
if (typeof targetDefaults === 'function') {
targetDefaults = targetDefaults(nuxtOptions)
}
const options: SLSOptions = defu(nuxtOptions.serverless, targetDefaults, defaults, { target }) const _defaults = defu(defaults, { target })
const _targetInput = defu(nuxt.options.serverless, _defaults)
const _target = extendTarget(nuxt.options.serverless, targetDefaults)(_targetInput)
const options: SLSOptions = defu(nuxt.options.serverless, _target, _defaults)
options.buildDir = resolve(options.rootDir, options.buildDir || '.nuxt')
options.publicDir = resolve(options.rootDir, options.publicDir || 'dist')
options.slsDir = resolve(options.rootDir, options.slsDir || '.sls') options.slsDir = resolve(options.rootDir, options.slsDir || '.sls')
options.targetDir = options.targetDir ? resolvePath(options, options.targetDir) : resolve(options.slsDir, target) options.targetDir = options.targetDir ? resolvePath(options, options.targetDir) : resolve(options.slsDir, target)

View File

@ -10,7 +10,7 @@ export default <Module> function slsModule () {
} }
// Config // Config
const options = getoptions(nuxt.options) const options = getoptions(nuxt)
if (options.minify !== false) { if (options.minify !== false) {
nuxt.options.build._minifyServer = true nuxt.options.build._minifyServer = true

View File

@ -93,7 +93,7 @@ export const getRollupConfig = (config: SLSOptions) => {
})) }))
// https://github.com/rollup/plugins/tree/master/packages/alias // https://github.com/rollup/plugins/tree/master/packages/alias
const renderer = config.renderer || (config.nuxt === 2 ? 'vue2' : 'vue3') const renderer = config.renderer || 'vue2'
options.plugins.push(alias({ options.plugins.push(alias({
entries: { entries: {
'~runtime': config.runtimeDir, '~runtime': config.runtimeDir,

View File

@ -5,36 +5,38 @@ import { extendTarget } from '../utils'
import { SLSTarget } from '../config' import { SLSTarget } from '../config'
import { worker } from './worker' import { worker } from './worker'
const getScriptTag = () => `<script> export const browser: SLSTarget = extendTarget(worker, (options) => {
const script = `<script>
if ('serviceWorker' in navigator) { if ('serviceWorker' in navigator) {
window.addEventListener('load', function () { window.addEventListener('load', function () {
navigator.serviceWorker.register('/server.js'); navigator.serviceWorker.register('${options.routerBase}_nuxt.js');
}); });
} }
</script>`.replace(/\n| +/g, '') </script>`.replace(/\n| +/g, '')
export const browser: SLSTarget = extendTarget(worker, { return {
targetDir: ({ publicDir }) => publicDir, targetDir: '{{ publicDir }}',
nuxtHooks: { nuxtHooks: {
'vue-renderer:ssr:templateParams' (params) { 'vue-renderer:ssr:templateParams' (params) {
params.APP += getScriptTag() params.APP += script
}, },
'vue-renderer:spa:templateParams' (params) { 'vue-renderer:spa:templateParams' (params) {
params.APP += getScriptTag() params.APP += script
}
},
hooks: {
'template:document' (tmpl) {
tmpl.compiled = tmpl.compiled.replace('</body>', getScriptTag() + '</body>')
},
async done ({ targetDir, publicDir }) {
const rootIndex = resolve(publicDir, 'index.html')
const rootFallback = resolve(publicDir, '200.html')
if (!existsSync(rootIndex) && existsSync(rootFallback)) {
await copy(rootFallback, rootIndex)
} }
},
hooks: {
'template:document' (tmpl) {
tmpl.compiled = tmpl.compiled.replace('</body>', script + '</body>')
},
async done ({ targetDir, publicDir }) {
const rootIndex = resolve(publicDir, 'index.html')
const rootFallback = resolve(publicDir, '200.html')
if (!existsSync(rootIndex) && existsSync(rootFallback)) {
await copy(rootFallback, rootIndex)
}
consola.info(`Try with \`npx serve ${relative(process.cwd(), targetDir)}\``) consola.info(`Try with \`npx serve ${relative(process.cwd(), targetDir)}\``)
}
} }
} }
}) })

View File

@ -3,8 +3,7 @@ import { writeFile, mkdirp } from 'fs-extra'
import jiti from 'jiti' import jiti from 'jiti'
import defu from 'defu' import defu from 'defu'
import Hookable from 'hookable' import Hookable from 'hookable'
import type { NuxtOptions } from '@nuxt/types' import { SLSOptions, UnresolvedPath, SLSTarget, SLSTargetFn, SLSConfig } from './config'
import { SLSOptions, UnresolvedPath, SLSTarget } from './config'
export function hl (str: string) { export function hl (str: string) {
return '`' + str + '`' return '`' + str + '`'
@ -44,6 +43,10 @@ export function resolvePath (options: SLSOptions, path: UnresolvedPath, resolveB
path = path(options) path = path(options)
} }
if (typeof path !== 'string') {
throw new TypeError('Invalid path: ' + path)
}
path = compileTemplate(path)(options) path = compileTemplate(path)(options)
return resolve(resolveBase, path) return resolve(resolveBase, path)
@ -61,16 +64,14 @@ export function detectTarget () {
return 'node' return 'node'
} }
export function extendTarget (base: SLSTarget, target: SLSTarget): SLSTarget { export function extendTarget (base: SLSTarget, target: SLSTarget): SLSTargetFn {
return (nuxtOptions: NuxtOptions) => { return (config: SLSConfig) => {
if (typeof target === 'function') { if (typeof target === 'function') {
target = target(nuxtOptions) target = target(config)
} }
if (typeof base === 'function') { if (typeof base === 'function') {
base = base(base) base = base(config)
} }
return defu({ return defu({
hooks: Hookable.mergeHooks(base.hooks, target.hooks), hooks: Hookable.mergeHooks(base.hooks, target.hooks),
nuxtHooks: Hookable.mergeHooks(base.nuxtHooks as any, target.nuxtHooks as any) nuxtHooks: Hookable.mergeHooks(base.nuxtHooks as any, target.nuxtHooks as any)