Commit 4a71fb6b authored by nkzawa's avatar nkzawa

Merge branch 'master' into pr/264

parents 825d1878 fc369fa2
The MIT License (MIT)
Copyright (c) 2016 Zeit, Inc. developers
Copyright (c) 2016 Zeit, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
......
......@@ -67,7 +67,7 @@ Glamor's [HowTo](https://github.com/threepointone/glamor/blob/master/docs/howto.
```jsx
import React from 'react'
import css, {insertRule} from 'next/css'
import css from 'next/css'
export default () => (
<div className={style}>
......@@ -75,9 +75,6 @@ export default () => (
</div>
)
// Global CSS rule
insertRule("html, body { margin: 0; padding: 0; }")
const style = css({
background: 'red',
':hover': {
......@@ -89,6 +86,10 @@ const style = css({
})
```
### Images and other static files
Create a folder called `static` in your project root directory. From your code you can then reference those files with `/static/` URLs, e.g.: `<img src="/static/file-name.jpg" />`.
### `<head>` side effects
We expose a built-in component for appending elements to the `<head>` of the page.
......@@ -187,13 +188,17 @@ import React from 'react'
export default class Error extends React.Component {
static getInitialProps ({ res, xhr }) {
const statusCode = res ? res.statusCode : xhr.status
const statusCode = res ? res.statusCode : (xhr ? xhr.status : null)
return { statusCode }
}
render () {
return (
<p>An error { this.props.statusCode } occurred</p>
<p>{
this.props.statusCode
? `An error ${this.props.statusCode} occurred on server`
: 'An error occurred on client'
]</p>
)
}
}
......
import HTMLDOMPropertyConfig from 'react/lib/HTMLDOMPropertyConfig'
import HTMLDOMPropertyConfig from 'react-dom/lib/HTMLDOMPropertyConfig'
const DEFAULT_TITLE = ''
......
import 'react-hot-loader/patch'
import './webpack-dev-client?http://localhost:3030'
import * as next from './next'
module.exports = next
import { requireModule } from '../lib/eval-script'
window.next = next
module.exports = requireModule
......@@ -3,21 +3,34 @@ import { render } from 'react-dom'
import HeadManager from './head-manager'
import { rehydrate } from '../lib/css'
import Router from '../lib/router'
import DefaultApp from '../lib/app'
import evalScript from '../lib/eval-script'
import App from '../lib/app'
import evalScript, { requireModule } from '../lib/eval-script'
const {
__NEXT_DATA__: { app, component, props, ids, err }
__NEXT_DATA__: { component, errorComponent, props, ids, err }
} = window
const App = app ? evalScript(app).default : DefaultApp
const Component = evalScript(component).default
document.addEventListener('DOMContentLoaded', () => {
const Component = evalScript(component).default
const ErrorComponent = evalScript(errorComponent).default
export const router = new Router(window.location.href, { Component, ctx: { err } })
const router = new Router(window.location.href, {
Component,
ErrorComponent,
ctx: { err }
})
const headManager = new HeadManager()
const container = document.getElementById('__next')
const appProps = { Component, props, router, headManager }
// This it to support error handling in the dev time with hot code reload.
if (window.next) {
window.next.router = router
}
rehydrate(ids)
render(createElement(App, appProps), container)
const headManager = new HeadManager()
const container = document.getElementById('__next')
const appProps = { Component, props, router, headManager }
rehydrate(ids)
render(createElement(App, appProps), container)
})
module.exports = requireModule
/* global __resourceQuery, next */
// Based on 'webpack-dev-server/client'
import url from 'url'
import stripAnsi from 'strip-ansi'
import socket from './socket'
function getCurrentScriptSource () {
// `document.currentScript` is the most accurate way to find the current script,
// but is not supported in all browsers.
if (document.currentScript) {
return document.currentScript.getAttribute('src')
}
// Fall back to getting all scripts in the document.
const scriptElements = document.scripts || []
const currentScript = scriptElements[scriptElements.length - 1]
if (currentScript) {
return currentScript.getAttribute('src')
}
// Fail as there was no script to use.
throw new Error('[WDS] Failed to get current script source')
}
let urlParts
if (typeof __resourceQuery === 'string' && __resourceQuery) {
// If this bundle is inlined, use the resource query to get the correct url.
urlParts = url.parse(__resourceQuery.substr(1))
} else {
// Else, get the url from the <script> this file was called with.
let scriptHost = getCurrentScriptSource()
scriptHost = scriptHost.replace(/\/[^\/]+$/, '')
urlParts = url.parse(scriptHost || '/', false, true)
}
let hot = false
let initial = true
let currentHash = ''
let logLevel = 'info'
function log (level, msg) {
if (logLevel === 'info' && level === 'info') {
return console.log(msg)
}
if (['info', 'warning'].indexOf(logLevel) >= 0 && level === 'warning') {
return console.warn(msg)
}
if (['info', 'warning', 'error'].indexOf(logLevel) >= 0 && level === 'error') {
return console.error(msg)
}
}
const onSocketMsg = {
hot () {
hot = true
log('info', '[WDS] Hot Module Replacement enabled.')
},
invalid () {
log('info', '[WDS] App updated. Recompiling...')
},
hash (hash) {
currentHash = hash
},
'still-ok': () => {
log('info', '[WDS] Nothing changed.')
},
'log-level': (level) => {
logLevel = level
},
ok () {
if (initial) {
initial = false
return
}
reloadApp()
},
warnings (warnings) {
log('info', '[WDS] Warnings while compiling.')
for (let i = 0; i < warnings.length; i++) {
console.warn(stripAnsi(warnings[i]))
}
if (initial) {
initial = false
return
}
reloadApp()
},
errors (errors) {
log('info', '[WDS] Errors while compiling.')
for (let i = 0; i < errors.length; i++) {
console.error(stripAnsi(errors[i]))
}
if (initial) {
initial = false
return
}
reloadApp()
},
'proxy-error': (errors) => {
log('info', '[WDS] Proxy error.')
for (let i = 0; i < errors.length; i++) {
log('error', stripAnsi(errors[i]))
}
if (initial) {
initial = false
return
}
},
reload (route) {
if (route === '/_error') {
for (const r of Object.keys(next.router.components)) {
const { Component } = next.router.components[r]
if (Component.__route === '/_error-debug') {
// reload all '/_error-debug'
// which are expected to be errors of '/_error' routes
next.router.reload(r)
}
}
return
}
next.router.reload(route)
},
close () {
log('error', '[WDS] Disconnected!')
}
}
let hostname = urlParts.hostname
let protocol = urlParts.protocol
if (urlParts.hostname === '0.0.0.0') {
// why do we need this check?
// hostname n/a for file protocol (example, when using electron, ionic)
// see: https://github.com/webpack/webpack-dev-server/pull/384
if (window.location.hostname && !!~window.location.protocol.indexOf('http')) {
hostname = window.location.hostname
}
}
// `hostname` can be empty when the script path is relative. In that case, specifying
// a protocol would result in an invalid URL.
// When https is used in the app, secure websockets are always necessary
// because the browser doesn't accept non-secure websockets.
if (hostname && (window.location.protocol === 'https:' || urlParts.hostname === '0.0.0.0')) {
protocol = window.location.protocol
}
const socketUrl = url.format({
protocol,
auth: urlParts.auth,
hostname,
port: (urlParts.port === '0') ? window.location.port : urlParts.port,
pathname: urlParts.path == null || urlParts.path === '/' ? '/sockjs-node' : urlParts.path
})
socket(socketUrl, onSocketMsg)
function reloadApp () {
if (hot) {
log('info', '[WDS] App hot update...')
window.postMessage('webpackHotUpdate' + currentHash, '*')
} else {
log('info', '[WDS] App updated. Reloading...')
window.location.reload()
}
}
import SockJS from 'sockjs-client'
let retries = 0
let sock = null
export default function socket (url, handlers) {
sock = new SockJS(url)
sock.onopen = () => {
retries = 0
}
sock.onclose = () => {
if (retries === 0) handlers.close()
// Try to reconnect.
sock = null
// After 10 retries stop trying, to prevent logspam.
if (retries <= 10) {
// Exponentially increase timeout to reconnect.
// Respectfully copied from the package `got`.
const retryInMs = 1000 * Math.pow(2, retries) + Math.random() * 100
retries += 1
setTimeout(() => {
socket(url, handlers)
}, retryInMs)
}
}
sock.onmessage = (e) => {
// This assumes that all data sent via the websocket is JSON.
const msg = JSON.parse(e.data)
if (handlers[msg.type]) {
handlers[msg.type](msg.data)
}
}
}
/* global next */
import webpackHotMiddlewareClient from 'webpack-hot-middleware/client?overlay=false&reload=true'
const handlers = {
reload (route) {
if (route === '/_error') {
for (const r of Object.keys(next.router.components)) {
const { Component } = next.router.components[r]
if (Component.__route === '/_error-debug') {
// reload all '/_error-debug'
// which are expected to be errors of '/_error' routes
next.router.reload(r)
}
}
return
}
next.router.reload(route)
},
change (route) {
const { Component } = next.router.components[route] || {}
if (Component && Component.__route === '/_error-debug') {
// reload to recover from runtime errors
next.router.reload(route)
}
}
}
webpackHotMiddlewareClient.subscribe((obj) => {
const fn = handlers[obj.action]
if (fn) {
const data = obj.data || []
fn(...data)
} else {
throw new Error('Unexpected action ' + obj.action)
}
})
# Example app using shared modules
This example features:
* An app with two pages which has a common Counter component
* That Counter component maintain the counter inside its module.
## How to run it
```sh
npm install
npm run dev
```
import React from 'react'
let count = 0
export default class Counter extends React.Component {
add () {
count += 1
this.forceUpdate()
}
render () {
return (
<div>
<p>Count is: {count}</p>
<button onClick={() => this.add()}>Add</button>
</div>
)
}
}
import React from 'react'
import Link from 'next/link'
const styles = {
a: {
marginRight: 10
}
}
export default () => (
<div>
<Link href='/'>
<a style={styles.a} >Home</a>
</Link>
<Link href='/about'>
<a style={styles.a} >About</a>
</Link>
</div>
)
{
"name": "shared-modules",
"version": "1.0.0",
"description": "This example features:",
"main": "index.js",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "*"
},
"author": "",
"license": "ISC",
"next": {
"cdn": false
}
}
import React from 'react'
import Header from '../components/Header'
import Counter from '../components/Counter'
export default () => (
<div>
<Header />
<p>This is the about page.</p>
<Counter />
</div>
)
import React from 'react'
import Header from '../components/Header'
import Counter from '../components/Counter'
export default () => (
<div>
<Header />
<p>HOME PAGE is here!</p>
<Counter />
</div>
)
......@@ -100,7 +100,7 @@ gulp.task('build-dev-client', ['compile-lib', 'compile-client'], () => {
.src('dist/client/next-dev.js')
.pipe(webpack({
quiet: true,
output: { filename: 'next-dev.bundle.js' },
output: { filename: 'next-dev.bundle.js', libraryTarget: 'var', library: 'require' },
module: {
loaders: [
{
......@@ -125,7 +125,7 @@ gulp.task('build-client', ['compile-lib', 'compile-client'], () => {
.src('dist/client/next.js')
.pipe(webpack({
quiet: true,
output: { filename: 'next.bundle.js' },
output: { filename: 'next.bundle.js', libraryTarget: 'var', library: 'require' },
plugins: [
new webpack.webpack.DefinePlugin({
'process.env': {
......@@ -169,7 +169,8 @@ gulp.task('watch', [
'watch-bin',
'watch-lib',
'watch-server',
'watch-client'
'watch-client',
'watch-pages'
])
gulp.task('watch-bin', () => {
......@@ -198,6 +199,12 @@ gulp.task('watch-client', () => {
])
})
gulp.task('watch-pages', () => {
return gulp.watch('pages/**/*.js', [
'copy-pages'
])
})
gulp.task('clean', () => {
return del('dist')
})
......
......@@ -10,8 +10,11 @@ export default ({ head, css, html, data, dev, staticMarkup, cdn }) => {
</head>
<body>
<div id='__next' dangerouslySetInnerHTML={{ __html: html }} />
{staticMarkup ? null : <script dangerouslySetInnerHTML={{ __html: '__NEXT_DATA__ = ' + htmlescape(data) }} />}
{staticMarkup ? null : <script dangerouslySetInnerHTML={{
__html: `__NEXT_DATA__ =${htmlescape(data)}; module={};`
}} />}
{staticMarkup ? null : createClientScript({ dev, cdn })}
<script type='text/javascript' src='/_next/commons.js' />
</body>
</html>
}
......@@ -30,7 +33,6 @@ function createClientScript ({ dev, cdn }) {
load('https://cdn.zeit.co/next.js/${pkg.version}/next.min.js', function (err) {
if (err) load('/_next/next.bundle.js')
})
function load (src, fn) {
fn = fn || function () {}
var script = document.createElement('script')
......
......@@ -14,6 +14,17 @@ const modules = new Map([
['next/head', Head]
])
function require (moduleName) {
const name = moduleName
const m = modules.get(name)
if (m) return m
throw new Error(`Module "${moduleName}" is not exists in the bundle`)
}
export const requireModule = require
/**
* IMPORTANT: This module is compiled *without* `use strict`
* so that when we `eval` a dependency below, we don't enforce
......@@ -28,10 +39,6 @@ const modules = new Map([
export default function evalScript (script) {
const module = { exports: {} }
const require = function (path) { // eslint-disable-line no-unused-vars
return modules.get(path)
}
// don't use Function() here since it changes source locations
eval(script) // eslint-disable-line no-eval
return module.exports
}
......@@ -11,6 +11,10 @@ class Head extends React.Component {
}
}
export function defaultHead () {
return [<meta charSet='utf-8' className='next-head' />]
}
function reduceComponents (components) {
return components
.map((c) => c.props.children)
......@@ -18,6 +22,7 @@ function reduceComponents (components) {
.map((children) => React.Children.toArray(children))
.reduce((a, b) => a.concat(b), [])
.reverse()
.concat(...defaultHead())
.filter(unique())
.reverse()
.map((c) => {
......
......@@ -3,15 +3,16 @@ import evalScript from './eval-script'
import shallowEquals from './shallow-equals'
export default class Router {
constructor (url, initialData) {
constructor (url, { Component, ErrorComponent, ctx } = {}) {
const parsed = parse(url, true)
// represents the current component key
this.route = toRoute(parsed.pathname)
// set up the component cache (by route keys)
this.components = { [this.route]: initialData }
this.components = { [this.route]: { Component, ctx } }
this.ErrorComponent = ErrorComponent
this.pathname = parsed.pathname
this.query = parsed.query
this.subscriptions = new Set()
......@@ -38,13 +39,19 @@ export default class Router {
this.route = route
this.set(getURL(), { ...data, props })
})
.catch((err) => {
.catch(async (err) => {
if (err.cancelled) return
// the only way we can appropriately handle
// this failure is deferring to the browser
// since the URL has already changed
window.location.reload()
const data = { Component: this.ErrorComponent, ctx: { err } }
const ctx = { ...data.ctx, pathname, query }
const props = await this.getInitialProps(data.Component, ctx)
this.route = route
this.set(getURL(), { ...data, props })
console.error(err)
})
.catch((err) => {
console.error(err)
})
}
......@@ -67,16 +74,25 @@ export default class Router {
let data
let props
let _err
try {
data = await this.fetchComponent(route)
const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx)
} catch (err) {
if (err.cancelled) return false
throw err
data = { Component: this.ErrorComponent, ctx: { err } }
const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx)
_err = err
console.error(err)
}
this.notify({ ...data, props })
if (_err) throw _err
}
back () {
......@@ -100,13 +116,20 @@ export default class Router {
let data
let props
let _err
try {
data = await this.fetchComponent(route)
const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx)
} catch (err) {
if (err.cancelled) return false
throw err
data = { Component: this.ErrorComponent, ctx: { err } }
const ctx = { ...data.ctx, pathname, query }
props = await this.getInitialProps(data.Component, ctx)
_err = err
console.error(err)
}
if (getURL() !== url) {
......@@ -115,6 +138,9 @@ export default class Router {
this.route = route
this.set(url, { ...data, props })
if (_err) throw _err
return true
}
......
{
"name": "next",
"version": "1.1.1",
"version": "1.1.2",
"description": "Minimalistic framework for server-rendered React applications",
"main": "./dist/lib/index.js",
"license": "MIT",
......@@ -22,72 +22,64 @@
"precommit": "npm run lint"
},
"ava": {
"babel": {
"presets": [
"es2015",
"react"
],
"plugins": [
"transform-async-to-generator",
"transform-object-rest-spread",
"transform-class-properties",
"transform-runtime"
]
}
"babel": {}
},
"standard": {
"parser": "babel-eslint"
},
"dependencies": {
"ansi-html": "0.0.6",
"babel-core": "6.17.0",
"babel-generator": "6.17.0",
"babel-loader": "6.2.5",
"babel-plugin-module-resolver": "2.3.0",
"babel-core": "6.18.2",
"babel-generator": "6.19.0",
"babel-loader": "6.2.8",
"babel-plugin-module-resolver": "2.4.0",
"babel-plugin-react-require": "^3.0.0",
"babel-plugin-transform-async-to-generator": "6.16.0",
"babel-plugin-transform-class-properties": "6.16.0",
"babel-plugin-transform-object-rest-spread": "6.16.0",
"babel-plugin-transform-class-properties": "6.19.0",
"babel-plugin-transform-object-rest-spread": "6.19.0",
"babel-plugin-transform-runtime": "6.15.0",
"babel-preset-es2015": "6.16.0",
"babel-preset-es2015": "6.18.0",
"babel-preset-react": "6.16.0",
"babel-runtime": "6.11.6",
"cross-spawn": "4.0.2",
"babel-runtime": "6.18.0",
"cross-spawn": "5.0.1",
"del": "2.2.2",
"friendly-errors-webpack-plugin": "1.1.0",
"glamor": "2.17.10",
"glob-promise": "1.0.6",
"glamor": "2.20.8",
"glob-promise": "2.0.0",
"htmlescape": "1.1.1",
"is-windows-bash": "1.0.2",
"json-loader": "0.5.4",
"loader-utils": "0.2.16",
"minimist": "1.2.0",
"mkdirp-then": "1.2.0",
"mz": "2.4.0",
"mz": "2.6.0",
"path-match": "1.2.4",
"react": "15.3.2",
"react-dom": "15.3.2",
"react": "15.4.1",
"react-dom": "15.4.1",
"react-hot-loader": "3.0.0-beta.6",
"send": "0.14.1",
"sockjs-client": "1.1.1",
"strip-ansi": "3.0.1",
"url": "0.11.0",
"webpack": "1.13.2",
"webpack-dev-server": "1.16.2",
"write-file-webpack-plugin": "3.3.0"
"webpack": "1.13.3",
"webpack-dev-middleware": "1.8.4",
"webpack-hot-middleware": "2.13.2",
"write-file-webpack-plugin": "3.4.2"
},
"devDependencies": {
"ava": "0.16.0",
"babel-eslint": "7.0.0",
"ava": "0.17.0",
"babel-eslint": "7.1.1",
"babel-plugin-transform-remove-strict-mode": "0.0.2",
"benchmark": "2.1.1",
"benchmark": "2.1.2",
"gulp": "3.9.1",
"gulp-ava": "0.14.1",
"gulp-ava": "0.15.0",
"gulp-babel": "6.1.2",
"gulp-benchmark": "1.1.1",
"gulp-cached": "1.1.0",
"gulp-cached": "1.1.1",
"gulp-notify": "2.2.0",
"husky": "0.11.9",
"run-sequence": "1.2.2",
"standard": "8.4.0",
"standard": "8.6.0",
"webpack-stream": "3.2.0"
}
}
......@@ -5,12 +5,12 @@ import style from 'next/css'
export default class ErrorDebug extends React.Component {
static getInitialProps ({ err }) {
const { message, module } = err
return { message, path: module.rawRequest }
const { name, message, stack, module } = err
return { name, message, stack, path: module ? module.rawRequest : null }
}
render () {
const { message, path } = this.props
const { name, message, stack, path } = this.props
return <div className={styles.errorDebug}>
<Head>
......@@ -21,8 +21,12 @@ export default class ErrorDebug extends React.Component {
}
`}} />
</Head>
<div className={styles.heading}>Error in {path}</div>
<pre className={styles.message} dangerouslySetInnerHTML={{ __html: ansiHTML(encodeHtml(message)) }} />
{path ? <div className={styles.heading}>Error in {path}</div> : null}
{
name === 'ModuleBuildError'
? <pre className={styles.message} dangerouslySetInnerHTML={{ __html: ansiHTML(encodeHtml(message)) }} />
: <pre className={styles.message}>{stack}</pre>
}
</div>
}
}
......@@ -38,16 +42,22 @@ const styles = {
}),
errorDebug: style({
height: '100%',
height: '100vh',
padding: '16px',
boxSizing: 'border-box'
boxSizing: 'border-box',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center'
}),
message: style({
fontFamily: '"SF Mono", "Roboto Mono", "Fira Mono", menlo-regular, monospace',
fontSize: '10px',
color: '#fbe7f1',
margin: 0
margin: 0,
whiteSpace: 'pre-wrap',
wordWrap: 'break-word'
}),
heading: style({
......@@ -63,7 +73,7 @@ const styles = {
// https://github.com/babel/babel/blob/master/packages/babel-code-frame/src/index.js
ansiHTML.setColors({
reset: 'fff',
reset: ['fff', 'a6004c'],
darkgrey: 'e54590',
yellow: 'ee8cbb',
green: 'f2a2c7',
......
import React from 'react'
import style, { merge } from 'next/css'
import style from 'next/css'
export default class Error extends React.Component {
static getInitialProps ({ res, xhr }) {
const statusCode = res ? res.statusCode : xhr.status
const statusCode = res ? res.statusCode : (xhr ? xhr.status : null)
return { statusCode }
}
render () {
const { statusCode } = this.props
const title = statusCode === 404 ? 'This page could not be found' : 'Internal Server Error'
const title = statusCode === 404
? 'This page could not be found'
: (statusCode ? 'Internal Server Error' : 'An unexpected error has occurred')
return <div className={merge(styles.error, styles['error_' + statusCode])}>
return <div className={styles.error}>
<div className={styles.text}>
<h1 className={styles.h1}>{statusCode}</h1>
{statusCode ? <h1 className={styles.h1}>{statusCode}</h1> : null}
<div className={styles.desc}>
<h2 className={styles.h2}>{title}.</h2>
</div>
......
import loaderUrils from 'loader-utils'
import loaderUtils from 'loader-utils'
module.exports = function (content) {
this.cacheable()
const query = loaderUrils.parseQuery(this.query)
const query = loaderUtils.parseQuery(this.query)
const name = query.name || '[hash].[ext]'
const context = query.context || this.options.context
const regExp = query.regExp
const opts = { context, content, regExp }
const interpolatedName = loaderUrils.interpolateName(this, name, opts)
const interpolatedName = loaderUtils.interpolateName(this, name, opts)
this.emitFile(interpolatedName, content)
......
......@@ -35,7 +35,7 @@ export default class WatchPagesPlugin {
if (compiler.hasEntry(name)) return
const entries = ['webpack/hot/dev-server', f]
const entries = ['next/dist/client/webpack-hot-middleware-client', f]
compiler.addEntry(entries, name)
})
......@@ -47,7 +47,7 @@ export default class WatchPagesPlugin {
if (name === errorPageName) {
compiler.addEntry([
'webpack/hot/dev-server',
'next/dist/client/webpack-hot-middleware-client',
join(__dirname, '..', '..', '..', 'pages', '_error.js')
], name)
}
......
......@@ -9,13 +9,13 @@ import DynamicEntryPlugin from './plugins/dynamic-entry-plugin'
import DetachPlugin from './plugins/detach-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
export default async function createCompiler (dir, { hotReload = false } = {}) {
export default async function createCompiler (dir, { hotReload = false, dev = false } = {}) {
dir = resolve(dir)
const pages = await glob('pages/**/*.js', { cwd: dir })
const entry = {}
const defaultEntries = hotReload ? ['webpack/hot/dev-server'] : []
const defaultEntries = hotReload ? ['next/dist/client/webpack-hot-middleware-client'] : []
for (const p of pages) {
entry[join('bundles', p)] = defaultEntries.concat(['./' + p])
}
......@@ -35,35 +35,60 @@ export default async function createCompiler (dir, { hotReload = false } = {}) {
const nodeModulesDir = join(__dirname, '..', '..', '..', 'node_modules')
const plugins = [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new WriteFilePlugin({
exitOnErrors: false,
log: false,
// required not to cache removed files
useHashIndex: false
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'commons',
filename: 'commons.js'
})
].concat(hotReload ? [
new webpack.HotModuleReplacementPlugin(),
new DetachPlugin(),
new DynamicEntryPlugin(),
new UnlinkFilePlugin(),
new WatchRemoveEventPlugin(),
new WatchPagesPlugin(dir),
new FriendlyErrorsWebpackPlugin()
] : [
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
sourceMap: false
})
])
]
if (!dev) {
plugins.push(
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
compress: { warnings: false },
sourceMap: false
})
)
}
if (hotReload) {
plugins.push(
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new DetachPlugin(),
new DynamicEntryPlugin(),
new UnlinkFilePlugin(),
new WatchRemoveEventPlugin(),
new WatchPagesPlugin(dir),
new FriendlyErrorsWebpackPlugin()
)
}
const babelRuntimePath = require.resolve('babel-runtime/package')
.replace(/[\\\/]package\.json$/, '')
.replace(/[\\/]package\.json$/, '')
const loaders = [{
const loaders = (hotReload ? [{
test: /\.js$/,
loader: 'hot-self-accept-loader',
include: [
join(dir, 'pages'),
nextPagesDir
]
}] : [])
.concat([{
test: /\.json$/,
loader: 'json-loader'
}, {
test: /\.(js|json)$/,
loader: 'emit-file-loader',
include: [dir, nextPagesDir],
exclude (str) {
......@@ -72,16 +97,7 @@ export default async function createCompiler (dir, { hotReload = false } = {}) {
query: {
name: 'dist/[path][name].[ext]'
}
}]
.concat(hotReload ? [{
test: /\.js$/,
loader: 'hot-self-accept-loader',
include: [
join(dir, 'pages'),
nextPagesDir
]
}] : [])
.concat([{
}, {
loader: 'babel',
include: nextPagesDir,
query: {
......@@ -101,11 +117,12 @@ export default async function createCompiler (dir, { hotReload = false } = {}) {
loader: 'babel',
include: [dir, nextPagesDir],
exclude (str) {
return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0
return /node_modules/.test(str) && str.indexOf(nextPagesDir) !== 0 && str.indexOf(dir) !== 0
},
query: {
presets: ['es2015', 'react'],
plugins: [
require.resolve('babel-plugin-react-require'),
require.resolve('babel-plugin-transform-async-to-generator'),
require.resolve('babel-plugin-transform-object-rest-spread'),
require.resolve('babel-plugin-transform-class-properties'),
......@@ -138,7 +155,7 @@ export default async function createCompiler (dir, { hotReload = false } = {}) {
path: join(dir, '.next'),
filename: '[name]',
libraryTarget: 'commonjs2',
publicPath: hotReload ? 'http://localhost:3030/' : null
publicPath: hotReload ? '/_webpack/' : null
},
externals: [
'react',
......@@ -154,7 +171,10 @@ export default async function createCompiler (dir, { hotReload = false } = {}) {
root: [
nodeModulesDir,
join(dir, 'node_modules')
]
].concat(
(process.env.NODE_PATH || '')
.split(process.platform === 'win32' ? ';' : ':')
)
},
resolveLoader: {
root: [
......@@ -164,9 +184,6 @@ export default async function createCompiler (dir, { hotReload = false } = {}) {
},
plugins,
module: {
preLoaders: [
{ test: /\.json$/, loader: 'json-loader' }
],
loaders
},
customInterpolateName: function (url, name, opts) {
......
import { join, relative, sep } from 'path'
import WebpackDevServer from 'webpack-dev-server'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'
import isWindowsBash from 'is-windows-bash'
import webpack from './build/webpack'
import read from './read'
export default class HotReloader {
constructor (dir) {
constructor (dir, dev = false) {
this.dir = dir
this.server = null
this.dev = dev
this.middlewares = []
this.webpackDevMiddleware = null
this.webpackHotMiddleware = null
this.initialized = false
this.stats = null
this.compilationErrors = null
this.prevAssets = null
this.prevChunkNames = null
this.prevFailedChunkNames = null
this.prevChunkHashes = null
}
async run (req, res) {
for (const fn of this.middlewares) {
await new Promise((resolve, reject) => {
fn(req, res, (err) => {
if (err) reject(err)
resolve()
})
})
}
}
async start () {
await this.prepareServer()
await this.prepareMiddlewares()
this.stats = await this.waitUntilValid()
await this.listen()
}
async prepareServer () {
const compiler = await webpack(this.dir, { hotReload: true })
async prepareMiddlewares () {
const compiler = await webpack(this.dir, { hotReload: true, dev: this.dev })
compiler.plugin('after-emit', (compilation, callback) => {
const { assets } = compilation
......@@ -52,6 +68,8 @@ export default class HotReloader {
.reduce((a, b) => a.concat(b), [])
.map((c) => c.name))
const chunkHashes = new Map(compilation.chunks.map((c) => [c.name, c.hash]))
if (this.initialized) {
// detect chunks which have to be replaced with a new template
// e.g, pages/index.js <-> pages/_error.js
......@@ -69,6 +87,16 @@ export default class HotReloader {
const route = toRoute(relative(rootDir, n))
this.send('reload', route)
}
for (const [n, hash] of chunkHashes) {
if (!this.prevChunkHashes.has(n)) continue
if (this.prevChunkHashes.get(n) === hash) continue
const route = toRoute(relative(rootDir, n))
// notify change to recover from runtime errors
this.send('change', route)
}
}
this.initialized = true
......@@ -76,29 +104,36 @@ export default class HotReloader {
this.compilationErrors = null
this.prevChunkNames = chunkNames
this.prevFailedChunkNames = failedChunkNames
this.prevChunkHashes = chunkHashes
})
this.server = new WebpackDevServer(compiler, {
publicPath: '/',
hot: true,
const windowsSettings = isWindowsBash() ? {
lazy: false,
watchOptions: {
aggregateTimeout: 300,
poll: true
}
} : {}
this.webpackDevMiddleware = webpackDevMiddleware(compiler, {
publicPath: '/_webpack/',
noInfo: true,
quiet: true,
clientLogLevel: 'warning'
clientLogLevel: 'warning',
...windowsSettings
})
this.webpackHotMiddleware = webpackHotMiddleware(compiler, { log: false })
this.middlewares = [
this.webpackDevMiddleware,
this.webpackHotMiddleware
]
}
waitUntilValid () {
return new Promise((resolve) => {
this.server.middleware.waitUntilValid(resolve)
})
}
listen () {
return new Promise((resolve, reject) => {
this.server.listen(3030, (err) => {
if (err) return reject(err)
resolve()
})
this.webpackDevMiddleware.waitUntilValid(resolve)
})
}
......@@ -125,8 +160,8 @@ export default class HotReloader {
return this.compilationErrors
}
send (type, data) {
this.server.sockWrite(this.server.sockets, type, data)
send (action, ...args) {
this.webpackHotMiddleware.publish({ action, data: args })
}
}
......
......@@ -11,14 +11,14 @@ export default class Server {
constructor ({ dir = '.', dev = false, hotReload = false }) {
this.dir = resolve(dir)
this.dev = dev
this.hotReloader = hotReload ? new HotReloader(this.dir) : null
this.hotReloader = hotReload ? new HotReloader(this.dir, this.dev) : null
this.router = new Router()
this.http = http.createServer((req, res) => {
this.run(req, res)
.catch((err) => {
console.error(err)
res.status(500)
res.statusCode = 500
res.end('error')
})
})
......@@ -40,6 +40,11 @@ export default class Server {
}
defineRoutes () {
this.router.get('/_next/commons.js', async (req, res, params) => {
const p = join(this.dir, '.next/commons.js')
await this.serveStatic(req, res, p)
})
this.router.get('/_next/:path+', async (req, res, params) => {
const p = join(__dirname, '..', 'client', ...(params.path || []))
await this.serveStatic(req, res, p)
......@@ -60,6 +65,10 @@ export default class Server {
}
async run (req, res) {
if (this.hotReloader) {
await this.hotReloader.run(req, res)
}
const fn = this.router.match(req, res)
if (fn) {
await fn()
......@@ -69,96 +78,112 @@ export default class Server {
}
async render (req, res) {
const { dir, dev } = this
const { pathname, query } = parse(req.url, true)
const ctx = { req, res, pathname, query }
const opts = { dir, dev }
let html
const compilationErr = this.getCompilationError(req.url)
if (compilationErr) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err: compilationErr })
return
}
try {
await this.doRender(res, 200, req.url, ctx)
} catch (err) {
const compilationErr2 = this.getCompilationError('/_error')
if (compilationErr2) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err: compilationErr2 })
return
}
if (err.code !== 'ENOENT') {
console.error(err)
const url = this.dev ? '/_error-debug' : '/_error'
await this.doRender(res, 500, url, { ...ctx, err })
return
}
const err = this.getCompilationError(req.url)
if (err) {
res.statusCode = 500
html = await render('/_error-debug', { ...ctx, err }, opts)
} else {
try {
html = await render(req.url, ctx, opts)
} catch (err) {
const _err = this.getCompilationError('/_error')
if (_err) {
res.statusCode = 500
html = await render('/_error-debug', { ...ctx, err: _err }, opts)
await this.doRender(res, 404, '/_error', { ...ctx, err })
} catch (err2) {
if (this.dev) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err: err2 })
} else {
if (err.code === 'ENOENT') {
res.statusCode = 404
} else {
console.error(err)
res.statusCode = 500
}
html = await render('/_error', { ...ctx, err }, opts)
throw err2
}
}
}
}
async doRender (res, statusCode, url, ctx) {
const { dir, dev } = this
// need to set statusCode before `render`
// since it can be used on getInitialProps
res.statusCode = statusCode
const html = await render(url, ctx, { dir, dev })
sendHTML(res, html)
}
async renderJSON (req, res) {
const { dir } = this
const opts = { dir }
const compilationErr = this.getCompilationError(req.url)
if (compilationErr) {
await this.doRenderJSON(res, 500, '/_error-debug.json', compilationErr)
return
}
let json
try {
await this.doRenderJSON(res, 200, req.url)
} catch (err) {
const compilationErr2 = this.getCompilationError('/_error.json')
if (compilationErr2) {
await this.doRenderJSON(res, 500, '/_error-debug.json', compilationErr2)
return
}
const err = this.getCompilationError(req.url)
if (err) {
res.statusCode = 500
json = await renderJSON('/_error-debug.json', opts)
json = { ...json, err: errorToJSON(err) }
} else {
try {
json = await renderJSON(req.url, opts)
} catch (err) {
const _err = this.getCompilationError('/_error.json')
if (_err) {
res.statusCode = 500
json = await renderJSON('/_error-debug.json', opts)
json = { ...json, err: errorToJSON(_err) }
} else {
if (err.code === 'ENOENT') {
res.statusCode = 404
} else {
console.error(err)
res.statusCode = 500
}
json = await renderJSON('/_error.json', opts)
}
if (err.code === 'ENOENT') {
await this.doRenderJSON(res, 404, '/_error.json')
} else {
console.error(err)
await this.doRenderJSON(res, 500, '/_error.json')
}
}
}
async doRenderJSON (res, statusCode, url, err) {
const { dir } = this
const json = await renderJSON(url, { dir })
if (err) {
json.err = errorToJSON(err)
}
const data = JSON.stringify(json)
res.setHeader('Content-Type', 'application/json')
res.setHeader('Content-Length', Buffer.byteLength(data))
res.statusCode = statusCode
res.end(data)
}
async render404 (req, res) {
const { dir, dev } = this
const { pathname, query } = parse(req.url, true)
const ctx = { req, res, pathname, query }
const opts = { dir, dev }
let html
const err = this.getCompilationError('/_error')
if (err) {
res.statusCode = 500
html = await render('/_error-debug', { ...ctx, err }, opts)
} else {
res.statusCode = 404
html = await render('/_error', ctx, opts)
const compilationErr = this.getCompilationError('/_error')
if (compilationErr) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err: compilationErr })
return
}
sendHTML(res, html)
try {
await this.doRender(res, 404, '/_error', ctx)
} catch (err) {
if (this.dev) {
await this.doRender(res, 500, '/_error-debug', { ...ctx, err })
} else {
throw err
}
}
}
serveStatic (req, res, path) {
......
......@@ -8,7 +8,7 @@ import read from './read'
import getConfig from './config'
import Router from '../lib/router'
import Document from '../lib/document'
import Head from '../lib/head'
import Head, {defaultHead} from '../lib/head'
import App from '../lib/app'
export async function render (url, ctx = {}, {
......@@ -20,8 +20,15 @@ export async function render (url, ctx = {}, {
const mod = await requireModule(join(dir, '.next', 'dist', 'pages', path))
const Component = mod.default || mod
const props = await (Component.getInitialProps ? Component.getInitialProps(ctx) : {})
const component = await read(join(dir, '.next', 'bundles', 'pages', path))
const [
props,
component,
errorComponent
] = await Promise.all([
Component.getInitialProps ? Component.getInitialProps(ctx) : {},
read(join(dir, '.next', 'bundles', 'pages', path)),
read(join(dir, '.next', 'bundles', 'pages', dev ? '_error-debug' : '_error'))
])
const { html, css, ids } = renderStatic(() => {
const app = createElement(App, {
......@@ -33,7 +40,7 @@ export async function render (url, ctx = {}, {
return (staticMarkup ? renderToStaticMarkup : renderToString)(app)
})
const head = Head.rewind() || []
const head = Head.rewind() || defaultHead()
const config = await getConfig(dir)
const doc = createElement(Document, {
......@@ -42,6 +49,7 @@ export async function render (url, ctx = {}, {
css,
data: {
component,
errorComponent,
props,
ids: ids,
err: (ctx.err && dev) ? errorToJSON(ctx.err) : null
......
......@@ -4,6 +4,7 @@ import Head from 'next/head'
export default () => <div>
<Head>
<meta charSet='iso-8859-5' />
<meta content='my meta' />
</Head>
<h1>I can haz meta tags</h1>
......
......@@ -9,13 +9,14 @@ test.before(() => build(dir))
test(async t => {
const html = await render('/stateless')
t.true(html.includes('<meta charset="utf-8" class="next-head"/>'))
t.true(html.includes('<h1>My component!</h1>'))
})
test(async t => {
const html = await render('/css')
t.true(html.includes('.css-im3wl1'))
t.true(html.includes('<div class="css-im3wl1">This is red</div>'))
t.regex(html, /\.css-\w+/)
t.regex(html, /<div class="css-\w+">This is red<\/div>/)
})
test(async t => {
......@@ -25,6 +26,7 @@ test(async t => {
test(async t => {
const html = await (render('/head'))
t.true(html.includes('<meta charset="iso-8859-5" class="next-head"/>'))
t.true(html.includes('<meta content="my meta" class="next-head"/>'))
t.true(html.includes('<div><h1>I can haz meta tags</h1></div>'))
})
......
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