2021-11-21 16:14:46 +00:00
|
|
|
import type { LegacyNuxtModule, NuxtModule, ModuleMeta, ModuleInstallOptions, ModuleOptions, ModuleSrc, Nuxt } from '@nuxt/schema'
|
|
|
|
import { resolveModule, requireModule, importModule } from '../internal/cjs'
|
|
|
|
import { resolveAlias } from '../resolve'
|
2021-05-24 11:14:10 +00:00
|
|
|
import { defineNuxtModule } from './define'
|
2021-06-25 09:37:18 +00:00
|
|
|
import { createModuleContainer } 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-04-02 11:47:01 +00:00
|
|
|
export async function installModule (nuxt: Nuxt, installOpts: ModuleInstallOptions) {
|
|
|
|
let src: ModuleSrc
|
|
|
|
let options: ModuleOptions = {}
|
|
|
|
const meta: ModuleMeta = {}
|
|
|
|
|
|
|
|
// Extract src, meta and options
|
|
|
|
if (typeof installOpts === 'string') {
|
|
|
|
src = installOpts
|
|
|
|
} else if (Array.isArray(installOpts)) {
|
|
|
|
[src, options] = installOpts
|
|
|
|
} else if (typeof installOpts === 'object') {
|
|
|
|
if (installOpts.src || installOpts.handler) {
|
|
|
|
src = installOpts.src || installOpts.handler
|
|
|
|
options = installOpts.options
|
|
|
|
Object.assign(meta, installOpts.meta)
|
|
|
|
} else {
|
|
|
|
src = installOpts as NuxtModule
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
src = installOpts
|
|
|
|
}
|
|
|
|
|
|
|
|
// Resolve as legacy handler
|
|
|
|
let handler: LegacyNuxtModule
|
|
|
|
if (typeof src === 'string') {
|
2021-04-18 16:38:30 +00:00
|
|
|
const _src = resolveModule(resolveAlias(src, 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`
|
|
|
|
const isESM = _src.endsWith('.mjs') || meta.isESM
|
|
|
|
handler = isESM ? await importModule(_src) : requireModule(_src)
|
2021-04-02 11:47:01 +00:00
|
|
|
if (!meta.name) {
|
|
|
|
meta.name = src
|
|
|
|
}
|
|
|
|
} else if (typeof src === 'function') {
|
|
|
|
handler = src
|
|
|
|
} else {
|
|
|
|
handler = defineNuxtModule(src)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Merge meta
|
|
|
|
if (handler.meta) {
|
|
|
|
Object.assign(meta, handler.meta)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure module is required once
|
|
|
|
if (typeof meta.name === 'string') {
|
|
|
|
nuxt.options._requiredModules = nuxt.options._requiredModules || {}
|
|
|
|
if (nuxt.options._requiredModules[meta.name]) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
nuxt.options._requiredModules[meta.name] = true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Execute in legacy container
|
2021-06-25 09:37:18 +00:00
|
|
|
const container = createModuleContainer(nuxt)
|
2021-06-24 14:06:16 +00:00
|
|
|
await handler.call(container, options)
|
2021-04-02 11:47:01 +00:00
|
|
|
}
|