feat: support targer functions to consume nuxtOptions

This commit is contained in:
Pooya Parsa 2020-11-06 13:55:30 +01:00
parent 5647d2dad0
commit 91caf2c470
2 changed files with 24 additions and 4 deletions

View File

@ -1,12 +1,13 @@
import { resolve } from 'path'
import defu from 'defu'
import { NuxtOptions } from '@nuxt/types'
import type { NuxtOptions } from '@nuxt/types'
import { tryImport, resolvePath, detectTarget } from './utils'
import * as TARGETS from './targets'
export type UnresolvedPath = string | ((SLSOptions) => string)
export interface SLSOptions {
nuxtOptions: NuxtOptions
node: false
target: string
entry: UnresolvedPath
@ -42,7 +43,7 @@ export interface SLSConfig extends Omit<Partial<SLSOptions>, 'targetDir'> {
targetDir: UnresolvedPath
}
export type SLSTarget = Partial<SLSConfig>
export type SLSTarget = Partial<SLSConfig> | ((NuxtOptions) => Partial<SLSConfig>)
export function getoptions (nuxtOptions: NuxtOptions): SLSOptions {
const defaults: SLSConfig = {
@ -55,6 +56,7 @@ export function getoptions (nuxtOptions: NuxtOptions): SLSOptions {
outName: '_nuxt.js',
runtimeDir: resolve(__dirname, '../runtime'),
static: [],
generateIgnore: [],
nuxt: 2,
logStartup: true,
inlineChunks: true,
@ -65,11 +67,15 @@ export function getoptions (nuxtOptions: NuxtOptions): SLSOptions {
if (typeof target === 'function') {
target = target(nuxtOptions)
}
let targetDefaults = TARGETS[target] || tryImport(nuxtOptions.rootDir, target)
if (!targetDefaults) {
throw new Error('Cannot resolve target: ' + target)
}
targetDefaults = targetDefaults.default || targetDefaults
if (typeof targetDefaults === 'function') {
targetDefaults = targetDefaults(nuxtOptions)
}
const options: SLSOptions = defu(nuxtOptions.serverless, targetDefaults, defaults, { target })

View File

@ -2,6 +2,8 @@ import { relative, dirname, resolve } from 'path'
import { writeFile, mkdirp } from 'fs-extra'
import jiti from 'jiti'
import defu from 'defu'
import Hookable from 'hookable'
import type { NuxtOptions } from '@nuxt/types'
import { SLSOptions, UnresolvedPath, SLSTarget } from './config'
export function hl (str: string) {
@ -60,6 +62,18 @@ export function detectTarget () {
}
export function extendTarget (base: SLSTarget, target: SLSTarget): SLSTarget {
// TODO: merge hooks
return defu(target, base)
return (nuxtOptions: NuxtOptions) => {
if (typeof target === 'function') {
target = target(nuxtOptions)
}
if (typeof base === 'function') {
base = base(base)
}
return defu({
hooks: Hookable.mergeHooks(base.hooks, target.hooks),
nuxtHooks: Hookable.mergeHooks(base.nuxtHooks as any, target.nuxtHooks as any)
}, target, base)
}
}