Commit 850a931e authored by Guillermo Rauch's avatar Guillermo Rauch

Merge branch 'master' into v3-beta

parents 533a31b0 dd4b4dd9
......@@ -30,7 +30,16 @@ export default () => {
return
}
const { err } = Router.components[route] || {}
const { err, Component } = Router.components[route] || {}
if (!Component) {
// This only happens when we create a new page without a default export.
// If you removed a default export from a exising viewing page, this has no effect.
console.log(`Hard reloading due to no default component in page: ${route}`)
window.location.reload()
return
}
if (err) {
// reload to recover from runtime errors
Router.reload(route)
......
......@@ -19,7 +19,7 @@ export default ({ children, title = 'This is the default title' }) => (
{ children }
<footer>
I`m here to stay
{'I`m here to stay'}
</footer>
</div>
)
......@@ -3,8 +3,8 @@
"next/babel"
],
"plugins": [
["wrap-in-js", {
"extensions": ["css$"]
["import", {
"libraryName": "antd"
}]
]
}
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-ant-design)
# Ant Design example
## How to use
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-ant-design
cd with-ant-design
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
This example shows how to use Next.js along with [Ant Design of React](http://ant.design). This is intended to show the integration of this UI toolkit with the Framework.
{
"name": "with-ant-design",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"antd": "^2.10.2",
"babel-plugin-import": "^1.1.1",
"next": "latest",
"react": "^15.5.4",
"react-dom": "^15.5.4"
},
"author": "",
"license": "ISC"
}
import Head from 'next/head'
import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button, LocaleProvider } from 'antd'
import enUS from 'antd/lib/locale-provider/en_US'
const FormItem = Form.Item
const Option = Select.Option
export default () => (
<LocaleProvider locale={enUS}>
<div style={{ marginTop: 100 }}>
<Head>
<link rel='stylesheet' href='//cdnjs.cloudflare.com/ajax/libs/antd/2.9.3/antd.min.css' />
</Head>
<Form layout='horizontal'>
<FormItem
label='Input Number'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<InputNumber size='large' min={1} max={10} style={{ width: 100 }} defaultValue={3} name='inputNumber' />
<a href='#'>Link</a>
</FormItem>
<FormItem
label='Switch'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Switch defaultChecked name='switch' />
</FormItem>
<FormItem
label='Slider'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Slider defaultValue={70} />
</FormItem>
<FormItem
label='Select'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<Select size='large' defaultValue='lucy' style={{ width: 192 }} name='select'>
<Option value='jack'>jack</Option>
<Option value='lucy'>lucy</Option>
<Option value='disabled' disabled>disabled</Option>
<Option value='yiminghe'>yiminghe</Option>
</Select>
</FormItem>
<FormItem
label='DatePicker'
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
<DatePicker name='startDate' />
</FormItem>
<FormItem
style={{ marginTop: 48 }}
wrapperCol={{ span: 8, offset: 8 }}
>
<Button size='large' type='primary' htmlType='submit'>
OK
</Button>
<Button size='large' style={{ marginLeft: 8 }}>
Cancel
</Button>
</FormItem>
</Form>
</div>
</LocaleProvider>
)
{
"presets": [
"next/babel"
],
"plugins": [
[
"import",
{
"libraryName": "antd-mobile"
}
]
]
}
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/with-material-ui)
# Ant Design Mobile example
## How to use
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/with-antd-mobile
cd with-antd-mobile
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
This example features how you use [antd-mobile](https://github.com/ant-design/ant-design-mobile) (Ant Design Mobile FrontEnd Framwork) with Next.js.
import React, { Component } from 'react'
import { LocaleProvider } from 'antd-mobile'
import enUS from 'antd-mobile/lib/locale-provider/en_US'
export default class Layout extends Component {
render () {
const { language, children } = this.props
const locale = language.substr(0, 2) === 'en' ? enUS : undefined
return (
<LocaleProvider locale={locale}>
{children}
</LocaleProvider>
)
}
}
import React, { Component } from 'react'
import Router from 'next/router'
import { TabBar, Icon } from 'antd-mobile'
export default class MenuBar extends Component {
render () {
const {
pathname,
children
} = this.props
return (
<TabBar>
{tabBarData.map(({ title, icon, selectedIcon, link, dot, component: Component }) => (
<TabBar.Item
key={link}
title={title}
icon={<Icon type={icon} />}
selectedIcon={<Icon type={selectedIcon} />}
selected={pathname === link}
onPress={() => Router.push(link)}
>
{children}
</TabBar.Item>
))}
</TabBar>
)
}
}
const tabBarData = [
{
title: 'Home',
icon: 'koubei-o',
selectedIcon: 'koubei',
link: '/home'
},
{
title: 'Trick',
icon: 'check-circle-o',
selectedIcon: 'check-circle',
link: '/trick'
}
]
const path = require('path')
const fs = require('fs')
const requireHacker = require('require-hacker')
function setupRequireHacker () {
requireHacker.resolver((filename, module) => {
if (filename.endsWith('/style/css')) {
return requireHacker.resolve(`${filename}.web.js`, module)
}
})
requireHacker.hook('js', filename => {
if (
filename.endsWith('.web.js') ||
!filename.includes('/node_modules/') ||
['antd-mobile', 'rc-swipeout', 'rmc-picker'].every(p => !filename.includes(p))
) return
const webjs = filename.replace(/\.js$/, '.web.js')
if (!fs.existsSync(webjs)) return
return fs.readFileSync(webjs, { encoding: 'utf8' })
})
requireHacker.hook('css', () => '')
requireHacker.hook('svg', filename => {
return requireHacker.to_javascript_module_source(fs.readFileSync(filename, { encoding: 'utf8' }))
})
}
setupRequireHacker()
function moduleDir (m) {
return path.dirname(require.resolve(`${m}/package.json`))
}
module.exports = {
webpack: (config, { dev }) => {
config.resolve.extensions = ['.web.js', '.js', '.json']
config.module.rules.push(
{
test: /\.(svg)$/i,
loader: 'svg-sprite-loader',
include: [
moduleDir('antd-mobile')
]
}
)
return config
}
}
{
"dependencies": {
"antd-mobile": "^1.1.2",
"babel-plugin-import": "^1.1.1",
"next": "latest",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"require-hacker": "^3.0.0",
"svg-sprite-loader": "~0.3.0"
},
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
}
}
import Document, { Head, Main, NextScript } from 'next/document'
export default class extends Document {
render () {
return (
<html>
<Head>
<script src='/static/hd.min.js' />
<link rel='stylesheet' type='text/css' href='//unpkg.com/antd-mobile/dist/antd-mobile.min.css' />
</Head>
<body style={{margin: 0}}>
<Main />
<NextScript />
</body>
</html>
)
}
}
import React, {Component} from 'react'
import {
WhiteSpace, WingBlank,
NavBar, Icon, Pagination, Steps
} from 'antd-mobile'
import Layout from '../components/Layout'
import MenuBar from '../components/MenuBar'
export default class Home extends Component {
static getInitialProps ({ req }) {
const language = req ? req.headers['accept-language'] : navigator.language
return {
language
}
}
render () {
const {
language,
url: { pathname }
} = this.props
return (
<Layout language={language}>
<MenuBar
pathname={pathname}
>
<NavBar
leftContent='back'
mode='light'
onLeftClick={() => console.log('onLeftClick')}
rightContent={[
<Icon key='0' type='search' style={{ marginRight: '0.32rem' }} />,
<Icon key='1' type='ellipsis' />
]}
>
NavBar
</NavBar>
<WhiteSpace />
<Pagination total={5} current={0} />
<WhiteSpace />
<WingBlank>
<Steps current={1}>
<Steps.Step title='Finished' description='Most components has supported' />
<Steps.Step title='In Progress' description='Switch Modal and Menu' />
<Steps.Step title='Waiting' description='1.2.0' />
</Steps>
</WingBlank>
</MenuBar>
</Layout>
)
}
}
import { Component } from 'react'
export default class Index extends Component {
static async getInitialProps ({ res }) {
res.setHeader('Location', '/home')
res.statusCode = 302
res.end()
}
}
import React, { Component } from 'react'
import {
WhiteSpace,
List, Switch, Modal, Button, Menu
} from 'antd-mobile'
import Layout from '../components/Layout'
import MenuBar from '../components/MenuBar'
export default class Trick extends Component {
static getInitialProps ({ req }) {
const language = req ? req.headers['accept-language'] : navigator.language
const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
const android = /android/i.test(userAgent)
const platform = android ? 'android' : 'ios'
return {
language,
platform
}
}
constructor (props) {
super(props)
this.menuData = [
{
label: 'Menu 1',
value: '1',
children: [
{
label: 'Submenu 1-1',
value: '11'
},
{
label: 'Submenu 1-2',
value: '12'
}
]
},
{
label: 'Menu 2',
value: '2',
children: [
{
label: 'Submenu 2-1',
value: '21'
},
{
label: 'Submenu 2-2',
value: '22'
},
{
label: 'Submenu 2-3',
value: '23'
}
]
}
]
this.state = {
switchChecked: true,
modalOpened: false
}
}
render () {
const {
language,
platform,
url: { pathname }
} = this.props
const {
switchChecked,
modalOpened
} = this.state
return (
<Layout language={language}>
<MenuBar
pathname={pathname}
>
<WhiteSpace />
<List renderHeader={() => 'Switch and Modal platform prop is required in SSR mode'}>
<List.Item
extra={
<Switch
platform={platform}
checked={switchChecked}
onChange={val => this.setState({ switchChecked: val })}
/>
}
>
Switch {platform}
</List.Item>
<Button onClick={() => this.setState({ modalOpened: true })}>
Open {platform} modal
</Button>
</List>
<Modal
title='Modal'
platform={platform}
visible={modalOpened}
transparent
closable
footer={[{ text: 'OK', onPress: () => this.setState({ modalOpened: false }) }]}
onClose={() => this.setState({ modalOpened: false })}
>
I am a modal.<br />
Must set platform prop
</Modal>
<List renderHeader={() => 'Menu height prop is required in SSR mode'}>
<Menu
height={500}
data={this.menuData}
/>
</List>
</MenuBar>
</Layout>
)
}
}
!function(e){function t(a){if(i[a])return i[a].exports;var n=i[a]={exports:{},id:a,loaded:!1};return e[a].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var i={};return t.m=e,t.c=i,t.p="",t(0)}([function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=window;t["default"]=i.flex=function(e,t){var a=e||100,n=t||1,r=i.document,o=navigator.userAgent,d=o.match(/Android[\S\s]+AppleWebkit\/(\d{3})/i),l=o.match(/U3\/((\d+|\.){5,})/i),c=l&&parseInt(l[1].split(".").join(""),10)>=80,p=navigator.appVersion.match(/(iphone|ipad|ipod)/gi),s=i.devicePixelRatio||1;p||d&&d[1]>534||c||(s=1);var u=1/s,m=r.querySelector('meta[name="viewport"]');m||(m=r.createElement("meta"),m.setAttribute("name","viewport"),r.head.appendChild(m)),m.setAttribute("content","width=device-width,user-scalable=no,initial-scale="+u+",maximum-scale="+u+",minimum-scale="+u),r.documentElement.style.fontSize=a/2*s*n+"px"},e.exports=t["default"]}]);
flex(100, 1);
......@@ -4,6 +4,7 @@
[
"css-modules-transform", {
"extensions": [".css", ".sass"],
"append": [ "postcss-cssnext" ],
"extractCss": "./static/css/bundle.css",
"preprocessCss": "./pre-processor.js"
}
......
@mixin opacity($opacity)
opacity: $opacity
filter: alpha(opacity=($opacity * 100))
\ No newline at end of file
......@@ -16,6 +16,8 @@
},
"devDependencies": {
"babel-plugin-css-modules-transform": "^1.2.1",
"node-sass": "^4.5.0"
"node-sass": "^4.5.0",
"postcss": "^5.2.16",
"postcss-cssnext": "^2.10.0"
}
}
@import "../global"
.example
@include opacity(0.5)
font-size: 36px
width: 300px
margin: 100px auto
\ No newline at end of file
display: flex
......@@ -10,7 +10,7 @@ if (typeof window !== 'undefined') {
}
export default () => {
css.global('html, body', { padding: '3rem 1rem', margin: 0, background: 'papayawhip', 'min-height': '100%', 'font-family': 'Helvetica, Arial, sans-serif', 'font-size': '24px' })
css.global('html, body', { padding: '3rem 1rem', margin: 0, background: 'papayawhip', minHeight: '100%', fontFamily: 'Helvetica, Arial, sans-serif', fontSize: '24px' })
const basicStyles = {
backgroundColor: 'white',
......
import { translate } from 'react-i18next'
export default translate(['common'])((props) => (<h1>{props.t('hello')}</h1>))
export default translate(['common'])((props) => (<h1>{props.t('hello')}, {props.t('morning')}</h1>))
......@@ -4,9 +4,12 @@ import startI18n from '../tools/startI18n'
import { getTranslation } from '../tools/translationHelpers'
import Title from '../components/Title'
// get language from query parameter or url path
const lang = 'id'
export default class Homepage extends Component {
static async getInitialProps () {
const translations = await getTranslation('pt', 'common', 'http://localhost:3000/static/locales/')
const translations = await getTranslation(lang, 'common', 'http://localhost:3000/static/locales/')
return { translations }
}
......@@ -14,7 +17,7 @@ export default class Homepage extends Component {
constructor (props) {
super(props)
this.i18n = startI18n(props.translations)
this.i18n = startI18n(props.translations, lang)
}
render (props) {
......
{
"hello": "halo"
}
\ No newline at end of file
{
"hello": "e ae tche"
"hello": "e ae tche",
"morning": "manha"
}
\ No newline at end of file
import i18n from 'i18next'
const startI18n = file => i18n.init({
const startI18n = (file, lang) => i18n.init({
lng: lang, // active language http://i18next.com/translate/
fallbackLng: 'pt',
resources: file,
ns: ['common'],
......
......@@ -29,26 +29,6 @@ now
Scoped CSS is neat and keeps your JS clean. PostCSS is amazing for extended features, such as nesting. CSS Modules keep your class names “local”.
# Known bugs
# Known issues
There's a bug, possibly within `next.js`, making composition between files unuseable. Consider the following:
*`styles.css`*
```css
.paragraph {
composes: font-sans from '../global.css';
}
```
*`global.css`*
```css
.font-sans {
font-family: georgia; /* ;) */
}
```
The following error is thrown:
```
Module build failed: Error: Cannot find module '-!./../node_modules/css-loader/index.js??ref--6-4!./../node_modules/postcss-loader/index.js!../global.css'
```
Composed CSS files are not watched by next.js, and thus, if you change one, nothing will happen. You'll need to edit a JS file or the CSS file you're composing for it to hot reload.
const trash = require('trash')
module.exports = {
webpack: (config) => {
config.module.rules.push(
......@@ -10,27 +12,21 @@ module.exports = {
name: 'dist/[path][name].[ext]'
}
},
'raw-loader',
'val-loader',
{
loader: 'skeleton-loader',
options: {
procedure: (content) => (
`${content} \n` + ['module.exports = {',
'stylesheet: module.exports.toString(),',
'classNames: exports.locals',
procedure: function (content) {
const fileName = `${this._module.userRequest}.json`
const classNames = JSON.stringify(require(fileName))
trash(fileName)
return ['module.exports = {',
`classNames: ${classNames},`,
`stylesheet: \`${content}\``,
'}'
].join('')
)
}
},
{
loader: 'css-loader',
options: {
modules: true,
minimize: true,
importLoaders: 1,
localIdentName: '[local]-[hash:base64:5]'
}
}
},
'postcss-loader'
......
......@@ -10,18 +10,17 @@
"author": "Thomas Lindstrøm <t@hom.as>",
"license": "ISC",
"dependencies": {
"babel-plugin-wrap-in-js": "^1.1.1",
"css-loader": "^0.26.1",
"cssnano": "^3.10.0",
"next": "latest",
"postcss-cssnext": "^2.9.0",
"postcss-loader": "^1.3.0",
"raw-loader": "^0.5.1",
"postcss-modules": "^0.6.4",
"react": "^15.4.2",
"react-dom": "^15.4.2",
"skeleton-loader": "0.0.7",
"val-loader": "^0.5.0"
"skeleton-loader": "^1.1.2",
"trash": "^4.0.1"
},
"devDependencies": {
"now": "^3.1.0"
"now": "^4.10.3"
}
}
.paragraph {
composes: font-color from './global.css';
font-size: 20px;
color: red;
}
module.exports = {
plugins: [
require('postcss-cssnext')()
require('postcss-cssnext')(),
require('postcss-modules')({
generateScopedName: '[local]-[hash:base64:5]'
}),
require('cssnano')()
]
}
......@@ -4,7 +4,6 @@ const isWindows = /^win/.test(process.platform)
export async function compile(fly) {
await fly.parallel(['bin', 'server', 'lib', 'client'])
await fly.start('unrestrict')
}
export async function bin(fly, opts) {
......@@ -27,14 +26,6 @@ export async function client(fly, opts) {
notify('Compiled client files')
}
export async function unrestrict(fly) {
await fly.source('dist/lib/eval-script.js').babel({
babelrc: false,
plugins: ['babel-plugin-transform-remove-strict-mode']
}).target('dist/lib')
notify('Completed removing strict mode for eval script')
}
export async function copy(fly) {
await fly.source('pages/**/*.js').target('dist/pages')
}
......
{
"name": "next",
"version": "3.0.0-beta6",
"version": "3.0.0-beta7",
"description": "Minimalistic framework for server-rendered React applications",
"main": "./dist/server/next.js",
"license": "MIT",
......@@ -82,12 +82,11 @@
"path-match": "1.2.4",
"pkg-up": "2.0.0",
"prop-types": "15.5.10",
"react-hot-loader": "3.0.0-beta.6",
"recursive-copy": "^2.0.6",
"send": "0.15.3",
"react-hot-loader": "3.0.0-beta.7",
"source-map-support": "0.4.15",
"strip-ansi": "3.0.1",
"styled-jsx": "0.5.7",
"styled-jsx": "1.0.2",
"touch": "1.0.0",
"unfetch": "2.1.2",
"url": "0.11.0",
......
......@@ -583,6 +583,7 @@ Supported options:
- `dev` (`bool`) whether to launch Next.js in dev mode - default `false`
- `dir` (`string`) where the Next project is located - default `'.'`
- `quiet` (`bool`) Hide error messages containing server information - default `false`
- `conf` (`object`) the same object you would use in `next.config.js` - default `{}`
Then, change your `start` script to `NODE_ENV=production node server.js`.
......@@ -863,7 +864,7 @@ Then run `now` and enjoy!
Next.js can be deployed to other hosting solutions too. Please have a look at the ['Deployment'](https://github.com/zeit/next.js/wiki/Deployment) section of the wiki.
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)
Note: we recommend putting `.next`, or your custom dist folder (you can set a custom folder in ['Custom 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)
## Static HTML export
......
......@@ -314,7 +314,7 @@ export default async function createCompiler (dir, { dev = false, quiet = false,
}
if (config.webpack) {
console.log('> Using "webpack" config function defined in next.config.js.')
console.log(`> Using "webpack" config function defined in ${config.configOrigin}.`)
webpackConfig = await config.webpack(webpackConfig, { dev })
}
return webpack(webpackConfig)
......
......@@ -8,17 +8,23 @@ const defaultConfig = {
webpackDevMiddleware: null,
poweredByHeader: true,
distDir: '.next',
assetPrefix: ''
assetPrefix: '',
configOrigin: 'default',
useFileSystemPublicRoutes: true
}
export default function getConfig (dir) {
export default function getConfig (dir, customConfig) {
if (!cache.has(dir)) {
cache.set(dir, loadConfig(dir))
cache.set(dir, loadConfig(dir, customConfig))
}
return cache.get(dir)
}
function loadConfig (dir) {
function loadConfig (dir, customConfig) {
if (customConfig && typeof customConfig === 'object') {
customConfig.configOrigin = 'server'
return withDefaults(customConfig)
}
const path = join(dir, 'next.config.js')
let userConfig = {}
......@@ -27,7 +33,12 @@ function loadConfig (dir) {
if (userHasConfig) {
const userConfigModule = require(path)
userConfig = userConfigModule.default || userConfigModule
userConfig.configOrigin = 'next.config.js'
}
return Object.assign({}, defaultConfig, userConfig)
return withDefaults(userConfig)
}
function withDefaults (config) {
return Object.assign({}, defaultConfig, config)
}
......@@ -36,8 +36,8 @@ export class Head extends Component {
getChunkPreloadLink (filename) {
const { __NEXT_DATA__ } = this.context._documentProps
let { buildStats, assetPrefix } = __NEXT_DATA__
const hash = buildStats ? buildStats[filename].hash : '-'
let { buildStats, assetPrefix, buildId } = __NEXT_DATA__
const hash = buildStats ? buildStats[filename].hash : buildId
return (
<link
......@@ -118,8 +118,8 @@ export class NextScript extends Component {
getChunkScript (filename, additionalProps = {}) {
const { __NEXT_DATA__ } = this.context._documentProps
let { buildStats, assetPrefix } = __NEXT_DATA__
const hash = buildStats ? buildStats[filename].hash : '-'
let { buildStats, assetPrefix, buildId } = __NEXT_DATA__
const hash = buildStats ? buildStats[filename].hash : buildId
return (
<script
......
......@@ -8,7 +8,7 @@ import clean from './build/clean'
import getConfig from './config'
export default class HotReloader {
constructor (dir, { quiet } = {}) {
constructor (dir, { quiet, conf } = {}) {
this.dir = dir
this.quiet = quiet
this.middlewares = []
......@@ -22,7 +22,7 @@ export default class HotReloader {
this.prevFailedChunkNames = null
this.prevChunkHashes = null
this.config = getConfig(dir)
this.config = getConfig(dir, conf)
}
async run (req, res) {
......@@ -148,7 +148,7 @@ export default class HotReloader {
}
if (this.config.webpackDevMiddleware) {
console.log('> Using "webpackDevMiddleware" config function defined in next.config.js.')
console.log(`> Using "webpackDevMiddleware" config function defined in ${this.config.configOrigin}.`)
webpackDevMiddlewareConfig = this.config.webpackDevMiddleware(webpackDevMiddlewareConfig)
}
......
import { resolve, join } from 'path'
import { resolve, join, sep } from 'path'
import { parse as parseUrl } from 'url'
import { parse as parseQs } from 'querystring'
import fs from 'fs'
......@@ -24,14 +24,14 @@ const internalPrefixes = [
]
export default class Server {
constructor ({ dir = '.', dev = false, staticMarkup = false, quiet = false } = {}) {
constructor ({ dir = '.', dev = false, staticMarkup = false, quiet = false, conf = null } = {}) {
this.dir = resolve(dir)
this.dev = dev
this.quiet = quiet
this.router = new Router()
this.hotReloader = dev ? new HotReloader(this.dir, { quiet }) : null
this.hotReloader = dev ? new HotReloader(this.dir, { quiet, conf }) : null
this.http = null
this.config = getConfig(this.dir)
this.config = getConfig(this.dir, conf)
this.dist = this.config.distDir
this.buildStats = !dev ? require(join(this.dir, this.dist, 'build-stats.json')) : null
this.buildId = !dev ? this.readBuildId() : '-'
......@@ -113,24 +113,32 @@ export default class Server {
},
'/_next/:hash/manifest.js': async (req, res, params) => {
if (!this.dev) return this.send404(res)
this.handleBuildHash('manifest.js', params.hash, res)
const p = join(this.dir, `${this.dist}/manifest.js`)
await this.serveStatic(req, res, p)
},
'/_next/:hash/main.js': async (req, res, params) => {
if (!this.dev) return this.send404(res)
this.handleBuildHash('main.js', params.hash, res)
const p = join(this.dir, `${this.dist}/main.js`)
await this.serveStatic(req, res, p)
},
'/_next/:hash/commons.js': async (req, res, params) => {
if (!this.dev) return this.send404(res)
this.handleBuildHash('commons.js', params.hash, res)
const p = join(this.dir, `${this.dist}/commons.js`)
await this.serveStatic(req, res, p)
},
'/_next/:hash/app.js': async (req, res, params) => {
if (this.dev) return this.send404(res)
this.handleBuildHash('app.js', params.hash, res)
const p = join(this.dir, `${this.dist}/app.js`)
await this.serveStatic(req, res, p)
......@@ -184,9 +192,11 @@ export default class Server {
'/static/:path+': async (req, res, params) => {
const p = join(this.dir, 'static', ...(params.path || []))
await this.serveStatic(req, res, p)
},
}
}
'/:path*': async (req, res, params, parsedUrl) => {
if (this.config.useFileSystemPublicRoutes) {
routes['/:path*'] = async (req, res, params, parsedUrl) => {
const { pathname, query } = parsedUrl
await this.render(req, res, pathname, query)
}
......@@ -238,7 +248,7 @@ export default class Server {
res.setHeader('X-Powered-By', `Next.js ${pkg.version}`)
}
const html = await this.renderToHTML(req, res, pathname, query)
return sendHTML(req, res, html, req.method)
return sendHTML(req, res, html, req.method, this.renderOpts)
}
async renderToHTML (req, res, pathname, query) {
......@@ -266,7 +276,7 @@ export default class Server {
async renderError (err, req, res, pathname, query) {
const html = await this.renderErrorToHTML(err, req, res, pathname, query)
return sendHTML(req, res, html, req.method)
return sendHTML(req, res, html, req.method, this.renderOpts)
}
async renderErrorToHTML (err, req, res, pathname, query) {
......@@ -298,6 +308,10 @@ export default class Server {
}
async serveStatic (req, res, path) {
if (!this.isServeableUrl(path)) {
return this.render404(req, res)
}
try {
return await serveStatic(req, res, path)
} catch (err) {
......@@ -309,6 +323,19 @@ export default class Server {
}
}
isServeableUrl (path) {
const resolved = resolve(path)
if (
resolved.indexOf(join(this.dir, this.dist) + sep) !== 0 &&
resolved.indexOf(join(this.dir, 'static') + sep) !== 0
) {
// Seems like the user is trying to traverse the filesystem.
return false
}
return true
}
isInternalUrl (req) {
for (const prefix of internalPrefixes) {
if (prefix.test(req.url)) {
......@@ -348,10 +375,16 @@ export default class Server {
handleBuildHash (filename, hash, res) {
if (this.dev) return
if (hash !== this.buildStats[filename].hash) {
throw new Error(`Invalid Build File Hash(${hash}) for chunk: ${filename}`)
}
res.setHeader('Cache-Control', 'max-age=365000000, immutable')
}
send404 (res) {
res.statusCode = 404
res.end('404 - Not Found')
}
}
......@@ -16,7 +16,7 @@ import { flushChunks } from '../lib/dynamic'
export async function render (req, res, pathname, query, opts) {
const html = await renderToHTML(req, res, pathname, opts)
sendHTML(req, res, html, req.method)
sendHTML(req, res, html, req.method, opts)
}
export function renderToHTML (req, res, pathname, query, opts) {
......@@ -25,7 +25,7 @@ export function renderToHTML (req, res, pathname, query, opts) {
export async function renderError (err, req, res, pathname, query, opts) {
const html = await renderErrorToHTML(err, req, res, query, opts)
sendHTML(req, res, html, req.method)
sendHTML(req, res, html, req.method, opts)
}
export function renderErrorToHTML (err, req, res, pathname, query, opts = {}) {
......@@ -90,15 +90,21 @@ async function doRender (req, res, pathname, query, {
}
const docProps = await loadGetInitialProps(Document, { ...ctx, renderPage })
// While developing, we should not cache any assets.
// So, we use a different buildId for each page load.
// With that we can ensure, we have unique URL for assets per every page load.
// So, it'll prevent issues like this: https://git.io/vHLtb
const devBuildId = Date.now()
if (res.finished) return
if (!Document.prototype || !Document.prototype.isReactComponent) throw new Error('_document.js is not exporting a React element')
const doc = createElement(Document, {
__NEXT_DATA__: {
props,
pathname,
query,
buildId,
buildId: dev ? devBuildId : buildId,
buildStats,
assetPrefix,
nextExport,
......@@ -160,7 +166,7 @@ export async function renderScriptError (req, res, page, error, customFields, op
`)
}
export function sendHTML (req, res, html, method) {
export function sendHTML (req, res, html, method, { dev }) {
if (res.finished) return
const etag = generateETag(html)
......@@ -170,6 +176,12 @@ export function sendHTML (req, res, html, method) {
return
}
if (dev) {
// In dev, we should not cache pages for any reason.
// That's why we do this.
res.setHeader('Cache-Control', 'no-store, must-revalidate')
}
res.setHeader('ETag', etag)
res.setHeader('Content-Type', 'text/html')
res.setHeader('Content-Length', Buffer.byteLength(html))
......
/* global describe, test, expect */
import fetch from 'node-fetch'
export default function (context) {
describe('Misc', () => {
......@@ -13,14 +12,5 @@ export default function (context) {
const html = await context.app.renderToHTML({}, res, '/finish-response', {})
expect(html).toBeFalsy()
})
test('allow etag header support', async () => {
const url = `http://localhost:${context.appPort}/stateless`
const etag = (await fetch(url)).headers.get('ETag')
const headers = { 'If-None-Match': etag }
const res2 = await fetch(url, { headers })
expect(res2.status).toBe(304)
})
})
}
......@@ -9,6 +9,7 @@ import {
renderViaHTTP
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import fetch from 'node-fetch'
const appDir = join(__dirname, '../')
let appPort
......@@ -35,6 +36,15 @@ describe('Production Usage', () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Hello World/)
})
it('should allow etag header support', async () => {
const url = `http://localhost:${appPort}/`
const etag = (await fetch(url)).headers.get('ETag')
const headers = { 'If-None-Match': etag }
const res2 = await fetch(url, { headers })
expect(res2.status).toBe(304)
})
})
describe('With navigation', () => {
......
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