Skip to content

Commit 105b153

Browse files
committed
feat: use loadNuxt (resolves #57)
BREAKING CHANGE: requires nuxt > 2.12
1 parent da293a1 commit 105b153

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed

lib/plugin.js

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
1-
const { resolve } = require('path')
2-
const { existsSync } = require('fs')
3-
const esm = require('esm')
4-
51
exports.register = async function (server, _config) {
62
// Apply defaults
73
const config = {
84
dev: process.env.NODE_ENV !== 'production',
95
rootDir: process.cwd(),
10-
nuxtConfig: 'nuxt.config.js',
116
edge: false,
127
baseURL: null,
138
route: {},
@@ -16,26 +11,18 @@ exports.register = async function (server, _config) {
1611
}
1712

1813
// Requre Nuxt
19-
const { Nuxt, Builder } = require(config.edge ? 'nuxt-edge' : 'nuxt')
14+
const { loadNuxt, getBuilder } = tryRequire('nuxt-edge') || tryRequire('nuxt')
2015

21-
// Resolve nuxt.config relative to rootDir
22-
config.nuxtConfig = resolve(config.rootDir, config.nuxtConfig)
16+
if (!loadNuxt) {
17+
throw new Error('Ensure nuxt or nuxt-edge >= 2.12 is instaled')
18+
}
2319

24-
// Load config
25-
const requireESM = esm(module, {
26-
cache: false
20+
// Initialize nuxt
21+
const nuxt = await loadNuxt({
22+
rootDir: config.rootDir,
23+
configOverrides: config.overrides,
24+
for: config.dev ? 'dev' : 'start'
2725
})
28-
const nuxtConfig = existsSync(config.nuxtConfig) ? requireESM(config.nuxtConfig) : {}
29-
30-
// Set rootDir and dev
31-
nuxtConfig.rootDir = config.rootDir
32-
nuxtConfig.dev = config.dev
33-
34-
// Create nuxt instance using options
35-
const nuxt = new Nuxt(nuxtConfig)
36-
37-
// Await nuxt to be ready
38-
await nuxt.ready()
3926

4027
// Expose nuxt
4128
server.expose('nuxt', nuxt)
@@ -62,11 +49,18 @@ exports.register = async function (server, _config) {
6249

6350
// Development mode
6451
if (config.dev) {
65-
const builder = new Builder(nuxt)
52+
const builder = await getBuilder(nuxt)
6653
server.expose('builder', builder)
6754
builder.build().catch(console.error)
6855
}
6956
}
7057

58+
function tryRequire (pkg) {
59+
try {
60+
return require(pkg)
61+
} catch (err) {
62+
}
63+
}
64+
7165
exports.name = 'nuxt'
7266
exports.pkg = require('../package.json')

0 commit comments

Comments
 (0)