Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Newexample #2070

Closed
wants to merge 13 commits into from
Closed
11 changes: 10 additions & 1 deletion client/webpack-hot-middleware-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion examples/layout-component/components/layout.js
Original file line number Diff line number Diff line change
Expand Up @@ -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>
)
2 changes: 1 addition & 1 deletion examples/with-i18next/components/Title.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
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>))
7 changes: 5 additions & 2 deletions examples/with-i18next/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,20 @@ 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 }
}

constructor (props) {
super(props)

this.i18n = startI18n(props.translations)
this.i18n = startI18n(props.translations, lang)
}

render (props) {
Expand Down
3 changes: 3 additions & 0 deletions examples/with-i18next/static/locales/id/common.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"hello": "halo"
}
3 changes: 2 additions & 1 deletion examples/with-i18next/static/locales/pt/common.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"hello": "e ae tche"
"hello": "e ae tche",
"morning": "manha"
}
3 changes: 2 additions & 1 deletion examples/with-i18next/tools/startI18n.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
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'],
Expand Down
25 changes: 25 additions & 0 deletions examples/with-johnnyFive/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[![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-socket.io)

# Socket.io 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-socket.io
cd with-socket.io
```

Install it and run:

```bash
npm install
npm run dev
```

## The idea behind the example

This example show how to use [socket.io](https://socket.io/) inside a Next.js application. It uses `getInitialProps` to fetch the old messages from a HTTP endpoint as if it was a Rest API. The example combine the WebSocket server with the Next server, in a production application you should split them as different services.

**Example:** [https://next-socket-io.now.sh/](https://next-socket-io.now.sh/)
24 changes: 24 additions & 0 deletions examples/with-johnnyFive/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"name": "next",
"version": "3.0.0-beta6",
"main": "./dist/server/next.js",
"license": "MIT",
"dependencies": {
"express": "^4.15.2",
"isomorphic-fetch": "^2.2.1",
"johnny-five": "^0.10.13",
"next": "latest",
"react": "^15.5.4",
"react-dom": "^15.5.4",
"socket.io": "^1.7.3",
"socket.io-client": "^1.7.3",
"react-hot-loader": "3.0.0-beta.6",
"recursive-copy": "^2.0.6",
"send": "0.15.3",
},
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
32 changes: 32 additions & 0 deletions examples/with-johnnyFive/pages/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { Component } from 'react'
import io from 'socket.io-client'
import fetch from 'isomorphic-fetch'

class HomePage extends Component {
// init state with the prefetched messages
state = {
ledState: 0
}

// connect to WS server and listen event
componentDidMount () {
this.socket = io('http://localhost:3000/')
}

handleLed(state) {
this.socket.emit('led', state)
}

render () {
return (
<main>
<div>
<button onClick={() => this.handleLed(1)}>ON</button>
<button onClick={() => this.handleLed(0)}>OFF</button>
</div>
</main>
)
}
}

export default HomePage
61 changes: 61 additions & 0 deletions examples/with-johnnyFive/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const app = require('express')()
const server = require('http').Server(app)
const io = require('socket.io')(server)
const next = require('next')
//http://johnny-five.io/
const five = require('johnny-five');

const dev = process.env.NODE_ENV !== 'production'
const nextApp = next({ dev })
const nextHandler = nextApp.getRequestHandler()

let led = null;

five.Board().on('ready', function() {
console.log('Arduino is ready.');

// Initial state
let state = {
value: 0
};

// Map pins to digital inputs on the board
led = new five.Led(13);

});

nextApp.prepare().then(() => {

app.get('*', (req, res) => {
return nextHandler(req, res)
})

var setState = function(st) {
if(st == 1){
led.on();
}else {
led.off();
}
};

io.on('connection', function(client) {
client.on('join', function(handshake) {
console.log(handshake);
});

client.on('led', function(data) {
// Set the new colors
setState(data);

//client.emit('led', data);
//client.broadcast.emit('led', data);
});
});

//You should change 'localhost' by you ip adress.
//change it on the index.js too.
server.listen(3000, 'localhost', (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
9 changes: 0 additions & 9 deletions flyfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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')
}
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "next",
"version": "2.3.1",
"version": "2.4.0",
"description": "Minimalistic framework for server-rendered React applications",
"main": "./dist/server/next.js",
"license": "MIT",
Expand Down Expand Up @@ -80,7 +80,7 @@
"path-match": "1.2.4",
"pkg-up": "2.0.0",
"prop-types": "15.5.10",
"react-hot-loader": "3.0.0-beta.6",
"react-hot-loader": "3.0.0-beta.7",
"send": "0.15.2",
"source-map-support": "0.4.15",
"strip-ansi": "3.0.1",
Expand Down
8 changes: 4 additions & 4 deletions server/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -103,8 +103,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
Expand Down
18 changes: 16 additions & 2 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,24 +100,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)
Expand Down Expand Up @@ -225,7 +233,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) {
Expand Down Expand Up @@ -253,7 +261,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) {
Expand Down Expand Up @@ -335,10 +343,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')
}
}
Loading