Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: monorepo handling #434

Merged
merged 17 commits into from
Jun 28, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,5 @@ Temporary Items

# End of https://www.toptal.com/developers/gitignore/api/osx,node
demo/package-lock.json

.netlify
11 changes: 0 additions & 11 deletions demo/netlify.toml

This file was deleted.

15 changes: 0 additions & 15 deletions demo/package.json

This file was deleted.

50 changes: 50 additions & 0 deletions helpers/checkNxConfig.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
const { existsSync } = require('fs')
const { EOL } = require('os')
const path = require('path')

const checkNxConfig = ({ netlifyConfig, nextConfig, failBuild, constants: { PUBLISH_DIR } }) => {
const errors = []
if (nextConfig.distDir === '.next') {
errors.push(
"- When using Nx you must set a value for 'distDir' in your next.config.js, and the value cannot be '.next'",
)
}
if (!PUBLISH_DIR.startsWith('apps')) {
errors.push(
"Please set the 'publish' value in your Netlify build config to a folder inside your app directory. e.g. 'apps/myapp/out'",
)
}

const expectedConfigFile = path.resolve(netlifyConfig.build.publish, '..', 'next.config.js')

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🥴


if (expectedConfigFile !== nextConfig.configFile) {
const confName = path.relative(process.cwd(), nextConfig.configFile)
errors.push(
`- Using incorrect config file '${confName}'. Expected to use '${path.relative(
process.cwd(),
expectedConfigFile,
)}'`,
)

if (existsSync(expectedConfigFile)) {
errors.push(
`Please move or delete '${confName}'${confName === 'next.config.js' ? ' from the root of your site' : ''}.`,
)
} else {
errors.push(
`Please move or delete '${confName}'${
confName === 'next.config.js' ? ' from the root of your site' : ''
}, and create '${path.relative(process.cwd(), expectedConfigFile)}' instead.`,
)
}
}

if (errors.length !== 0) {
failBuild(
// TODO: Add ntl.fyi link to docs
['Invalid configuration', ...errors, 'See the docs on using Nx with Netlify for more information'].join(EOL),
)
}
}

module.exports = checkNxConfig
12 changes: 12 additions & 0 deletions helpers/getNextRoot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { existsSync } = require('fs')
const path = require('path')

const getNextRoot = ({ netlifyConfig }) => {
let nextRoot = process.cwd()
if (!existsSync(path.join(nextRoot, 'next.config.js'))) {
nextRoot = path.dirname(netlifyConfig.build.publish)
}
return nextRoot
}

module.exports = getNextRoot
2 changes: 1 addition & 1 deletion helpers/validateNextUsage.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { lt: ltVersion, gte: gteVersion } = require('semver')
const { yellowBright } = require('chalk')
const { lt: ltVersion, gte: gteVersion } = require('semver')

// Ensure Next.js is available.
// We use `peerDependencies` instead of `dependencies` so that users can choose
Expand Down
32 changes: 18 additions & 14 deletions helpers/verifyBuildTarget.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
const getNextConfig = require('./getNextConfig')
const findUp = require('find-up')
const { writeFile, unlink } = require('fs-extra')
const path = require('path')

const { writeFile } = require('fs-extra')

const getNextConfig = require('./getNextConfig')
const getNextRoot = require('./getNextRoot')

// Checks if site has the correct next.config.js
const verifyBuildTarget = async ({ failBuild }) => {
const { target } = await getNextConfig(failBuild)
const verifyBuildTarget = async ({ failBuild, netlifyConfig }) => {
const nextRoot = getNextRoot({ netlifyConfig })

const { target, configFile, ...rest } = await getNextConfig(failBuild, nextRoot)
console.log({ target, rest, configFile, nextRoot })

// If the next config exists, log warning if target isnt in acceptableTargets
const acceptableTargets = ['serverless', 'experimental-serverless-trace']
Expand All @@ -19,8 +24,6 @@ const verifyBuildTarget = async ({ failBuild }) => {
)}". Building with "serverless" target.`,
)

/* eslint-disable fp/no-delete, node/no-unpublished-require */

// We emulate Vercel so that we can set target to serverless if needed
process.env.NOW_BUILDER = true
// If no valid target is set, we use an internal Next env var to force it
Expand All @@ -29,30 +32,31 @@ const verifyBuildTarget = async ({ failBuild }) => {
// 🐉 We need Next to recalculate "isZeitNow" var so we can set the target, but it's
// set as an import side effect so we need to clear the require cache first. 🐲
// https://github.com/vercel/next.js/blob/canary/packages/next/telemetry/ci-info.ts
/* eslint-disable node/no-unpublished-require */

delete require.cache[require.resolve('next/dist/telemetry/ci-info')]
delete require.cache[require.resolve('next/dist/next-server/server/config')]

/* eslint-enable node/no-unpublished-require */

// Clear memoized cache
getNextConfig.clear()

// Creating a config file, because otherwise Next won't reload the config and pick up the new target

if (!(await findUp('next.config.js'))) {
if (!configFile) {
await writeFile(
path.resolve('next.config.js'),
`module.exports = {
// Supported targets are "serverless" and "experimental-serverless-trace"
target: "serverless"
}`,
// Supported targets are "serverless" and "experimental-serverless-trace"
target: "serverless"
}`,
)
}
// Force the new config to be generated
await getNextConfig(failBuild)

await getNextConfig(failBuild, nextRoot)
// Reset the value in case something else is looking for it
process.env.NOW_BUILDER = false
/* eslint-enable fp/no-delete, node/no-unpublished-require */
}

module.exports = verifyBuildTarget
34 changes: 27 additions & 7 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
const path = require('path')

const makeDir = require('make-dir')

const { restoreCache, saveCache } = require('./helpers/cacheBuild')
const checkNxConfig = require('./helpers/checkNxConfig')
const copyUnstableIncludedDirs = require('./helpers/copyUnstableIncludedDirs')
const doesNotNeedPlugin = require('./helpers/doesNotNeedPlugin')
const getNextConfig = require('./helpers/getNextConfig')
const getNextRoot = require('./helpers/getNextRoot')
const validateNextUsage = require('./helpers/validateNextUsage')
const verifyBuildTarget = require('./helpers/verifyBuildTarget')
const nextOnNetlify = require('./src')

// * Helpful Plugin Context *
// - Between the prebuild and build steps, the project's build command is run
// - Between the build and postbuild steps, any functions are bundled

module.exports = {
async onPreBuild({ netlifyConfig, packageJson, utils }) {
async onPreBuild({ netlifyConfig, packageJson, utils, constants }) {
const { failBuild } = utils.build

validateNextUsage(failBuild)
Expand All @@ -29,9 +32,19 @@ module.exports = {

// Populates the correct config if needed
await verifyBuildTarget({ netlifyConfig, packageJson, failBuild })
const nextRoot = getNextRoot({ netlifyConfig })

// Because we memoize nextConfig, we need to do this after the write file
const nextConfig = await getNextConfig(utils.failBuild)
const nextConfig = await getNextConfig(utils.failBuild, nextRoot)

const isNx = Boolean(
(packageJson.devDependencies && packageJson.devDependencies['@nrwl/next']) ||
(packageJson.dependencies && packageJson.dependencies['@nrwl/next']),
)

if (isNx) {
checkNxConfig({ netlifyConfig, packageJson, nextConfig, failBuild, constants })
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

clean


if (nextConfig.images.domains.length !== 0 && !process.env.NEXT_IMAGE_ALLOWED_DOMAINS) {
console.log(
Expand All @@ -50,6 +63,8 @@ module.exports = {
}) {
const { failBuild } = utils.build

const nextRoot = getNextRoot({ netlifyConfig })

if (doesNotNeedPlugin({ netlifyConfig, packageJson, failBuild })) {
return
}
Expand All @@ -58,17 +73,22 @@ module.exports = {

await makeDir(PUBLISH_DIR)

await nextOnNetlify({ functionsDir: FUNCTIONS_SRC, publishDir: PUBLISH_DIR })
await nextOnNetlify({
functionsDir: path.resolve(FUNCTIONS_SRC),
publishDir: netlifyConfig.build.publish,
nextRoot,
})
},

async onPostBuild({ netlifyConfig, packageJson, constants: { FUNCTIONS_DIST }, utils }) {
if (doesNotNeedPlugin({ netlifyConfig, packageJson, utils })) {
return
}
const nextRoot = getNextRoot({ netlifyConfig })

const nextConfig = await getNextConfig(utils.failBuild)
await saveCache({ cache: utils.cache, distDir: nextConfig.distDir })
copyUnstableIncludedDirs({ nextConfig, functionsDist: FUNCTIONS_DIST })
const nextConfig = await getNextConfig(utils.failBuild, nextRoot)
await saveCache({ cache: utils.cache, distDir: path.join(nextRoot, nextConfig.distDir) })
copyUnstableIncludedDirs({ nextConfig, functionsDist: path.resolve(FUNCTIONS_DIST) })
},
}

Expand Down
11 changes: 10 additions & 1 deletion netlify.toml
Original file line number Diff line number Diff line change
@@ -1,2 +1,11 @@
[build]
base="demo/"
command = "npm run build:demo"
functions = "demo/netlify/functions"
publish = "demo/out"
base="."

[dev]
command="npm run dev:demo"

[[plugins]]
package="."

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wowee

Loading