Commit a8e3b022 authored by JJ Kasper's avatar JJ Kasper Committed by Tim Neutkens

Add `src` directory support (#8735)

* Add find-pages-dir

* Add support for src directory

* Add test for pages dir preference

* Update comment
parent fb9d777f
...@@ -9,6 +9,7 @@ One of your public files has the exact same path as a page file which is not sup ...@@ -9,6 +9,7 @@ One of your public files has the exact same path as a page file which is not sup
Rename either the public file or page file that is causing the conflict. Rename either the public file or page file that is causing the conflict.
Example conflict between public file and page file Example conflict between public file and page file
``` ```
public/ public/
hello hello
...@@ -17,6 +18,7 @@ pages/ ...@@ -17,6 +18,7 @@ pages/
``` ```
Non-conflicting public file and page file Non-conflicting public file and page file
``` ```
public/ public/
hello.txt hello.txt
......
...@@ -82,7 +82,7 @@ An easy way to disable Sentry while developing is to set its `enabled` flag base ...@@ -82,7 +82,7 @@ An easy way to disable Sentry while developing is to set its `enabled` flag base
```js ```js
Sentry.init({ Sentry.init({
dsn: 'PUT_YOUR_SENTRY_DSN_HERE', dsn: 'PUT_YOUR_SENTRY_DSN_HERE',
enabled: process.env.NODE_ENV === 'production' enabled: process.env.NODE_ENV === 'production',
}) })
``` ```
......
...@@ -56,7 +56,9 @@ MyError.getInitialProps = async ({ res, err, asPath }) => { ...@@ -56,7 +56,9 @@ MyError.getInitialProps = async ({ res, err, asPath }) => {
// If this point is reached, getInitialProps was called without any // If this point is reached, getInitialProps was called without any
// information about what the error might be. This is unexpected and may // information about what the error might be. This is unexpected and may
// indicate a bug introduced in Next.js, so record it in Sentry // indicate a bug introduced in Next.js, so record it in Sentry
Sentry.captureException(new Error(`_error.js getInitialProps missing data at path: ${asPath}`)) Sentry.captureException(
new Error(`_error.js getInitialProps missing data at path: ${asPath}`)
)
return errorInitialProps return errorInitialProps
} }
......
...@@ -10,9 +10,7 @@ const isProd = env.NODE_ENV === 'production' ...@@ -10,9 +10,7 @@ const isProd = env.NODE_ENV === 'production'
const Test5 = () => ( const Test5 = () => (
<React.Fragment> <React.Fragment>
<h1>Client Test 5</h1> <h1>Client Test 5</h1>
<p> <p>isProd: {isProd}</p>
isProd: {isProd}
</p>
</React.Fragment> </React.Fragment>
) )
......
...@@ -12,25 +12,22 @@ const Index = () => ( ...@@ -12,25 +12,22 @@ const Index = () => (
<p> <p>
<strong>Important:</strong> exceptions in development mode take a <strong>Important:</strong> exceptions in development mode take a
different path than in production. These tests should be run on a different path than in production. These tests should be run on a
production build (i.e. 'next build'). production build (i.e. 'next build').{' '}
{' '}
<a href='https://nextjs.org/docs#custom-error-handling'>Read more</a> <a href='https://nextjs.org/docs#custom-error-handling'>Read more</a>
</p> </p>
<ul> <ul>
<li>Server exceptions</li> <li>Server exceptions</li>
<ul> <ul>
<li> <li>
getInitialProps throws an Error. This should cause _error.js to getInitialProps throws an Error. This should cause _error.js to render
render and record Error('Client Test 1') in Sentry. and record Error('Client Test 1') in Sentry.{' '}
{' '}
<a href='/server/test1' target='_blank'> <a href='/server/test1' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
</li> </li>
<li> <li>
getInitialProps returns a Promise that rejects. This should cause getInitialProps returns a Promise that rejects. This should cause
_error.js to render and record Error('Server Test 2') in Sentry. _error.js to render and record Error('Server Test 2') in Sentry.{' '}
{' '}
<a href='/server/test2' target='_blank'> <a href='/server/test2' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
...@@ -38,8 +35,7 @@ const Index = () => ( ...@@ -38,8 +35,7 @@ const Index = () => (
<li> <li>
getInitialProps calls a Promise that rejects, but does not handle the getInitialProps calls a Promise that rejects, but does not handle the
rejection or await its result (returning synchronously). Sentry should rejection or await its result (returning synchronously). Sentry should
record Error('Server Test 3'). record Error('Server Test 3').{' '}
{' '}
<a href='/server/test3' target='_blank'> <a href='/server/test3' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
...@@ -47,8 +43,7 @@ const Index = () => ( ...@@ -47,8 +43,7 @@ const Index = () => (
<li> <li>
There is a top-of-module Promise that rejects, but its result is not There is a top-of-module Promise that rejects, but its result is not
awaited. Sentry should record Error('Server Test 4'). Note this will awaited. Sentry should record Error('Server Test 4'). Note this will
also be recorded on the client side, once the page is hydrated. also be recorded on the client side, once the page is hydrated.{' '}
{' '}
<a href='/server/test4' target='_blank'> <a href='/server/test4' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
...@@ -62,64 +57,45 @@ const Index = () => ( ...@@ -62,64 +57,45 @@ const Index = () => (
and record Error('Client Test 1') in Sentry. Note Sentry will double and record Error('Client Test 1') in Sentry. Note Sentry will double
count this exception. Once from an unhandledrejection and again in count this exception. Once from an unhandledrejection and again in
_error.js. Could be a bug in Next.js or Sentry, requires more _error.js. Could be a bug in Next.js or Sentry, requires more
debugging. debugging.{' '}
{' '}
<Link href='/client/test1'> <Link href='/client/test1'>
<a> <a>Perform client side navigation</a>
Perform client side navigation
</a>
</Link> </Link>
</li> </li>
<li> <li>
getInitialProps returns a Promise that rejects. This should cause getInitialProps returns a Promise that rejects. This should cause
_error.js to render and record Error('Client Test 2') in Sentry. As _error.js to render and record Error('Client Test 2') in Sentry. As
above, Sentry will double count this exception. above, Sentry will double count this exception.{' '}
{' '}
<Link href='/client/test2'> <Link href='/client/test2'>
<a> <a>Perform client side navigation</a>
Perform client side navigation
</a>
</Link> </Link>
</li> </li>
<li> <li>
getInitialProps calls a Promise that rejects, but does not handle the getInitialProps calls a Promise that rejects, but does not handle the
rejection or await its result (returning synchronously). Sentry should rejection or await its result (returning synchronously). Sentry should
record Error('Client Test 3'). record Error('Client Test 3').{' '}
{' '}
<Link href='/client/test3'> <Link href='/client/test3'>
<a> <a>Perform client side navigation</a>
Perform client side navigation
</a>
</Link> </Link>
</li> </li>
<li> <li>
There is a top-of-module Promise that rejects, but its result is not There is a top-of-module Promise that rejects, but its result is not
awaited. Sentry should record Error('Client Test 4'). awaited. Sentry should record Error('Client Test 4').{' '}
{' '}
<Link href='/client/test4'> <Link href='/client/test4'>
<a> <a>Perform client side navigation</a>
Perform client side navigation </Link>{' '}
</a> or{' '}
</Link>
{' '}
or
{' '}
<a href='/client/test4' target='_blank'> <a href='/client/test4' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
</li> </li>
<li> <li>
There is a top-of-module exception. _error.js should render and record There is a top-of-module exception. _error.js should render and record
ReferenceError('process is not defined') in Sentry. ReferenceError('process is not defined') in Sentry.{' '}
{' '}
<Link href='/client/test5'> <Link href='/client/test5'>
<a> <a>Perform client side navigation</a>
Perform client side navigation </Link>{' '}
</a> or{' '}
</Link>
{' '}
or
{' '}
<a href='/client/test5' target='_blank'> <a href='/client/test5' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
...@@ -127,17 +103,12 @@ const Index = () => ( ...@@ -127,17 +103,12 @@ const Index = () => (
<li> <li>
There is an exception during React lifecycle that is caught by There is an exception during React lifecycle that is caught by
Next.js's React Error Boundary. In this case, when the component Next.js's React Error Boundary. In this case, when the component
mounts. This should cause _error.js to render and record mounts. This should cause _error.js to render and record Error('Client
Error('Client Test 6') in Sentry. Test 6') in Sentry.{' '}
{' '}
<Link href='/client/test6'> <Link href='/client/test6'>
<a> <a>Perform client side navigation</a>
Perform client side navigation </Link>{' '}
</a> or{' '}
</Link>
{' '}
or
{' '}
<a href='/client/test6' target='_blank'> <a href='/client/test6' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
...@@ -145,32 +116,22 @@ const Index = () => ( ...@@ -145,32 +116,22 @@ const Index = () => (
<li> <li>
There is an unhandled Promise rejection during React lifecycle. In There is an unhandled Promise rejection during React lifecycle. In
this case, when the component mounts. Sentry should record this case, when the component mounts. Sentry should record
Error('Client Test 7'). Error('Client Test 7').{' '}
{' '}
<Link href='/client/test7'> <Link href='/client/test7'>
<a> <a>Perform client side navigation</a>
Perform client side navigation </Link>{' '}
</a> or{' '}
</Link>
{' '}
or
{' '}
<a href='/client/test7' target='_blank'> <a href='/client/test7' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
</li> </li>
<li> <li>
An Error is thrown from an event handler. Sentry should record An Error is thrown from an event handler. Sentry should record
Error('Client Test 8'). Error('Client Test 8').{' '}
{' '}
<Link href='/client/test8'> <Link href='/client/test8'>
<a> <a>Perform client side navigation</a>
Perform client side navigation </Link>{' '}
</a> or{' '}
</Link>
{' '}
or
{' '}
<a href='/client/test8' target='_blank'> <a href='/client/test8' target='_blank'>
Open in a new tab Open in a new tab
</a> </a>
......
...@@ -2675,7 +2675,6 @@ For the production deployment, you can use the same configuration and run `now` ...@@ -2675,7 +2675,6 @@ For the production deployment, you can use the same configuration and run `now`
- [Build a SaaS Product with React-Material-UI-Next-MobX-Express-Mongoose-MongoDB-TypeScript](https://github.com/async-labs/saas) - [Build a SaaS Product with React-Material-UI-Next-MobX-Express-Mongoose-MongoDB-TypeScript](https://github.com/async-labs/saas)
- [Working with Ghost and Next.js](https://ghost.org/docs/api/nextjs/) - [Working with Ghost and Next.js](https://ghost.org/docs/api/nextjs/)
## FAQ ## FAQ
<details> <details>
......
...@@ -41,6 +41,7 @@ import { ...@@ -41,6 +41,7 @@ import {
import getBaseWebpackConfig from './webpack-config' import getBaseWebpackConfig from './webpack-config'
import { getPageChunks } from './webpack/plugins/chunk-graph-plugin' import { getPageChunks } from './webpack/plugins/chunk-graph-plugin'
import { writeBuildId } from './write-build-id' import { writeBuildId } from './write-build-id'
import { findPagesDir } from '../lib/find-pages-dir'
import createSpinner from './spinner' import createSpinner from './spinner'
import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../lib/constants' import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../lib/constants'
import { isDynamicRoute } from '../next-server/lib/router/utils' import { isDynamicRoute } from '../next-server/lib/router/utils'
...@@ -71,8 +72,6 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -71,8 +72,6 @@ export default async function build(dir: string, conf = null): Promise<void> {
) )
} }
await verifyTypeScriptSetup(dir)
let backgroundWork: (Promise<any> | undefined)[] = [] let backgroundWork: (Promise<any> | undefined)[] = []
backgroundWork.push( backgroundWork.push(
recordVersion({ cliCommand: 'build' }), recordVersion({ cliCommand: 'build' }),
...@@ -87,10 +86,15 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -87,10 +86,15 @@ export default async function build(dir: string, conf = null): Promise<void> {
const { target } = config const { target } = config
const buildId = await generateBuildId(config.generateBuildId, nanoid) const buildId = await generateBuildId(config.generateBuildId, nanoid)
const distDir = path.join(dir, config.distDir) const distDir = path.join(dir, config.distDir)
const pagesDir = path.join(dir, 'pages')
const publicDir = path.join(dir, 'public') const publicDir = path.join(dir, 'public')
const pagesDir = findPagesDir(dir)
let publicFiles: string[] = [] let publicFiles: string[] = []
await verifyTypeScriptSetup(dir, pagesDir)
console.log('Creating an optimized production build ...')
console.log()
if (config.experimental.publicDirectory) { if (config.experimental.publicDirectory) {
publicFiles = await recursiveReadDir(publicDir, /.*/) publicFiles = await recursiveReadDir(publicDir, /.*/)
} }
...@@ -153,6 +157,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -153,6 +157,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
isServer: false, isServer: false,
config, config,
target, target,
pagesDir,
entrypoints: entrypoints.client, entrypoints: entrypoints.client,
}), }),
getBaseWebpackConfig(dir, { getBaseWebpackConfig(dir, {
...@@ -161,6 +166,7 @@ export default async function build(dir: string, conf = null): Promise<void> { ...@@ -161,6 +166,7 @@ export default async function build(dir: string, conf = null): Promise<void> {
isServer: true, isServer: true,
config, config,
target, target,
pagesDir,
entrypoints: entrypoints.server, entrypoints: entrypoints.server,
}), }),
]) ])
......
...@@ -50,20 +50,22 @@ const escapePathVariables = (value: any) => { ...@@ -50,20 +50,22 @@ const escapePathVariables = (value: any) => {
export default async function getBaseWebpackConfig( export default async function getBaseWebpackConfig(
dir: string, dir: string,
{ {
dev = false,
isServer = false,
buildId, buildId,
config, config,
dev = false,
isServer = false,
pagesDir,
tracer,
target = 'server', target = 'server',
entrypoints, entrypoints,
tracer,
}: { }: {
tracer?: any
dev?: boolean
isServer?: boolean
buildId: string buildId: string
config: any config: any
dev?: boolean
isServer?: boolean
pagesDir: string
target?: string target?: string
tracer?: any
entrypoints: WebpackEntrypoints entrypoints: WebpackEntrypoints
} }
): Promise<webpack.Configuration> { ): Promise<webpack.Configuration> {
...@@ -75,6 +77,7 @@ export default async function getBaseWebpackConfig( ...@@ -75,6 +77,7 @@ export default async function getBaseWebpackConfig(
isServer, isServer,
hasModern: !!config.experimental.modern, hasModern: !!config.experimental.modern,
distDir, distDir,
pagesDir,
cwd: dir, cwd: dir,
cache: true, cache: true,
}, },
...@@ -154,7 +157,7 @@ export default async function getBaseWebpackConfig( ...@@ -154,7 +157,7 @@ export default async function getBaseWebpackConfig(
'next/config': 'next/dist/next-server/lib/runtime-config.js', 'next/config': 'next/dist/next-server/lib/runtime-config.js',
'next/dynamic': 'next/dist/next-server/lib/dynamic.js', 'next/dynamic': 'next/dist/next-server/lib/dynamic.js',
next: NEXT_PROJECT_ROOT, next: NEXT_PROJECT_ROOT,
[PAGES_DIR_ALIAS]: path.join(dir, 'pages'), [PAGES_DIR_ALIAS]: pagesDir,
[DOT_NEXT_ALIAS]: distDir, [DOT_NEXT_ALIAS]: distDir,
}, },
mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'], mainFields: isServer ? ['main', 'module'] : ['browser', 'module', 'main'],
......
...@@ -54,6 +54,7 @@ module.exports = babelLoader.custom(babel => { ...@@ -54,6 +54,7 @@ module.exports = babelLoader.custom(babel => {
const custom = { const custom = {
isServer: opts.isServer, isServer: opts.isServer,
isModern: opts.isModern, isModern: opts.isModern,
pagesDir: opts.pagesDir,
hasModern: opts.hasModern hasModern: opts.hasModern
} }
const filename = join(opts.cwd, 'noop.js') const filename = join(opts.cwd, 'noop.js')
...@@ -86,19 +87,19 @@ module.exports = babelLoader.custom(babel => { ...@@ -86,19 +87,19 @@ module.exports = babelLoader.custom(babel => {
delete loader.distDir delete loader.distDir
delete loader.isModern delete loader.isModern
delete loader.hasModern delete loader.hasModern
delete loader.pagesDir
return { loader, custom } return { loader, custom }
}, },
config ( config (
cfg, cfg,
{ {
source, source,
customOptions: { isServer, isModern, hasModern } customOptions: { isServer, isModern, hasModern, pagesDir }
} }
) { ) {
const { cwd } = cfg.options
const filename = this.resourcePath const filename = this.resourcePath
const options = Object.assign({}, cfg.options) const options = Object.assign({}, cfg.options)
const isPageFile = filename.startsWith(join(cwd, 'pages')) const isPageFile = filename.startsWith(pagesDir)
if (cfg.hasFilesystemConfig()) { if (cfg.hasFilesystemConfig()) {
for (const file of [cfg.babelrc, cfg.config]) { for (const file of [cfg.babelrc, cfg.config]) {
......
...@@ -41,20 +41,6 @@ const nextBuild: cliCommand = argv => { ...@@ -41,20 +41,6 @@ const nextBuild: cliCommand = argv => {
printAndExit(`> No such directory exists as the project root: ${dir}`) printAndExit(`> No such directory exists as the project root: ${dir}`)
} }
// Check if the pages directory exists
if (!existsSync(join(dir, 'pages'))) {
// Check one level down the tree to see if the pages directory might be there
if (existsSync(join(dir, '..', 'pages'))) {
printAndExit(
'> No `pages` directory found. Did you mean to run `next` in the parent (`../`) directory?'
)
}
printAndExit(
"> Couldn't find a `pages` directory. Please create one under the project root"
)
}
build(dir) build(dir)
.then(() => process.exit(0)) .then(() => process.exit(0))
.catch(err => { .catch(err => {
......
...@@ -52,18 +52,6 @@ const nextDev: cliCommand = argv => { ...@@ -52,18 +52,6 @@ const nextDev: cliCommand = argv => {
printAndExit(`> No such directory exists as the project root: ${dir}`) printAndExit(`> No such directory exists as the project root: ${dir}`)
} }
if (!existsSync(join(dir, 'pages'))) {
if (existsSync(join(dir, '..', 'pages'))) {
printAndExit(
'> No `pages` directory found. Did you mean to run `next` in the parent (`../`) directory?'
)
}
printAndExit(
"> Couldn't find a `pages` directory. Please create one under the project root"
)
}
const port = args['--port'] || 3000 const port = args['--port'] || 3000
const appUrl = `http://${args['--hostname'] || 'localhost'}:${port}` const appUrl = `http://${args['--hostname'] || 'localhost'}:${port}`
......
...@@ -51,18 +51,6 @@ const nextExport: cliCommand = argv => { ...@@ -51,18 +51,6 @@ const nextExport: cliCommand = argv => {
printAndExit(`> No such directory exists as the project root: ${dir}`) printAndExit(`> No such directory exists as the project root: ${dir}`)
} }
if (!existsSync(join(dir, 'pages'))) {
if (existsSync(join(dir, '..', 'pages'))) {
printAndExit(
'> No `pages` directory found. Did you mean to run `next` in the parent (`../`) directory?'
)
}
printAndExit(
"> Couldn't find a `pages` directory. Please create one under the project root"
)
}
const options = { const options = {
silent: args['--silent'] || false, silent: args['--silent'] || false,
threads: args['--threads'], threads: args['--threads'],
......
...@@ -5,7 +5,6 @@ export const NEXT_PROJECT_ROOT_NODE_MODULES = join( ...@@ -5,7 +5,6 @@ export const NEXT_PROJECT_ROOT_NODE_MODULES = join(
NEXT_PROJECT_ROOT, NEXT_PROJECT_ROOT,
'node_modules' 'node_modules'
) )
export const DEFAULT_PAGES_DIR = join(NEXT_PROJECT_ROOT_DIST, 'pages')
export const NEXT_PROJECT_ROOT_DIST_CLIENT = join( export const NEXT_PROJECT_ROOT_DIST_CLIENT = join(
NEXT_PROJECT_ROOT_DIST, NEXT_PROJECT_ROOT_DIST,
'client' 'client'
......
import fs from 'fs'
import path from 'path'
const existsSync = (f: string): boolean => {
try {
fs.accessSync(f, fs.constants.F_OK)
return true
} catch (_) {
return false
}
}
export function findPagesDir(dir: string): string {
// prioritize ./pages over ./src/pages
let curDir = path.join(dir, 'pages')
if (existsSync(curDir)) return curDir
curDir = path.join(dir, 'src/pages')
if (existsSync(curDir)) return curDir
// Check one level up the tree to see if the pages directory might be there
if (existsSync(path.join(dir, '..', 'pages'))) {
throw new Error(
'> No `pages` directory found. Did you mean to run `next` in the parent (`../`) directory?'
)
}
throw new Error(
"> Couldn't find a `pages` directory. Please create one under the project root"
)
}
...@@ -20,7 +20,7 @@ function writeJson(fileName: string, object: object): Promise<void> { ...@@ -20,7 +20,7 @@ function writeJson(fileName: string, object: object): Promise<void> {
async function hasTypeScript(dir: string): Promise<boolean> { async function hasTypeScript(dir: string): Promise<boolean> {
const typescriptFiles = await recursiveReadDir( const typescriptFiles = await recursiveReadDir(
path.join(dir, 'pages'), dir,
/.*\.(ts|tsx)$/, /.*\.(ts|tsx)$/,
/(node_modules|.*\.d\.ts)/ /(node_modules|.*\.d\.ts)/
) )
...@@ -96,7 +96,10 @@ async function checkDependencies({ ...@@ -96,7 +96,10 @@ async function checkDependencies({
process.exit(1) process.exit(1)
} }
export async function verifyTypeScriptSetup(dir: string): Promise<void> { export async function verifyTypeScriptSetup(
dir: string,
pagesDir: string
): Promise<void> {
const tsConfigPath = path.join(dir, 'tsconfig.json') const tsConfigPath = path.join(dir, 'tsconfig.json')
const yarnLockFile = path.join(dir, 'yarn.lock') const yarnLockFile = path.join(dir, 'yarn.lock')
...@@ -110,7 +113,7 @@ export async function verifyTypeScriptSetup(dir: string): Promise<void> { ...@@ -110,7 +113,7 @@ export async function verifyTypeScriptSetup(dir: string): Promise<void> {
) )
firstTimeSetup = tsConfig === '' || tsConfig === '{}' firstTimeSetup = tsConfig === '' || tsConfig === '{}'
} else { } else {
const hasTypeScriptFiles = await hasTypeScript(dir) const hasTypeScriptFiles = await hasTypeScript(pagesDir)
if (hasTypeScriptFiles) { if (hasTypeScriptFiles) {
firstTimeSetup = true firstTimeSetup = true
} else { } else {
......
...@@ -33,6 +33,7 @@ import Router, { Params, route, Route, RouteMatch } from './router' ...@@ -33,6 +33,7 @@ import Router, { Params, route, Route, RouteMatch } from './router'
import { sendHTML } from './send-html' import { sendHTML } from './send-html'
import { serveStatic } from './serve-static' import { serveStatic } from './serve-static'
import { isBlockedPage, isInternalUrl } from './utils' import { isBlockedPage, isInternalUrl } from './utils'
import { findPagesDir } from '../../lib/find-pages-dir'
import { initializeSprCache, getSprCache, setSprCache } from './spr-cache' import { initializeSprCache, getSprCache, setSprCache } from './spr-cache'
type NextConfig = any type NextConfig = any
...@@ -65,6 +66,7 @@ export default class Server { ...@@ -65,6 +66,7 @@ export default class Server {
quiet: boolean quiet: boolean
nextConfig: NextConfig nextConfig: NextConfig
distDir: string distDir: string
pagesDir: string
publicDir: string publicDir: string
pagesManifest: string pagesManifest: string
buildId: string buildId: string
...@@ -95,6 +97,7 @@ export default class Server { ...@@ -95,6 +97,7 @@ export default class Server {
this.dir = resolve(dir) this.dir = resolve(dir)
this.quiet = quiet this.quiet = quiet
const phase = this.currentPhase() const phase = this.currentPhase()
this.pagesDir = findPagesDir(this.dir)
this.nextConfig = loadConfig(phase, this.dir, conf) this.nextConfig = loadConfig(phase, this.dir, conf)
this.distDir = join(this.dir, this.nextConfig.distDir) this.distDir = join(this.dir, this.nextConfig.distDir)
this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH) this.publicDir = join(this.dir, CLIENT_PUBLIC_FILES_PATH)
......
...@@ -110,10 +110,11 @@ function erroredPages (compilation, options = { enhanceName: name => name }) { ...@@ -110,10 +110,11 @@ function erroredPages (compilation, options = { enhanceName: name => name }) {
} }
export default class HotReloader { export default class HotReloader {
constructor (dir, { config, buildId } = {}) { constructor (dir, { config, pagesDir, buildId } = {}) {
this.buildId = buildId this.buildId = buildId
this.dir = dir this.dir = dir
this.middlewares = [] this.middlewares = []
this.pagesDir = pagesDir
this.webpackDevMiddleware = null this.webpackDevMiddleware = null
this.webpackHotMiddleware = null this.webpackHotMiddleware = null
this.initialized = false this.initialized = false
...@@ -204,10 +205,9 @@ export default class HotReloader { ...@@ -204,10 +205,9 @@ export default class HotReloader {
} }
async getWebpackConfig () { async getWebpackConfig () {
const pagesDir = join(this.dir, 'pages')
const pagePaths = await Promise.all([ const pagePaths = await Promise.all([
findPageFile(pagesDir, '/_app', this.config.pageExtensions), findPageFile(this.pagesDir, '/_app', this.config.pageExtensions),
findPageFile(pagesDir, '/_document', this.config.pageExtensions) findPageFile(this.pagesDir, '/_document', this.config.pageExtensions)
]) ])
const pages = createPagesMapping( const pages = createPagesMapping(
...@@ -235,6 +235,7 @@ export default class HotReloader { ...@@ -235,6 +235,7 @@ export default class HotReloader {
isServer: false, isServer: false,
config: this.config, config: this.config,
buildId: this.buildId, buildId: this.buildId,
pagesDir: this.pagesDir,
entrypoints: { ...entrypoints.client, ...additionalClientEntrypoints } entrypoints: { ...entrypoints.client, ...additionalClientEntrypoints }
}), }),
getBaseWebpackConfig(this.dir, { getBaseWebpackConfig(this.dir, {
...@@ -242,6 +243,7 @@ export default class HotReloader { ...@@ -242,6 +243,7 @@ export default class HotReloader {
isServer: true, isServer: true,
config: this.config, config: this.config,
buildId: this.buildId, buildId: this.buildId,
pagesDir: this.pagesDir,
entrypoints: entrypoints.server entrypoints: entrypoints.server
}) })
]) ])
...@@ -442,6 +444,7 @@ export default class HotReloader { ...@@ -442,6 +444,7 @@ export default class HotReloader {
{ {
dir: this.dir, dir: this.dir,
buildId: this.buildId, buildId: this.buildId,
pagesDir: this.pagesDir,
distDir: this.config.distDir, distDir: this.config.distDir,
reload: this.reload.bind(this), reload: this.reload.bind(this),
pageExtensions: this.config.pageExtensions, pageExtensions: this.config.pageExtensions,
......
...@@ -22,6 +22,7 @@ import React from 'react' ...@@ -22,6 +22,7 @@ import React from 'react'
import { findPageFile } from './lib/find-page-file' import { findPageFile } from './lib/find-page-file'
import { normalizePagePath } from '../next-server/server/normalize-page-path' import { normalizePagePath } from '../next-server/server/normalize-page-path'
import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../lib/constants' import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../lib/constants'
import { findPagesDir } from '../lib/find-pages-dir'
if (typeof React.Suspense === 'undefined') { if (typeof React.Suspense === 'undefined') {
throw new Error( throw new Error(
...@@ -51,7 +52,7 @@ export default class DevServer extends Server { ...@@ -51,7 +52,7 @@ export default class DevServer extends Server {
) )
}) })
} }
this.pagesDir = join(this.dir, 'pages') this.pagesDir = findPagesDir(this.dir)
} }
currentPhase () { currentPhase () {
...@@ -110,7 +111,7 @@ export default class DevServer extends Server { ...@@ -110,7 +111,7 @@ export default class DevServer extends Server {
let resolved = false let resolved = false
return new Promise(resolve => { return new Promise(resolve => {
const pagesDir = join(this.dir, 'pages') const pagesDir = this.pagesDir
// Watchpack doesn't emit an event for an empty directory // Watchpack doesn't emit an event for an empty directory
fs.readdir(pagesDir, (_, files) => { fs.readdir(pagesDir, (_, files) => {
...@@ -174,9 +175,10 @@ export default class DevServer extends Server { ...@@ -174,9 +175,10 @@ export default class DevServer extends Server {
} }
async prepare () { async prepare () {
await verifyTypeScriptSetup(this.dir) await verifyTypeScriptSetup(this.dir, this.pagesDir)
this.hotReloader = new HotReloader(this.dir, { this.hotReloader = new HotReloader(this.dir, {
pagesDir: this.pagesDir,
config: this.nextConfig, config: this.nextConfig,
buildId: this.buildId buildId: this.buildId
}) })
......
...@@ -32,9 +32,15 @@ function addEntry (compilation, context, name, entry) { ...@@ -32,9 +32,15 @@ function addEntry (compilation, context, name, entry) {
export default function onDemandEntryHandler ( export default function onDemandEntryHandler (
devMiddleware, devMiddleware,
multiCompiler, multiCompiler,
{ buildId, dir, reload, pageExtensions, maxInactiveAge, pagesBufferLength } {
buildId,
pagesDir,
reload,
pageExtensions,
maxInactiveAge,
pagesBufferLength
}
) { ) {
const pagesDir = join(dir, 'pages')
const { compilers } = multiCompiler const { compilers } = multiCompiler
const invalidator = new Invalidator(devMiddleware, multiCompiler) const invalidator = new Invalidator(devMiddleware, multiCompiler)
let entries = {} let entries = {}
......
module.exports = {
target: 'serverless',
experimental: {
modern: true
}
}
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import fs from 'fs-extra'
import {
renderViaHTTP,
findPort,
launchApp,
killApp,
nextBuild,
nextStart
} from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
let app
let appPort
const appDir = join(__dirname, '../')
function runTests (dev) {
it('should render from pages', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/PAGES/)
})
it('should render not render from src/pages', async () => {
const html = await renderViaHTTP(appPort, '/hello')
expect(html).toMatch(/404/)
})
}
const nextConfig = join(appDir, 'next.config.js')
describe('Dynamic Routing', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests(true)
})
describe('production mode', () => {
beforeAll(async () => {
const curConfig = await fs.readFile(nextConfig, 'utf8')
if (curConfig.includes('target')) {
await fs.writeFile(
nextConfig,
`
module.exports = {
experimental: { modern: true }
}
`
)
}
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('SSR production mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`
module.exports = {
target: 'serverless',
experimental: {
modern: true
}
}
`
)
await nextBuild(appDir)
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
})
module.exports = {
experimental: {
modern: true
}
}
import { useRouter } from 'next/router'
const $comment = ({ gipQuery }) => {
const router = useRouter()
const { query } = router
return (
<>
<p>
I am {query.comment} on {query.name}
</p>
<span>gip {gipQuery && gipQuery.name}</span>
</>
)
}
$comment.getInitialProps = async ({ query }) => {
return { gipQuery: query }
}
export default $comment
import { useRouter } from 'next/router'
const Page = () => {
const router = useRouter()
const { query } = router
return <p>Show comments for {query.name} here</p>
}
Page.getInitialProps = () => ({})
export default Page
import { useRouter } from 'next/router'
const Page = () => {
const router = useRouter()
const { query } = router
return <p>This is {query.name}</p>
}
Page.getInitialProps = () => ({})
export default Page
export default () => 'hello from another!'
import { useRouter } from 'next/router'
const Page = () => {
const router = useRouter()
const { name, id } = router.query
return (
<>
<p>
Blog post {name} comment {id || '(all)'}
</p>
</>
)
}
Page.getInitialProps = () => ({})
export default Page
import Link from 'next/link'
const Page = () => (
<div>
<h3>My blog</h3>
<Link href='/[post]' as='/post-1'>
<a id='view-post-1'>View post 1</a>
</Link>
<br />
<Link href='/[post]/comments' as='/post-1/comments'>
<a id='view-post-1-comments'>View post 1 comments</a>
</Link>
<br />
<Link href='/[post]/[comment]' as='/post-1/comment-1'>
<a id='view-post-1-comment-1'>View comment 1 on post 1</a>
</Link>
<br />
<Link href='/blog/[post]/comment/[id]' as='/blog/321/comment/123'>
<a id='view-nested-dynamic-cmnt'>View comment 123 on blog post 321</a>
</Link>
<br />
<Link href='/[post]?fromHome=true' as='/post-1?fromHome=true'>
<a id='view-post-1-with-query'>View post 1 with query</a>
</Link>
<br />
<Link href='/on-mount/[post]' as='/on-mount/test-w-hash#item-400'>
<a id='view-dynamic-with-hash'>View test with hash</a>
</Link>
</div>
)
export default Page
import { useRouter } from 'next/router'
export default () => {
const router = useRouter()
const { query } = router
return (
<>
<p>onmpost: {query.post || 'pending'}</p>
{Array.from({ length: 500 }, (x, i) => i + 1).map(i => {
return (
<div key={`item-${i}`} id={`item-${i}`}>
{i}
</div>
)
})}
</>
)
}
/* eslint-env jest */
/* global jasmine */
import webdriver from 'next-webdriver'
import { join } from 'path'
import fs from 'fs-extra'
import {
renderViaHTTP,
findPort,
launchApp,
killApp,
waitFor,
nextBuild,
nextStart
} from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
let app
let appPort
let buildId
const appDir = join(__dirname, '../')
const buildIdPath = join(appDir, '.next/BUILD_ID')
function runTests (dev) {
it('should render normal route', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/my blog/i)
})
it('should render another normal route', async () => {
const html = await renderViaHTTP(appPort, '/another')
expect(html).toMatch(/hello from another/)
})
it('should render dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/post-1')
expect(html).toMatch(/this is.*?post-1/i)
})
it('should prioritize a non-dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/post-1/comments')
expect(html).toMatch(/show comments for.*post-1.*here/i)
})
it('should render nested dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/post-1/comment-1')
expect(html).toMatch(/i am.*comment-1.*on.*post-1/i)
})
it('should render optional dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/blog/543/comment')
// expect(html).toMatch(/blog post.*543.*comment.*all/i)
expect(html).toMatch(/404/i)
})
it('should render nested optional dynamic page', async () => {
const html = await renderViaHTTP(appPort, '/blog/321/comment/123')
expect(html).toMatch(/blog post.*321.*comment.*123/i)
})
it('should render dynamic route with query', async () => {
const browser = await webdriver(appPort, '/')
await browser.elementByCss('#view-post-1-with-query').click()
await waitFor(1000)
const url = await browser.eval('window.location.search')
expect(url).toBe('?fromHome=true')
})
it('should navigate to a dynamic page successfully', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.elementByCss('#view-post-1').click()
await browser.waitForElementByCss('p')
const text = await browser.elementByCss('p').text()
expect(text).toMatch(/this is.*?post-1/i)
} finally {
if (browser) await browser.close()
}
})
// it('should navigate optional dynamic page', async () => {
// let browser
// try {
// browser = await webdriver(appPort, '/')
// await browser.elementByCss('#view-blog-post-1-comments').click()
// await browser.waitForElementByCss('p')
// const text = await browser.elementByCss('p').text()
// expect(text).toMatch(/blog post.*543.*comment.*\(all\)/i)
// } finally {
// if (browser) await browser.close()
// }
// })
it('should navigate optional dynamic page with value', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.elementByCss('#view-nested-dynamic-cmnt').click()
await browser.waitForElementByCss('p')
const text = await browser.elementByCss('p').text()
expect(text).toMatch(/blog post.*321.*comment.*123/i)
} finally {
if (browser) await browser.close()
}
})
it('should navigate to a nested dynamic page successfully', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.elementByCss('#view-post-1-comment-1').click()
await browser.waitForElementByCss('p')
const text = await browser.elementByCss('p').text()
expect(text).toMatch(/i am.*comment-1.*on.*post-1/i)
} finally {
if (browser) await browser.close()
}
})
it('should pass params in getInitialProps during SSR', async () => {
const html = await renderViaHTTP(appPort, '/post-1/cmnt-1')
expect(html).toMatch(/gip.*post-1/i)
})
it('should pass params in getInitialProps during client navigation', async () => {
let browser
try {
browser = await webdriver(appPort, '/')
await browser.elementByCss('#view-post-1-comment-1').click()
await browser.waitForElementByCss('span')
const text = await browser.elementByCss('span').text()
expect(text).toMatch(/gip.*post-1/i)
} finally {
if (browser) await browser.close()
}
})
it('should update dynamic values on mount', async () => {
const html = await renderViaHTTP(appPort, '/on-mount/post-1')
expect(html).toMatch(/onmpost:.*pending/)
const browser = await webdriver(appPort, '/on-mount/post-1')
await waitFor(1000)
const text = await browser.eval(`document.body.innerHTML`)
expect(text).toMatch(/onmpost:.*post-1/)
})
it('should not have placeholder query values for SSS', async () => {
const html = await renderViaHTTP(appPort, '/on-mount/post-1')
expect(html).not.toMatch(/post:.*?\[post\].*?<\/p>/)
})
it('should update with a hash in the URL', async () => {
const browser = await webdriver(appPort, '/on-mount/post-1#abc')
await waitFor(1000)
const text = await browser.eval(`document.body.innerHTML`)
expect(text).toMatch(/onmpost:.*post-1/)
})
it('should scroll to a hash on mount', async () => {
const browser = await webdriver(appPort, '/on-mount/post-1#item-400')
await waitFor(1000)
const text = await browser.eval(`document.body.innerHTML`)
expect(text).toMatch(/onmpost:.*post-1/)
const scrollPosition = await browser.eval('window.pageYOffset')
expect(scrollPosition).toBe(7232)
})
it('should scroll to a hash on client-side navigation', async () => {
const browser = await webdriver(appPort, '/')
await waitFor(1000)
await browser.elementByCss('#view-dynamic-with-hash').click()
await browser.waitForElementByCss('p')
const text = await browser.elementByCss('p').text()
expect(text).toMatch(/onmpost:.*test-w-hash/)
const scrollPosition = await browser.eval('window.pageYOffset')
expect(scrollPosition).toBe(7232)
})
if (dev) {
it('should work with HMR correctly', async () => {
const browser = await webdriver(appPort, '/post-1/comments')
let text = await browser.eval(`document.documentElement.innerHTML`)
expect(text).toMatch(/comments for.*post-1/)
const page = join(appDir, 'src/pages/[name]/comments.js')
const origContent = await fs.readFile(page, 'utf8')
const newContent = origContent.replace(/comments/, 'commentss')
try {
await fs.writeFile(page, newContent, 'utf8')
await waitFor(3 * 1000)
let text = await browser.eval(`document.documentElement.innerHTML`)
expect(text).toMatch(/commentss for.*post-1/)
} finally {
await fs.writeFile(page, origContent, 'utf8')
if (browser) await browser.close()
}
})
} else {
it('should output modern bundles with dynamic route correctly', async () => {
const bundlePath = join(
appDir,
'.next/static/',
buildId,
'pages/blog/[name]/comment/[id]'
)
await fs.access(bundlePath + '.js', fs.constants.F_OK)
await fs.access(bundlePath + '.module.js', fs.constants.F_OK)
})
}
}
const nextConfig = join(appDir, 'next.config.js')
describe('Dynamic Routing', () => {
describe('dev mode', () => {
beforeAll(async () => {
appPort = await findPort()
app = await launchApp(appDir, appPort)
})
afterAll(() => killApp(app))
runTests(true)
})
describe('production mode', () => {
beforeAll(async () => {
const curConfig = await fs.readFile(nextConfig, 'utf8')
if (curConfig.includes('target')) {
await fs.writeFile(
nextConfig,
`
module.exports = {
experimental: { modern: true }
}
`
)
}
await nextBuild(appDir)
buildId = await fs.readFile(buildIdPath, 'utf8')
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
describe('SSR production mode', () => {
beforeAll(async () => {
await fs.writeFile(
nextConfig,
`
module.exports = {
target: 'serverless',
experimental: {
modern: true
}
}
`
)
await nextBuild(appDir)
buildId = await fs.readFile(buildIdPath, 'utf8')
appPort = await findPort()
app = await nextStart(appDir, appPort)
})
afterAll(() => killApp(app))
runTests()
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment