Commit 07b46d7f authored by Nataliya Karatkova's avatar Nataliya Karatkova Committed by Tim Neutkens

Update examples: static export using dynamic routes instead exp… (#9237)

parent cb7a184c
......@@ -36,6 +36,6 @@ yarn dev
## The idea behind the example
This example show how to export to static HTML files your Next.js application fetching data from an API to generate a dynamic list of pages. This use a custom Express server in development to configure custom routing and then generate a map of pages to export for production.
This example show how to export to static HTML files your Next.js application fetching data from an API to generate a dynamic list of pages.
When trying to run `npm start` it will build and export your pages into the `out` folder and serve them on `localhost:5000`.
import Link from 'next/link'
export default props => (
export default ({ title, body, id }) => (
<article>
<h2>{props.title}</h2>
<p>{props.body}</p>
{/* render the URL as /post/:id */}
<Link
href={{ pathname: '/post', query: { id: props.id } }}
as={`/post/${props.id}`}
>
<h2>{title}</h2>
<p>{body}</p>
<Link href='/post/[id]' as={`/post/${id}`}>
<a>Read more...</a>
</Link>
</article>
......
......@@ -13,7 +13,7 @@ module.exports = {
(pages, post) =>
Object.assign({}, pages, {
[`/post/${post.id}`]: {
page: '/post',
page: '/post/[id]',
query: { id: post.id }
}
}),
......
{
"name": "with-static-export",
"main": "server.js",
"dependencies": {
"express": "^4.15.3",
"isomorphic-unfetch": "^2.0.0",
"isomorphic-unfetch": "^3.0.0",
"next": "latest",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"serve": "9.4.0"
"react": "^16.11.0",
"react-dom": "^16.11.0",
"serve": "11.2.0"
},
"scripts": {
"dev": "node .",
"dev": "next",
"build": "next build",
"preexport": "npm run build",
"export": "next export",
......
......@@ -14,15 +14,17 @@ export default class extends Component {
}
render () {
const { title, body } = this.props
return (
<main>
<Head>
<title>{this.props.title}</title>
<title>{title}</title>
</Head>
<h1>{this.props.title}</h1>
<h1>{title}</h1>
<p>{this.props.body}</p>
<p>{body}</p>
<Link href='/'>
<a>Go back to home</a>
......
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
// custom route for posts
server.get('/post/:id', (req, res) => {
return app.render(req, res, '/post', {
id: req.params.id
})
})
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
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