From 105b153a87f5cb7da185a7d53d8b6d4964a0e449 Mon Sep 17 00:00:00 2001 From: pooya parsa Date: Wed, 26 Aug 2020 16:17:55 +0200 Subject: [PATCH] feat: use `loadNuxt` (resolves #57) BREAKING CHANGE: requires nuxt > 2.12 --- lib/plugin.js | 40 +++++++++++++++++----------------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/lib/plugin.js b/lib/plugin.js index b4918a7..ba06e32 100755 --- a/lib/plugin.js +++ b/lib/plugin.js @@ -1,13 +1,8 @@ -const { resolve } = require('path') -const { existsSync } = require('fs') -const esm = require('esm') - exports.register = async function (server, _config) { // Apply defaults const config = { dev: process.env.NODE_ENV !== 'production', rootDir: process.cwd(), - nuxtConfig: 'nuxt.config.js', edge: false, baseURL: null, route: {}, @@ -16,26 +11,18 @@ exports.register = async function (server, _config) { } // Requre Nuxt - const { Nuxt, Builder } = require(config.edge ? 'nuxt-edge' : 'nuxt') + const { loadNuxt, getBuilder } = tryRequire('nuxt-edge') || tryRequire('nuxt') - // Resolve nuxt.config relative to rootDir - config.nuxtConfig = resolve(config.rootDir, config.nuxtConfig) + if (!loadNuxt) { + throw new Error('Ensure nuxt or nuxt-edge >= 2.12 is instaled') + } - // Load config - const requireESM = esm(module, { - cache: false + // Initialize nuxt + const nuxt = await loadNuxt({ + rootDir: config.rootDir, + configOverrides: config.overrides, + for: config.dev ? 'dev' : 'start' }) - const nuxtConfig = existsSync(config.nuxtConfig) ? requireESM(config.nuxtConfig) : {} - - // Set rootDir and dev - nuxtConfig.rootDir = config.rootDir - nuxtConfig.dev = config.dev - - // Create nuxt instance using options - const nuxt = new Nuxt(nuxtConfig) - - // Await nuxt to be ready - await nuxt.ready() // Expose nuxt server.expose('nuxt', nuxt) @@ -62,11 +49,18 @@ exports.register = async function (server, _config) { // Development mode if (config.dev) { - const builder = new Builder(nuxt) + const builder = await getBuilder(nuxt) server.expose('builder', builder) builder.build().catch(console.error) } } +function tryRequire (pkg) { + try { + return require(pkg) + } catch (err) { + } +} + exports.name = 'nuxt' exports.pkg = require('../package.json')