This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
install.ts
58 lines (47 loc) · 2.13 KB
/
install.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import type { Nuxt, NuxtModule } from '@nuxt/schema'
import { useNuxt } from '../context'
import { resolveModule, requireModule, importModule } from '../internal/cjs'
import { resolveAlias } from '../resolve'
/** Installs a module on a Nuxt instance. */
export async function installModule (moduleToInstall: string | NuxtModule, _inlineOptions?: any, _nuxt?: Nuxt) {
const nuxt = useNuxt()
const { nuxtModule, inlineOptions } = await normalizeModule(moduleToInstall, _inlineOptions)
// Call module
await nuxtModule(inlineOptions, nuxt)
if (typeof moduleToInstall === 'string') {
nuxt.options.build.transpile.push(moduleToInstall)
}
nuxt.options._installedModules = nuxt.options._installedModules || []
nuxt.options._installedModules.push({
meta: await nuxtModule.getMeta?.(),
entryPath: typeof moduleToInstall === 'string' ? resolveAlias(moduleToInstall) : undefined
})
}
// --- Internal ---
async function normalizeModule (nuxtModule: string | NuxtModule, inlineOptions?: any) {
const 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 || '') {
[nuxtModule, inlineOptions] = [inlineOptions, {}]
console.warn(new Error('`installModule` is being called with old signature!'))
}
// Import if input is string
if (typeof nuxtModule === 'string') {
const _src = resolveModule(resolveAlias(nuxtModule), { paths: nuxt.options.modulesDir })
// TODO: also check with type: 'module' in closest `package.json`
const isESM = _src.endsWith('.mjs')
try {
nuxtModule = isESM ? await importModule(_src) : requireModule(_src)
} catch (error: unknown) {
console.error(`Error while requiring module \`${nuxtModule}\`: ${error}`)
throw error
}
}
// Throw error if input is not a function
if (typeof nuxtModule !== 'function') {
throw new TypeError('Nuxt module should be a function: ' + nuxtModule)
}
return { nuxtModule, inlineOptions } as { nuxtModule: NuxtModule<any>, inlineOptions: undefined | Record<string, any> }
}