Commit 98ed666c authored by Arunoda Susiripala's avatar Arunoda Susiripala

merge master into next-export

parents 14fa6f58 f4d6cbfc
......@@ -4,15 +4,31 @@ import { StyleSheetServer } from 'aphrodite'
export default class MyDocument extends Document {
static async getInitialProps ({ renderPage }) {
const { html, css } = StyleSheetServer.renderStatic(() => renderPage())
return { ...html, css }
const ids = css.renderedClassNames
return { ...html, css, ids }
}
constructor (props) {
super(props)
/* Take the renderedClassNames from aphrodite (as generated
in getInitialProps) and assign them to __NEXT_DATA__ so that they
are accessible to the client for rehydration. */
const { __NEXT_DATA__, ids } = props
if (ids) {
__NEXT_DATA__.ids = this.props.ids
}
}
render () {
/* Make sure to use data-aphrodite attribute in the style tag here
so that aphrodite knows which style tag it's in control of when
the client goes to render styles. If you don't you'll get a second
<style> tag */
return (
<html>
<Head>
<title>My page</title>
<style dangerouslySetInnerHTML={{ __html: this.props.css.content }} />
<style data-aphrodite dangerouslySetInnerHTML={{ __html: this.props.css.content }} />
</Head>
<body>
<Main />
......
import React from 'react'
import { StyleSheet, css } from 'aphrodite'
if (typeof window !== 'undefined') {
/* StyleSheet.rehydrate takes an array of rendered classnames,
and ensures that the client side render doesn't generate
duplicate style definitions in the <style data-aphrodite> tag */
StyleSheet.rehydrate(window.__NEXT_DATA__.ids)
}
export default () => (
<div className={css(styles.root)}>
<h1 className={css(styles.title)}>My page</h1>
......
import { ApolloClient, createNetworkInterface } from 'react-apollo'
import fetch from 'isomorphic-fetch'
let apolloClient = null
function _initClient (headers, initialState) {
// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) {
global.fetch = fetch
}
function create () {
return new ApolloClient({
initialState,
ssrMode: !process.browser,
dataIdFromObject: result => result.id || null,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
networkInterface: createNetworkInterface({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn',
opts: {
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
opts: { // Additional fetch() options like `credentials` or `headers`
credentials: 'same-origin'
// Pass headers here if your graphql server requires them
}
})
})
}
export const initClient = (headers, initialState = {}) => {
export default function initApollo () {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (!process.browser) {
return _initClient(headers, initialState)
return create()
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = _initClient(headers, initialState)
apolloClient = create()
}
return apolloClient
}
import { createStore, combineReducers, applyMiddleware, compose } from 'redux'
import reducers from './reducers'
let reduxStore = null
// Get the Redux DevTools extension and fallback to a no-op function
let devtools = f => f
if (process.browser && window.__REDUX_DEVTOOLS_EXTENSION__) {
devtools = window.__REDUX_DEVTOOLS_EXTENSION__()
}
function create (apollo, initialState = {}) {
return createStore(
combineReducers({ // Setup reducers
...reducers,
apollo: apollo.reducer()
}),
initialState, // Hydrate the store with server-side data
compose(
applyMiddleware(apollo.middleware()), // Add additional middleware here
devtools
)
)
}
export default function initRedux (apollo, initialState) {
// Make sure to create a new store for every server-side request so that data
// isn't shared between connections (which would be bad)
if (!process.browser) {
return create(apollo, initialState)
}
// Reuse store on the client-side
if (!reduxStore) {
reduxStore = create(apollo, initialState)
}
return reduxStore
}
import { createStore } from 'redux'
import getReducer from './reducer'
import createMiddleware from './middleware'
let reduxStore = null
export const initStore = (client, initialState) => {
let store
if (!process.browser || !reduxStore) {
const middleware = createMiddleware(client.middleware())
store = createStore(getReducer(client), initialState, middleware)
if (!process.browser) {
return store
}
reduxStore = store
}
return reduxStore
}
import { applyMiddleware, compose } from 'redux'
export default function createMiddleware (clientMiddleware) {
const middleware = applyMiddleware(clientMiddleware)
if (process.browser && window.devToolsExtension) {
return compose(middleware, window.devToolsExtension())
}
return middleware
}
import { combineReducers } from 'redux'
export default function getReducer (client) {
return combineReducers({
apollo: client.reducer()
})
}
export default {
example: (state = {}, { type, payload }) => {
switch (type) {
case 'EXAMPLE_ACTION':
return {
...state
}
default:
return state
}
}
}
import 'isomorphic-fetch'
import React from 'react'
import PropTypes from 'prop-types'
import { ApolloProvider, getDataFromTree } from 'react-apollo'
import { initClient } from './initClient'
import { initStore } from './initStore'
import initApollo from './initApollo'
import initRedux from './initRedux'
export default ComposedComponent => {
return class WithData extends React.Component {
static displayName = `WithData(${ComposedComponent.displayName})`
static propTypes = {
serverState: PropTypes.object.isRequired
}
export default (Component) => (
class extends React.Component {
static async getInitialProps (ctx) {
const headers = ctx.req ? ctx.req.headers : {}
const client = initClient(headers)
const store = initStore(client, client.initialState)
let serverState = {}
const props = {
url: { query: ctx.query, pathname: ctx.pathname },
...await (Component.getInitialProps ? Component.getInitialProps(ctx) : {})
// Evaluate the composed component's getInitialProps()
let composedInitialProps = {}
if (ComposedComponent.getInitialProps) {
composedInitialProps = await ComposedComponent.getInitialProps(ctx)
}
// Run all graphql queries in the component tree
// and extract the resulting data
if (!process.browser) {
const apollo = initApollo()
const redux = initRedux(apollo)
// Provide the `url` prop data in case a graphql query uses it
const url = {query: ctx.query, pathname: ctx.pathname}
// Run all graphql queries
const app = (
<ApolloProvider client={client} store={store}>
<Component {...props} />
// No need to use the Redux Provider
// because Apollo sets up the store for us
<ApolloProvider client={apollo} store={redux}>
<ComposedComponent url={url} {...composedInitialProps} />
</ApolloProvider>
)
await getDataFromTree(app)
}
const state = store.getState()
// Extract query data from the store
const state = redux.getState()
return {
initialState: {
...state,
apollo: {
data: client.getInitialState().data
// No need to include other initial Redux state because when it
// initialises on the client-side it'll create it again anyway
serverState = {
apollo: { // Make sure to only include Apollo's data state
data: state.apollo.data
}
},
headers,
...props
}
}
return {
serverState,
...composedInitialProps
}
}
constructor (props) {
super(props)
this.client = initClient(this.props.headers, this.props.initialState)
this.store = initStore(this.client, this.props.initialState)
this.apollo = initApollo()
this.redux = initRedux(this.apollo, this.props.serverState)
}
render () {
return (
<ApolloProvider client={this.client} store={this.store}>
<Component {...this.props} />
// No need to use the Redux Provider
// because Apollo sets up the store for us
<ApolloProvider client={this.apollo} store={this.redux}>
<ComposedComponent {...this.props} />
</ApolloProvider>
)
}
}
)
}
{
"name": "with-apollo-and-redux",
"version": "1.0.0",
"version": "2.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"graphql": "^0.9.1",
"graphql": "^0.9.3",
"isomorphic-fetch": "^2.2.1",
"next": "latest",
"react": "^15.4.2",
"react-apollo": "^1.0.0-rc.2",
"prop-types": "^15.5.8",
"react": "^15.5.4",
"react-apollo": "^1.1.3",
"react-dom": "^15.5.4",
"redux": "^3.6.0"
},
"author": "",
......
import { ApolloClient, createNetworkInterface } from 'react-apollo'
import fetch from 'isomorphic-fetch'
let apolloClient = null
function _initClient (headers, initialState) {
// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) {
global.fetch = fetch
}
function create (initialState) {
return new ApolloClient({
initialState,
ssrMode: !process.browser,
dataIdFromObject: result => result.id || null,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
networkInterface: createNetworkInterface({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn',
opts: {
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
opts: { // Additional fetch() options like `credentials` or `headers`
credentials: 'same-origin'
// Pass headers here if your graphql server requires them
}
})
})
}
export const initClient = (headers, initialState = {}) => {
export default function initApollo (initialState) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (!process.browser) {
return _initClient(headers, initialState)
return create(initialState)
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = _initClient(headers, initialState)
apolloClient = create(initialState)
}
return apolloClient
}
import 'isomorphic-fetch'
import React from 'react'
import PropTypes from 'prop-types'
import { ApolloProvider, getDataFromTree } from 'react-apollo'
import { initClient } from './initClient'
import initApollo from './initApollo'
export default ComposedComponent => {
return class WithData extends React.Component {
static displayName = `WithData(${ComposedComponent.displayName})`
static propTypes = {
serverState: PropTypes.object.isRequired
}
export default (Component) => (
class extends React.Component {
static async getInitialProps (ctx) {
const headers = ctx.req ? ctx.req.headers : {}
const client = initClient(headers)
let serverState = {}
const props = {
url: { query: ctx.query, pathname: ctx.pathname },
...await (Component.getInitialProps ? Component.getInitialProps(ctx) : {})
// Evaluate the composed component's getInitialProps()
let composedInitialProps = {}
if (ComposedComponent.getInitialProps) {
composedInitialProps = await ComposedComponent.getInitialProps(ctx)
}
// Run all graphql queries in the component tree
// and extract the resulting data
if (!process.browser) {
const apollo = initApollo()
// Provide the `url` prop data in case a graphql query uses it
const url = {query: ctx.query, pathname: ctx.pathname}
// Run all graphql queries
const app = (
<ApolloProvider client={client}>
<Component {...props} />
<ApolloProvider client={apollo}>
<ComposedComponent url={url} {...composedInitialProps} />
</ApolloProvider>
)
await getDataFromTree(app)
// Extract query data from the Apollo's store
const state = apollo.getInitialState()
serverState = {
apollo: { // Make sure to only include Apollo's data state
data: state.data
}
}
}
return {
initialState: {
apollo: {
data: client.getInitialState().data
}
},
headers,
...props
serverState,
...composedInitialProps
}
}
constructor (props) {
super(props)
this.client = initClient(this.props.headers, this.props.initialState)
this.apollo = initApollo(this.props.serverState)
}
render () {
return (
<ApolloProvider client={this.client}>
<Component {...this.props} />
<ApolloProvider client={this.apollo}>
<ComposedComponent {...this.props} />
</ApolloProvider>
)
}
}
)
}
{
"name": "with-apollo",
"version": "1.0.1",
"version": "2.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"graphql": "^0.9.1",
"graphql": "^0.9.3",
"isomorphic-fetch": "^2.2.1",
"next": "latest",
"react": "^15.4.2",
"react-apollo": "^1.0.0-rc.3"
"prop-types": "^15.5.8",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"react-apollo": "^1.1.3"
},
"author": "",
"license": "ISC"
......
import Document, { Head, Main, NextScript } from 'next/document'
import cxs from 'cxs'
import cxs from 'cxs/lite'
export default class MyDocument extends Document {
static async getInitialProps ({ renderPage }) {
......@@ -13,7 +13,7 @@ export default class MyDocument extends Document {
<html>
<Head>
<title>My page</title>
<style dangerouslySetInnerHTML={{ __html: this.props.style }} />
<style id='cxs-style' dangerouslySetInnerHTML={{ __html: this.props.style }} />
</Head>
<body>
<Main />
......
import React from 'react'
import cxs from 'cxs'
import cxs from 'cxs/lite'
// Using cxs/lite on both the server and client,
// the styles will need to be rehydrated.
if (typeof window !== 'undefined') {
const styleTag = document.getElementById('cxs-style')
const serverCss = styleTag.innerHTML
cxs.rehydrate(serverCss)
}
export default () => (
<div className={cx.root}>
......
module.exports = {
clientCredentials: {
// TODO firebase client config
},
serverCredentials: {
// TODO service account json here
}
}
module.exports = {
// TODO firebase server config
}
import React, { Component } from 'react'
import firebase from 'firebase'
import 'isomorphic-fetch'
import { clientCredentials } from '../firebaseCredentials'
import clientCredentials from '../credentials/client'
export default class Index extends Component {
static async getInitialProps ({req, query}) {
......
......@@ -10,7 +10,7 @@ const app = next({ dev })
const handle = app.getRequestHandler()
const firebase = admin.initializeApp({
credential: admin.credential.cert(require('./firebaseCredentials').serverCredentials),
credential: admin.credential.cert(require('./credentials/server')),
databaseURL: '' // TODO database URL goes here
}, 'server')
......
{
"env": {
"development": {
"presets": ["next/babel"]
"presets": "next/babel"
},
"production": {
"presets": ["next/babel"]
"presets": "next/babel"
},
"test": {
// next/babel does not transpile import/export syntax.
// So, using es2015 in the beginning will fix that.
"presets": ["es2015", "next/babel"]
"presets": [
["env", { "modules": "commonjs" }],
"next/babel"
]
}
}
}
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`With Snapshot Testing App shows "Hello world!" 1`] = `
<div
data-jsx={2648947580}>
data-jsx={2648947580}
>
<p
data-jsx={2648947580}>
data-jsx={2648947580}
>
Hello World!
</p>
</div>
......
/* global it, expect, describe */
/* eslint-env jest */
import React from 'react'
import { shallow } from 'enzyme'
import React from 'react'
import renderer from 'react-test-renderer'
import App from '../pages/index.js'
describe('With Enzyme', () => {
it('App shows "Hello world!"', () => {
const app = shallow(
<App />
)
const app = shallow(<App />)
expect(app.find('p').text()).toEqual('Hello World!')
})
......
......@@ -2,20 +2,19 @@
"name": "with-jest",
"dependencies": {
"next": "latest",
"react": "^15.4.2",
"react-dom": "^15.4.2"
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"devDependencies": {
"enzyme": "^2.8.2",
"jest": "^20.0.0",
"react-addons-test-utils": "^15.5.1",
"react-test-renderer": "^15.5.4"
},
"scripts": {
"test": "jest",
"dev": "next",
"build": "next build",
"start": "next start"
},
"devDependencies": {
"enzyme": "^2.5.1",
"jest-cli": "^18.0.0",
"react-addons-test-utils": "^15.4.2",
"babel-preset-es2015": "^6.22.0",
"react-test-renderer": "^15.4.2"
}
}
module.exports = {
webpack: (config) => {
// Remove minifed react aliases for material-ui so production builds work
if (config.resolve.alias) {
delete config.resolve.alias.react
delete config.resolve.alias['react-dom']
}
return config
}
}
{
"dependencies": {
"material-ui": "^0.17.4",
"material-ui": "^0.18.0",
"next": "latest",
"react": "^15.5.4",
"react-dom": "^15.5.4",
......
......@@ -7,14 +7,11 @@ import getMuiTheme from 'material-ui/styles/getMuiTheme'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import injectTapEventPlugin from 'react-tap-event-plugin'
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
try {
if (typeof window !== 'undefined') {
injectTapEventPlugin()
}
} catch (e) {
// do nothing
// Make sure react-tap-event-plugin only gets injected once
// Needed for material-ui
if (!process.tapEventInjected) {
injectTapEventPlugin()
process.tapEventInjected = true
}
const styles = {
......@@ -24,17 +21,23 @@ const styles = {
}
}
const _muiTheme = getMuiTheme({
const muiTheme = {
palette: {
accent1Color: deepOrange500
}
})
}
class Main extends Component {
static getInitialProps ({ req }) {
const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
const isServer = !!req
return {isServer, userAgent}
// Ensures material-ui renders the correct css prefixes server-side
let userAgent
if (process.browser) {
userAgent = navigator.userAgent
} else {
userAgent = req.headers['user-agent']
}
return { userAgent }
}
constructor (props, context) {
......@@ -58,6 +61,8 @@ class Main extends Component {
}
render () {
const { userAgent } = this.props
const standardActions = (
<FlatButton
label='Ok'
......@@ -66,12 +71,8 @@ class Main extends Component {
/>
)
const { userAgent } = this.props
/* https://github.com/callemall/material-ui/issues/3336 */
const muiTheme = getMuiTheme(getMuiTheme({userAgent: userAgent}), _muiTheme)
return (
<MuiThemeProvider muiTheme={muiTheme}>
<MuiThemeProvider muiTheme={getMuiTheme({userAgent, ...muiTheme})}>
<div style={styles.container}>
<Dialog
open={this.state.open}
......
......@@ -27,7 +27,7 @@ now
## The idea behind the example
This example, just like `with-react` and `with-mobx` examples, shows how to manage a global state in your web-application.
This example, just like `with-redux` and `with-mobx` examples, shows how to manage a global state in your web-application.
In this case we are using [refnux](https://github.com/algesten/refnux) which is an alternative, simpler, purely functional store state manager.
We have two very similar pages (page1.js, page2.js). They both
......
{
"presets": [
"next/babel",
"stage-0"
],
"plugins": [
["styled-components", { "ssr": true, "displayName": true, "preprocess": false } ]
]
}
\ No newline at end of file
......@@ -30,6 +30,4 @@ This example features how you use a different styling solution than [styled-jsx]
For this purpose we are extending the `<Document />` and injecting the server side rendered styles into the `<head>`.
## Notes:
- On initial install, you may see a server-side error: `TypeError: Cannot read property 'cssRules' of undefined when using this line of code` until you actually render a `styled-component`. I have submitted a PR to fix this issue with them [here](https://github.com/styled-components/styled-components/pull/391). For the time being, make sure you render at least one `styled-component` when you use this.
# WARNING This example uses styled-components v2 which is currently in BETA
......@@ -7,10 +7,12 @@
"start": "next start"
},
"dependencies": {
"babel-plugin-styled-components": "^1.1.4",
"babel-preset-stage-0": "^6.24.1",
"next": "latest",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"styled-components": "^1.4.4"
"styled-components": "^2.0.0-17"
},
"author": "",
"license": "ISC"
......
import Document, { Head, Main, NextScript } from 'next/document'
import styleSheet from 'styled-components/lib/models/StyleSheet'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps ({ renderPage }) {
const page = renderPage()
const styles = (
<style dangerouslySetInnerHTML={{ __html: styleSheet.rules().map(rule => rule.cssText).join('\n') }} />
)
return { ...page, styles }
}
render () {
const sheet = new ServerStyleSheet()
const main = sheet.collectStyles(<Main />)
const styleTags = sheet.getStyleElement()
return (
<html>
<Head>
<title>My page</title>
{styleTags}
</Head>
<body>
<Main />
<div className='root'>
{main}
</div>
<NextScript />
</body>
</html>
......
......@@ -18,9 +18,10 @@ export default class PageLoader {
if (route[0] !== '/') {
throw new Error('Route name should start with a "/"')
}
route = route.replace(/index$/, '')
if (route === '/') return route
return route.replace(/index$/, '').replace(/\/$/, '')
return route.replace(/\/$/, '')
}
loadPage (route) {
......
{
"name": "next",
"version": "2.3.0",
"version": "2.3.1",
"description": "Minimalistic framework for server-rendered React applications",
"main": "./dist/server/next.js",
"license": "MIT",
......@@ -53,7 +53,7 @@
"babel-plugin-transform-es2015-modules-commonjs": "6.24.1",
"babel-plugin-transform-object-rest-spread": "6.22.0",
"babel-plugin-transform-react-jsx-source": "6.22.0",
"babel-plugin-transform-react-remove-prop-types": "0.4.4",
"babel-plugin-transform-react-remove-prop-types": "0.4.5",
"babel-plugin-transform-runtime": "6.22.0",
"babel-preset-env": "1.3.3",
"babel-preset-react": "6.24.1",
......@@ -79,7 +79,7 @@
"mz": "2.6.0",
"path-match": "1.2.4",
"pkg-up": "2.0.0",
"prop-types": "15.5.7",
"prop-types": "15.5.9",
"react-hot-loader": "3.0.0-beta.6",
"send": "0.15.2",
"source-map-support": "0.4.15",
......@@ -89,7 +89,7 @@
"unfetch": "2.1.2",
"url": "0.11.0",
"uuid": "3.0.1",
"webpack": "2.4.0",
"webpack": "2.5.1",
"webpack-dev-middleware": "1.10.2",
"webpack-hot-middleware": "2.18.0",
"write-file-webpack-plugin": "4.0.2"
......@@ -116,7 +116,7 @@
"lint-staged": "^3.4.0",
"node-fetch": "1.6.3",
"node-notifier": "5.1.2",
"nyc": "10.3.0",
"nyc": "10.3.2",
"react": "15.5.3",
"react-dom": "15.5.3",
"recursive-copy": "^2.0.6",
......
......@@ -6,12 +6,15 @@
Next.js is a minimalistic framework for server-rendered React applications.
**Visit https://learnnextjs.com to get started with Next.js.**
---
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
<!-- https://github.com/thlorenz/doctoc -->
- [How to use](#how-to-use)
- [Getting Started](#getting-started)
- [Setup](#setup)
- [Automatic code splitting](#automatic-code-splitting)
- [CSS](#css)
......@@ -36,6 +39,7 @@ Next.js is a minimalistic framework for server-rendered React applications.
- [Customizing babel config](#customizing-babel-config)
- [CDN support with Asset Prefix](#cdn-support-with-asset-prefix)
- [Production deployment](#production-deployment)
- [Recipes](#recipes)
- [FAQ](#faq)
- [Contributing](#contributing)
- [Authors](#authors)
......@@ -44,10 +48,6 @@ Next.js is a minimalistic framework for server-rendered React applications.
## How to use
### Getting Started
A step by step interactive guide of next features is available at [learnnextjs.com](https://learnnextjs.com/)
### Setup
Install it:
......@@ -129,17 +129,24 @@ export default () => (
}
}
`}</style>
<style global jsx>{`
body {
background: black;
}
`}</style>
</div>
)
```
Please see the [styled-jsx documentation](https://github.com/zeit/styled-jsx) for more examples.
#### CSS-in-JS
<p><details>
<summary>
<b>Examples</b>
</summary>
<ul><li><a href="./examples/with-styled-components">Styled components</a></li><li><a href="./examples/with-styletron">Styletron</a></li><li><a href="./examples/with-glamor">Glamor</a></li><li><a href="./examples/with-cxs">Cxs</a></li><li><a href="./examples/with-aphrodite">Aphrodite</a></li><li><a href="./examples/with-fela">Fela</a></li></ul>
<ul><li><a href="./examples/with-styled-components">Styled components</a></li><li><a href="./examples/with-styletron">Styletron</a></li><li><a href="./examples/with-glamor">Glamor</a></li><li><a href="./examples/with-glamorous">Glamorous</a></li><li><a href="./examples/with-cxs">Cxs</a></li><li><a href="./examples/with-aphrodite">Aphrodite</a></li><li><a href="./examples/with-fela">Fela</a></li></ul>
</details></p>
It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles:
......@@ -614,6 +621,8 @@ The `ctx` object is equivalent to the one received in all [`getInitialProps`](#f
- `renderPage` (`Function`) a callback that executes the actual React rendering logic (synchronously). It's useful to decorate this function in order to support server-rendering wrappers like Aphrodite's [`renderStatic`](https://github.com/Khan/aphrodite#server-side-rendering)
__Note: React-components outside of `<Main />` will not be initialised by the browser. If you need shared components in all your pages (like a menu or a toolbar), do _not_ add application logic here, but take a look at [this example](https://github.com/zeit/next.js/tree/master/examples/layout-component).__
### Custom error handling
404 or 500 errors are handled both client and server side by a default component `error.js`. If you wish to override it, define a `_error.js`:
......@@ -752,6 +761,10 @@ Next.js can be deployed to other hosting solutions too. Please have a look at th
Note: we recommend putting `.next`, or your custom dist folder (Please have a look at ['Custom Config'](You can set a custom folder in config https://github.com/zeit/next.js#custom-configuration.)), in `.npmignore` or `.gitignore`. Otherwise, use `files` or `now.files` to opt-into a whitelist of files you want to deploy (and obviously exclude `.next` or your custom dist folder)
## Recipes
- [Setting up 301 redirects](https://www.raygesualdo.com/posts/301-redirects-with-nextjs/)
## FAQ
<details>
......
......@@ -9,7 +9,7 @@ const envPlugins = {
]
}
const plugins = envPlugins[process.env.NODE_ENV] || []
const plugins = envPlugins[process.env.NODE_ENV] || envPlugins['development']
module.exports = {
presets: [
......
......@@ -12,7 +12,17 @@ export default class PagesPlugin {
pages.forEach((chunk) => {
const page = compilation.assets[chunk.name]
const pageName = matchRouteName.exec(chunk.name)[1]
const routeName = `/${pageName.replace(/[/\\]?index$/, '')}`
let routeName = `/${pageName.replace(/[/\\]?index$/, '')}`
// We need to convert \ into / when we are in windows
// to get the proper route name
// Here we need to do windows check because it's possible
// to have "\" in the filename in unix.
// Anyway if someone did that, he'll be having issues here.
// But that's something we cannot avoid.
if (/^win/.test(process.platform)) {
routeName = routeName.replace(/\\/g, '/')
}
const content = page.source()
const newContent = `
......
......@@ -295,7 +295,7 @@ export default async function createCompiler (dir, { dev = false, quiet = false,
module: {
rules
},
devtool: dev ? 'inline-source-map' : false,
devtool: dev ? 'cheap-module-inline-source-map' : false,
performance: { hints: false }
}
......
import CDM from '../lib/cdm'
export default CDM
......@@ -323,7 +323,7 @@ export default (context, render) => {
})
describe('with different types of urls', () => {
it('on normal page', async () => {
it('should work with normal page', async () => {
const browser = await webdriver(context.appPort, '/with-cdm')
const text = await browser.elementByCss('p').text()
......@@ -331,7 +331,7 @@ export default (context, render) => {
browser.close()
})
it('on dir/index page ', async () => {
it('should work with dir/index page ', async () => {
const browser = await webdriver(context.appPort, '/nested-cdm/index')
const text = await browser.elementByCss('p').text()
......@@ -339,13 +339,29 @@ export default (context, render) => {
browser.close()
})
it('on dir/ page ', async () => {
it('should work with dir/ page ', async () => {
const browser = await webdriver(context.appPort, '/nested-cdm/')
const text = await browser.elementByCss('p').text()
expect(text).toBe('ComponentDidMount executed on client.')
browser.close()
})
it('should work with /index page', async () => {
const browser = await webdriver(context.appPort, '/index')
const text = await browser.elementByCss('p').text()
expect(text).toBe('ComponentDidMount executed on client.')
browser.close()
})
it('should work with / page', async () => {
const browser = await webdriver(context.appPort, '/')
const text = await browser.elementByCss('p').text()
expect(text).toBe('ComponentDidMount executed on client.')
browser.close()
})
})
describe('with asPath', () => {
......
This diff is collapsed.
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