Skip to content

Commit 430569c

Browse files
authored
Merge pull request #114 from netlify/chore/refactor-get-next-config
chore: separate `getNextConfig()`
2 parents a4d644e + c4da751 commit 430569c

File tree

2 files changed

+31
-14
lines changed

2 files changed

+31
-14
lines changed

helpers/getNextConfig.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const { resolve } = require('path')
2+
3+
let nextConfig
4+
5+
// Load next.config.js
6+
const getNextConfig = async function (failBuild) {
7+
// Memoizes `nextConfig`
8+
if (nextConfig !== undefined) {
9+
return nextConfig
10+
}
11+
12+
// We cannot load `next` at the top-level because we validate whether the
13+
// site is using `next` inside `onPreBuild`.
14+
const { PHASE_PRODUCTION_BUILD } = require('next/constants')
15+
const loadConfig = require('next/dist/next-server/server/config').default
16+
17+
try {
18+
nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, resolve('.'))
19+
} catch (error) {
20+
return failBuild('Error loading your next.config.js.', { error })
21+
}
22+
23+
return nextConfig
24+
}
25+
26+
module.exports = getNextConfig

helpers/hasCorrectNextConfig.js

+5-14
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,18 @@
1-
const path = require('path')
1+
const getNextConfig = require('./getNextConfig')
22

3-
// Checks if site has the correct next.cofig.js
3+
// Checks if site has the correct next.config.js
44
const hasCorrectNextConfig = async ({ nextConfigPath, failBuild }) => {
55
// In the plugin's case, no config is valid because we'll make it ourselves
66
if (nextConfigPath === undefined) return true
77

8-
// We cannot load `next` at the top-level because we validate whether the
9-
// site is using `next` inside `onPreBuild`.
10-
const { PHASE_PRODUCTION_BUILD } = require('next/constants')
11-
const { default: loadConfig } = require('next/dist/next-server/server/config')
8+
const { target } = await getNextConfig(failBuild)
129

1310
// If the next config exists, log warning if target isnt in acceptableTargets
1411
const acceptableTargets = ['serverless', 'experimental-serverless-trace']
15-
let nextConfig
16-
try {
17-
nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, path.resolve('.'))
18-
} catch (error) {
19-
return failBuild('Error loading your next.config.js.', { error })
20-
}
21-
const isValidTarget = acceptableTargets.includes(nextConfig.target)
12+
const isValidTarget = acceptableTargets.includes(target)
2213
if (!isValidTarget) {
2314
console.log(
24-
`Your next.config.js must set the "target" property to one of: ${acceptableTargets.join(', ')}. Update the
15+
`Your next.config.js must set the "target" property to one of: ${acceptableTargets.join(', ')}. Update the
2516
target property to allow this plugin to run.`,
2617
)
2718
}

0 commit comments

Comments
 (0)