Skip to content

Commit

Permalink
feat: use loadNuxt (resolves #57)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: requires nuxt > 2.12
  • Loading branch information
pi0 committed Aug 26, 2020
1 parent da293a1 commit 105b153
Showing 1 changed file with 17 additions and 23 deletions.
40 changes: 17 additions & 23 deletions lib/plugin.js
Original file line number Diff line number Diff line change
@@ -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: {},
Expand All @@ -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)
Expand All @@ -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')

0 comments on commit 105b153

Please sign in to comment.