From c4da75164225e1dcd8ce5e91665d7e13cf2a9034 Mon Sep 17 00:00:00 2001 From: ehmicky <ehmicky@gmail.com> Date: Thu, 11 Mar 2021 16:43:01 +0100 Subject: [PATCH] chore: separate `getNextConfig()` --- helpers/getNextConfig.js | 26 ++++++++++++++++++++++++++ helpers/hasCorrectNextConfig.js | 19 +++++-------------- 2 files changed, 31 insertions(+), 14 deletions(-) create mode 100644 helpers/getNextConfig.js diff --git a/helpers/getNextConfig.js b/helpers/getNextConfig.js new file mode 100644 index 0000000000..8925d34484 --- /dev/null +++ b/helpers/getNextConfig.js @@ -0,0 +1,26 @@ +const { resolve } = require('path') + +let nextConfig + +// Load next.config.js +const getNextConfig = async function (failBuild) { + // Memoizes `nextConfig` + if (nextConfig !== undefined) { + return nextConfig + } + + // We cannot load `next` at the top-level because we validate whether the + // site is using `next` inside `onPreBuild`. + const { PHASE_PRODUCTION_BUILD } = require('next/constants') + const loadConfig = require('next/dist/next-server/server/config').default + + try { + nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, resolve('.')) + } catch (error) { + return failBuild('Error loading your next.config.js.', { error }) + } + + return nextConfig +} + +module.exports = getNextConfig diff --git a/helpers/hasCorrectNextConfig.js b/helpers/hasCorrectNextConfig.js index 14fb04f1a0..36bf0ff2b5 100644 --- a/helpers/hasCorrectNextConfig.js +++ b/helpers/hasCorrectNextConfig.js @@ -1,27 +1,18 @@ -const path = require('path') +const getNextConfig = require('./getNextConfig') -// Checks if site has the correct next.cofig.js +// Checks if site has the correct next.config.js const hasCorrectNextConfig = async ({ nextConfigPath, failBuild }) => { // In the plugin's case, no config is valid because we'll make it ourselves if (nextConfigPath === undefined) return true - // We cannot load `next` at the top-level because we validate whether the - // site is using `next` inside `onPreBuild`. - const { PHASE_PRODUCTION_BUILD } = require('next/constants') - const { default: loadConfig } = require('next/dist/next-server/server/config') + const { target } = await getNextConfig(failBuild) // If the next config exists, log warning if target isnt in acceptableTargets const acceptableTargets = ['serverless', 'experimental-serverless-trace'] - let nextConfig - try { - nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, path.resolve('.')) - } catch (error) { - return failBuild('Error loading your next.config.js.', { error }) - } - const isValidTarget = acceptableTargets.includes(nextConfig.target) + const isValidTarget = acceptableTargets.includes(target) if (!isValidTarget) { console.log( - `Your next.config.js must set the "target" property to one of: ${acceptableTargets.join(', ')}. Update the + `Your next.config.js must set the "target" property to one of: ${acceptableTargets.join(', ')}. Update the target property to allow this plugin to run.`, ) }