Skip to content

Commit

Permalink
Add configuration to specify the name of the pages directory.
Browse files Browse the repository at this point in the history
  • Loading branch information
George Pantazis committed Jan 30, 2017
1 parent db50fc7 commit ecedf64
Show file tree
Hide file tree
Showing 14 changed files with 77 additions and 40 deletions.
11 changes: 7 additions & 4 deletions bin/next-build
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import { resolve, join } from 'path'
import { existsSync } from 'fs'
import parseArgs from 'minimist'
import getConfig from '../server/config'
import build from '../server/build'
import { printAndExit } from '../lib/utils'

Expand Down Expand Up @@ -29,18 +30,20 @@ if (argv.help) {
}

const dir = resolve(argv._[0] || '.')
const config = getConfig(dir)
const pagesDirectory = config.pagesDirectory

// Check if pages dir exists and warn if not
if (!existsSync(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?')
if (!existsSync(join(dir, pagesDirectory))) {
if (existsSync(join(dir, '..', pagesDirectory))) {
printAndExit(`> No \`${pagesDirectory}\` 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')
printAndExit(`> Couldn't find a \`${pagesDirectory}\` directory. Please create one under the project root`)
}

build(dir)
Expand Down
11 changes: 7 additions & 4 deletions bin/next-dev
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { resolve, join } from 'path'
import parseArgs from 'minimist'
import { existsSync } from 'fs'
import Server from '../server'
import getConfig from '../server/config'
import { printAndExit } from '../lib/utils'

process.env.NODE_ENV = process.env.NODE_ENV || 'development'
Expand Down Expand Up @@ -39,18 +40,20 @@ if (argv.help) {
}

const dir = resolve(argv._[0] || '.')
const config = getConfig(dir)
const pagesDirectory = config.pagesDirectory

// Check if pages dir exists and warn if not
if (!existsSync(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?')
if (!existsSync(join(dir, pagesDirectory))) {
if (existsSync(join(dir, '..', pagesDirectory))) {
printAndExit(`> No \`${pagesDirectory}\` 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')
printAndExit(`> Couldn't find a \`${pagesDirectory}\` directory. Please create one under the project root`)
}

const srv = new Server({ dir, dev: true })
Expand Down
13 changes: 8 additions & 5 deletions bin/next-init
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { resolve, join, basename } from 'path'
import parseArgs from 'minimist'
import { exists, writeFile, mkdir } from 'mz/fs'
import mkdirp from 'mkdirp-then'
import getConfig from '../server/config'

const argv = parseArgs(process.argv.slice(2), {
alias: {
Expand All @@ -29,9 +30,11 @@ if (argv.help) {
}

const dir = resolve(argv._[0] || '.')
const config = getConfig(dir)
const pagesDirectory = config.pagesDirectory

if (basename(dir) === 'pages') {
console.warn('Your root directory is named "pages". This looks suspicious. You probably want to go one directory up.')
if (basename(dir) === pagesDirectory) {
console.warn(`Your root directory is named "${pagesDirectory}". This looks suspicious. You probably want to go one directory up.`)
process.exit(1)
}

Expand All @@ -49,9 +52,9 @@ exists(dir)
await mkdir(join(dir, 'static'))
}

if (!await exists(join(dir, 'pages'))) {
await mkdir(join(dir, 'pages'))
await writeFile(join(dir, 'pages', 'index.js'), basePage)
if (!await exists(join(dir, pagesDirectory))) {
await mkdir(join(dir, pagesDirectory))
await writeFile(join(dir, pagesDirectory, 'index.js'), basePage)
}
})
.catch((err) => {
Expand Down
2 changes: 1 addition & 1 deletion lib/prefetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ if (hasServiceWorkerSupport()) {

function getPrefetchUrl (href) {
let { pathname } = urlParse(href)
const url = `/_next/${__NEXT_DATA__.buildId}/pages${pathname}`
const url = `/_next/${__NEXT_DATA__.buildId}/${__NEXT_DATA__.pagesDirectory}${pathname}`

return url
}
Expand Down
2 changes: 1 addition & 1 deletion lib/router/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export default class Router extends EventEmitter {
}
}

const url = `/_next/${__NEXT_DATA__.buildId}/pages${route}`
const url = `/_next/${__NEXT_DATA__.buildId}/${__NEXT_DATA__.pagesDirectory}${route}`
const xhr = loadComponent(url, (err, data) => {
if (err) return reject(err)
resolve({ ...data, xhr })
Expand Down
5 changes: 4 additions & 1 deletion server/build/gzip.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@ import fs from 'fs'
import path from 'path'
import zlib from 'zlib'
import glob from 'glob-promise'
import getConfig from '../config'

export default async function gzipAssets (dir) {
const nextDir = path.resolve(dir, '.next')
const config = getConfig(dir)
const pagesDirectory = config.pagesDirectory

const coreAssets = [
path.join(nextDir, 'commons.js'),
path.join(nextDir, 'main.js')
]
const pages = await glob('bundles/pages/**/*.json', { cwd: nextDir })
const pages = await glob(`bundles/${pagesDirectory}/**/*.json`, { cwd: nextDir })

const allAssets = [
...coreAssets,
Expand Down
5 changes: 4 additions & 1 deletion server/build/loaders/hot-self-accept-loader.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { resolve, relative } from 'path'
import getConfig from '../../config'

module.exports = function (content, sourceMap) {
this.cacheable()
Expand Down Expand Up @@ -34,7 +35,9 @@ module.exports = function (content, sourceMap) {
const nextPagesDir = resolve(__dirname, '..', '..', '..', 'pages')

function getRoute (loaderContext) {
const pagesDir = resolve(loaderContext.options.context, 'pages')
const config = getConfig(loaderContext.options.context)
const pagesDirectory = config.pagesDirectory
const pagesDir = resolve(loaderContext.options.context, pagesDirectory)
const { resourcePath } = loaderContext
const dir = [pagesDir, nextPagesDir]
.find((d) => resourcePath.indexOf(d) === 0)
Expand Down
11 changes: 10 additions & 1 deletion server/build/plugins/json-pages-plugin.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import getConfig from '../../config'

export default class JsonPagesPlugin {
constructor (dir) {
this.config = getConfig(dir)
}

apply (compiler) {
compiler.plugin('after-compile', (compilation, callback) => {
const regex = new RegExp(`^bundles/${this.config.pagesDirectory}.*.js$`)
const pages = Object
.keys(compilation.assets)
.filter((filename) => /^bundles[/\\]pages.*\.js$/.test(filename))
.filter((filename) => {
return filename.match(regex)
})

pages.forEach((pageName) => {
const page = compilation.assets[pageName]
Expand Down
10 changes: 5 additions & 5 deletions server/build/plugins/watch-pages-plugin.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { resolve, join } from 'path'
import { join } from 'path'
import getConfig from '../../config'

export default class WatchPagesPlugin {
constructor (dir) {
this.dir = resolve(dir, 'pages')
this.config = getConfig(dir)
}

apply (compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.plugin('optimize-assets', (assets, callback) => {
// transpile pages/_document.js and descendants,
// but don't need the bundle file
delete assets[join('bundles', 'pages', '_document.js')]
delete assets[join('bundles', this.config.pagesDirectory, '_document.js')]
callback()
})
})
Expand All @@ -19,10 +20,9 @@ export default class WatchPagesPlugin {
// watch the pages directory
compilation.contextDependencies = [
...compilation.contextDependencies,
this.dir
this.config.pagesDirectory
]
callback()
})
}
}

14 changes: 7 additions & 7 deletions server/build/webpack.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ const defaultPages = [
]
const nextPagesDir = join(__dirname, '..', '..', 'pages')
const nextNodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules')
const interpolateNames = new Map(defaultPages.map((p) => {
return [join(nextPagesDir, p), `dist/pages/${p}`]
}))

export default async function createCompiler (dir, { dev = false, quiet = false } = {}) {
dir = resolve(dir)
Expand All @@ -29,19 +26,22 @@ export default async function createCompiler (dir, { dev = false, quiet = false
? [join(__dirname, '..', '..', 'client/webpack-hot-middleware-client')] : []
const mainJS = dev
? require.resolve('../../client/next-dev') : require.resolve('../../client/next')
const interpolateNames = new Map(defaultPages.map((p) => {
return [join(nextPagesDir, p), `dist/${config.pagesDirectory}/${p}`]
}))

let minChunks

const entry = async () => {
const entries = { 'main.js': mainJS }

const pages = await glob('pages/**/*.js', { cwd: dir })
const pages = await glob(`${config.pagesDirectory}/**/*.js`, { cwd: dir })
for (const p of pages) {
entries[join('bundles', p)] = [...defaultEntries, `./${p}?entry`]
}

for (const p of defaultPages) {
const entryName = join('bundles', 'pages', p)
const entryName = join('bundles', config.pagesDirectory, p)
if (!entries[entryName]) {
entries[entryName] = [...defaultEntries, join(nextPagesDir, p) + '?entry']
}
Expand Down Expand Up @@ -77,7 +77,7 @@ export default async function createCompiler (dir, { dev = false, quiet = false
return count >= minChunks
}
}),
new JsonPagesPlugin(),
new JsonPagesPlugin(dir),
new CaseSensitivePathPlugin()
]

Expand Down Expand Up @@ -125,7 +125,7 @@ export default async function createCompiler (dir, { dev = false, quiet = false
test: /\.js(\?[^?]*)?$/,
loader: 'hot-self-accept-loader',
include: [
join(dir, 'pages'),
join(dir, config.pagesDirectory),
nextPagesDir
]
}, {
Expand Down
3 changes: 2 additions & 1 deletion server/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ const cache = new Map()

const defaultConfig = {
webpack: null,
poweredByHeader: true
poweredByHeader: true,
pagesDirectory: 'pages'
}

export default function getConfig (dir) {
Expand Down
4 changes: 3 additions & 1 deletion server/hot-reloader.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import isWindowsBash from 'is-windows-bash'
import webpack from './build/webpack'
import clean from './build/clean'
import readPage from './read-page'
import getConfig from './config'

export default class HotReloader {
constructor (dir, { quiet } = {}) {
Expand All @@ -20,6 +21,7 @@ export default class HotReloader {
this.prevChunkNames = null
this.prevFailedChunkNames = null
this.prevChunkHashes = null
this.config = getConfig(dir)
}

async run (req, res) {
Expand Down Expand Up @@ -96,7 +98,7 @@ export default class HotReloader {
// and to update error content
const failed = failedChunkNames

const rootDir = join('bundles', 'pages')
const rootDir = join('bundles', this.config.pagesDirectory)

for (const n of new Set([...added, ...removed, ...failed, ...succeeded])) {
const route = toRoute(relative(rootDir, n))
Expand Down
4 changes: 2 additions & 2 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export default class Server {
await this.serveStaticWithGzip(req, res, p)
},

'/_next/:buildId/pages/:path*': async (req, res, params) => {
[`/_next/:buildId/${this.config.pagesDirectory}/:path*`]: async (req, res, params) => {
this.handleBuildId(params.buildId, res)
const paths = params.path || ['index']
const pathname = `/${paths.join('/')}`
Expand Down Expand Up @@ -298,7 +298,7 @@ export default class Server {
const errors = this.hotReloader.getCompilationErrors()
if (!errors.size) return

const id = join(this.dir, '.next', 'bundles', 'pages', page)
const id = join(this.dir, '.next', 'bundles', this.config.pagesDirectory, page)
const p = resolveFromList(id, errors.keys())
if (p) return errors.get(p)[0]
}
Expand Down
22 changes: 16 additions & 6 deletions server/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import send from 'send'
import fs from 'mz/fs'
import accepts from 'accepts'
import mime from 'mime-types'
import getConfig from './config'
import requireModule from './require'
import resolvePath from './resolve'
import readPage from './read-page'
Expand Down Expand Up @@ -39,10 +40,14 @@ async function doRender (req, res, pathname, query, {
dev = false,
staticMarkup = false
} = {}) {
const config = getConfig(dir)
const pagesDirectory = config.pagesDirectory

page = page || pathname

let [Component, Document] = await Promise.all([
requireModule(join(dir, '.next', 'dist', 'pages', page)),
requireModule(join(dir, '.next', 'dist', 'pages', '_document'))
requireModule(join(dir, '.next', 'dist', pagesDirectory, page)),
requireModule(join(dir, '.next', 'dist', pagesDirectory, '_document'))
])
Component = Component.default || Component
Document = Document.default || Document
Expand All @@ -54,8 +59,8 @@ async function doRender (req, res, pathname, query, {
errorComponent
] = await Promise.all([
loadGetInitialProps(Component, ctx),
readPage(join(dir, '.next', 'bundles', 'pages', page)),
readPage(join(dir, '.next', 'bundles', 'pages', '_error'))
readPage(join(dir, '.next', 'bundles', pagesDirectory, page)),
readPage(join(dir, '.next', 'bundles', pagesDirectory, '_error'))
])

// the response might be finshed on the getinitialprops call
Expand Down Expand Up @@ -93,6 +98,7 @@ async function doRender (req, res, pathname, query, {
pathname,
query,
buildId,
pagesDirectory,
err: (err && dev) ? errorToJSON(err) : null
},
dev,
Expand All @@ -104,12 +110,16 @@ async function doRender (req, res, pathname, query, {
}

export async function renderJSON (req, res, page, { dir = process.cwd() } = {}) {
const pagePath = await resolvePath(join(dir, '.next', 'bundles', 'pages', page))
const config = getConfig(dir)
const pagesDirectory = config.pagesDirectory
const pagePath = await resolvePath(join(dir, '.next', 'bundles', pagesDirectory, page))
return serveStaticWithGzip(req, res, pagePath)
}

export async function renderErrorJSON (err, req, res, { dir = process.cwd(), dev = false } = {}) {
const component = await readPage(join(dir, '.next', 'bundles', 'pages', '_error'))
const config = getConfig(dir)
const pagesDirectory = config.pagesDirectory
const component = await readPage(join(dir, '.next', 'bundles', pagesDirectory, '_error'))

sendJSON(res, {
component,
Expand Down

0 comments on commit ecedf64

Please sign in to comment.