2021-12-21 13:57:26 +00:00
|
|
|
import type { NuxtModule, Nuxt } from '@nuxt/schema'
|
|
|
|
import { useNuxt } from '../context'
|
2021-11-21 16:14:46 +00:00
|
|
|
import { resolveModule, requireModule, importModule } from '../internal/cjs'
|
|
|
|
import { resolveAlias } from '../resolve'
|
2021-12-21 13:57:26 +00:00
|
|
|
import { useModuleContainer } from './container'
|
2021-04-02 11:47:01 +00:00
|
|
|
|
2021-04-15 18:49:29 +00:00
|
|
|
/** Installs a module on a Nuxt instance. */
|
2021-12-21 13:57:26 +00:00
|
|
|
export async function installModule (nuxtModule: string | NuxtModule, inlineOptions?: any, nuxt: Nuxt = useNuxt()) {
|
|
|
|
// Detect if `installModule` used with older signuture (nuxt, nuxtModule)
|
|
|
|
// TODO: Remove in RC
|
|
|
|
// @ts-ignore
|
|
|
|
if (nuxtModule?._version || nuxtModule?.version || nuxtModule?.constructor?.version || '') {
|
|
|
|
// @ts-ignore
|
|
|
|
[nuxt, nuxtModule] = [nuxtModule, inlineOptions]
|
|
|
|
inlineOptions = {}
|
|
|
|
console.warn(new Error('`installModule` is being called with old signature!'))
|
2021-04-02 11:47:01 +00:00
|
|
|
}
|
|
|
|
|
2021-12-21 13:57:26 +00:00
|
|
|
// Import if input is string
|
|
|
|
if (typeof nuxtModule === 'string') {
|
|
|
|
const _src = resolveModule(resolveAlias(nuxtModule, nuxt.options.alias), { paths: nuxt.options.modulesDir })
|
2021-10-21 17:02:26 +00:00
|
|
|
// TODO: also check with type: 'module' in closest `package.json`
|
2021-12-21 13:57:26 +00:00
|
|
|
const isESM = _src.endsWith('.mjs')
|
|
|
|
nuxtModule = isESM ? await importModule(_src) : requireModule(_src)
|
2021-04-02 11:47:01 +00:00
|
|
|
}
|
|
|
|
|
2021-12-21 13:57:26 +00:00
|
|
|
// Throw error if input is not a function
|
|
|
|
if (typeof nuxtModule !== 'function') {
|
|
|
|
throw new TypeError('Nuxt module should be a function: ' + nuxtModule)
|
2021-04-02 11:47:01 +00:00
|
|
|
}
|
|
|
|
|
2021-12-21 13:57:26 +00:00
|
|
|
// Call module
|
|
|
|
await nuxtModule.call(useModuleContainer(), inlineOptions, nuxt)
|
2021-04-02 11:47:01 +00:00
|
|
|
}
|