vercel / next.js Goto Github PK
View Code? Open in Web Editor NEWThe React Framework
Home Page: https://nextjs.org
License: MIT License
The React Framework
Home Page: https://nextjs.org
License: MIT License
I've also been exploring this too. Definitely think this is the right direction forward. One simplification that I think can be made is to represent the entire HTML tree in the page, so instead of this:
export default () => <div>
<Head>
<meta content='my meta' />
</Head>
<h1>I can haz meta tags</h1>
</div>
With side-effect and DOM-reaching craziness, you could do something like this:
export default () => (
<html>
<head>
<meta content='my meta' />
</head>
<body>
<h1>I can haz meta tags</h1>
</body>
</html>
)
Implementation goes like this:
html
component reaches into the children, finds the first child in body
and returns that.Under examples
, with standard
+ jsx support
I noticed that one React root is used, while this is certainly the simplest solution, I'm curious if there's a plan to support or use multiple React roots?
In the current architecture with a single root, a client-side navigation blows away everything visible on the page and re-renders everything for the new route, including parts of the component tree that exist on both routes.
With multiple React roots, common site elements like a <header>
could be in their own React root, and when the same page "region" exists between two routes the component tree won't need to be torn down and re-rendered during that client-side navigation. An architecture with multiple roots/regions would also allow the server to flush out to the response before waiting for the entire page to be rendered.
I imagine that when using Next, it'll be natural to break out common page-level UI component trees, like the site's header, and reuse it on all pages, similar to an "include", and at these page "region" boundaries there's an opportunity to use multiple React roots to speed up both server and client rendering.
So I'm mainly curious if this sort of thing might be part of Next in the future, or if the simplicity of one React root and re-rendering the entire page on client-side navigation is an explicit design decision for the framework?
Some example scenarios to check
/test
and test.js
doesn't exist, render 404
. Creating it renders test.js
test.js
but with an error, we replace the 404
with an errortest.js
has an error but I remove it, render 404
error.js
has an error (fallback + console.error
in main terminal is acceptable for this)error.js
works when rendering an error{
"name": "mistat",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"author": "",
"license": "ISC",
"dependencies": {
"next": "latest"
},
"next":{"cdn":false}
}
when I run next build & next start or run next ,the cdn is not dispair,shall we style the cdn link in our service ?
Like inferno
or preact
.
From the end user perspective, it would work as follows.
Configure package.json
:
{
"dependencies:" {
"next": "x.y.z",
"next-preact": "x.y.z",
"preact": "x.y.z"
}
}
Then we transform JSX to the pragma that, in this example, next-preact
would need.
The rendering pipeline would similarly be pluggable.
next -s server.js
or in package.json
:
{
"next": {
"serverHandler": "./server.js"
}
}
Let's say you want to override the default mapping between filesystem and route, you could set up something like this:
const { renderComponent } = require('next/server')
module.exports = ({ path, req, res }) => {
if ('/a' === path) {
return renderComponent(req, './b')
}
}
The function would receive a context object with the following properties (as far as I have thought about it):
path
the intended path of the request. This is so that if we request /a.json
or /a
, the path is still /a
, which simplifies the logic for the programmerreq
the original request from noderes
the original response from nodeThe return value can be a Promise
. If undefined
is returned, it performs the default behavior.
This file provides an opportunity to short-circuit (like send a 301
), add global security / authentication requirements, etc.
[1] We might or might not want to transpile this file. Since it's "server-only", I think it's ok to assume it just supports whatever the version of Node.js you're running.
Is there currently any way to render partials? For example, how would one go about adding a component to the application without having to tack it onto each and every file in the pages directory?
Hi,
Will next provide a ability to allow us to embed our own Express.js middlewares / routers for handling server side logic, e.g. backend API.
We can have the following server/body-parser-urlencoded-middleware.js
:
import bodyParser from 'body-parser-urlencoded'
export default bodyParser.urlencoded({ extended: false })
and also api-router.js
:
import express from 'express'
const router = express.Router()
router.get('/',(req, res) => {
res.send('Hello API')
})
export default router
And for next side will just grabbing all files under server/
directory,
If the filename ends with "middleware" then plug it like app.use(middleware())
If ends with "router" then extract the route, in the case above is app.use("/api", router)
and we can request to the API in our next app.
Just a basic concept for open discussion, or is there any other method to implement API feature? Thanks.
Hello,
I'm trying to include a css resource using the Head
component (it's a large css file, so I don't want to use glamor
)
<Head>
<meta charSet='utf-8'/>
<meta name='viewport' content='initial-scale=1.0, width=device-width'/>
<link rel="stylesheet" href="/static/css/application.css"/>
<script defer src="/static/js/application.js"></script>
</Head>
Unfortunately by doing so, when I navigate to another page, the css gets unloaded and then loaded again causing the UI to kinda "flicker".
What's the NextJS way to deal with that use case?
Thank you.
Repo will add CI for automatic testing when have new pull request ?
This way, people can avoid accidents and side-effects. Typically if you're starting a next build
you want to start from a clean slate.
Displaying a simple warning in stdout is probably a good idea.
Platform: Linux (Arch) x86_64
node: v6.9.1
npm: 3.10.9
pages/index.js:
import React from 'react'
export default () => (
<div>Welcome to next.js!</div>
)
when I run next
I get:
ERROR in ./pages/index.js
Module build failed: ReferenceError: Unknown plugin "transform-async-to-generator" specified in "base" at 0, attempted to resolve relative to "/home/gk/projects/test/pages"
at /usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:176:17
at Array.map (native)
at Function.normalisePlugins (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:154:20)
at OptionManager.mergeOptions (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:228:36)
at OptionManager.init (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/options/option-manager.js:373:12)
at File.initOptions (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/index.js:221:65)
at new File (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/file/index.js:141:24)
at Pipeline.transform (/usr/lib/node_modules/next/node_modules/babel-core/lib/transformation/pipeline.js:46:16)
at transpile (/usr/lib/node_modules/next/node_modules/babel-loader/index.js:38:20)
at Object.module.exports (/usr/lib/node_modules/next/node_modules/babel-loader/index.js:131:12)
@ multi bundles/pages/index.js
As far as I can tell, the static getInitialProps
doesn't provide a uniform way to access url params on the client and server. On the server, you can access req
and parse the url yourself. On the client, we don't seem to have access to the route information within the getInitialProps
function. The uses for this are fairly obvious, i think, such as loading a particular user profile based on an :id
param, and so on. I'm also wondering if auth could somehow be implemented here too -- thought I'm less clear if that's the best API.
There appears to be no provision made in the Next code for terminating the application gracefully. I don't see any hooks into SIGTERM or SIGKILL events, and server/index.js
doesn't offer a stop()
function.
This means that any time the app receives a shutdown event from the host machine it will halt while in the middle of handling requests instead of waiting for the requests to complete and properly stopping the server.
This also makes it impossible to start and stop the server in integration tests.
JSX
as used with most React
projects comes with a very obscure situation
The following doesn't work:
export default () => <div />
You need to import React from 'react'
so that the JSX transformation to React.createElement
, which appears nowhere in the source, works.
How do we fix this?
For the vast number of users who with very good reasons reject CSS-in-JS, we could support something like this:
import Head from 'next/head'
import shadow from 'next-shadow'
export shadow(() => (
<footer>
<div>hi <span>world</span></div>
<style>{`
div span {
/* this won't conflict with any other element anywhere,
including spans from nested components */
color: red
}
`}</style>
</footer>
))
In the future, if we find a way of making this work with server-rendering, we could make every single component a custom element with built-in isolation capabilities out of the box, no shadow()
wrapping needed. If you want global effects, you can use <Head>
, otherwise everything is isolated.
This would put CSS-in-JS and full CSS support on equal ground, both supported, both with pros-and-cons and great performance.
The problems:
We want to have an example of global state. Since Redux is King of Global State®, let's go with a tiny redux example.
See Slack conversation for reference
Something similar to https://react-router.now.sh/route-config ?
An example would be of helpful.
next-prefetch
is a substitute for <Link />
(builds on top of it) that:
ServiceWorker
prefetch={false}
if you want to turn it offfallbackWorker={true}
to fallback to a web worker if the browser doesn't support service workers.This is the technique that we use at ▲ZEIT to make everything really speedy.
We need to extract it out of our impl or someone can write this from scratch.
Installing a service worker is pretty intrusive, so I don't think this is something we want in core. We can write it as a separate module.
Makes the contribution cycle a lot nicer, specially from the community
Per FAQ:
We intend for Next.js
to be a great starting point for any website or app, no matter how small.
If you’re building a very small mostly-content website, you still want to benefit from features like lazy-loading, a component architecture and module bundling.
But in some cases, the size of React itself would far exceed the content of the page!
For this reason we want to promote a situation where users can share the cache for the basic runtime across internet properties. The application code continues to load from your server as usual.
We are committed to providing a great uptime and levels of security for our CDN. Even so, we also automatically fall back if the CDN script fails to load with a simple trick.
To turn the CDN off, just set { “next”: { “cdn”: false } }
in package.json
.
Perhaps directly take babel
in package.json
, unless next.babel
is set.
Looking at the overall project structure, this seems like a rather easy step on your roadmap. Maybe someone from the team can provide a good starting point for contributors?
I'm just wondering, if I want to use an image in my component how should I handle it ? and where the image should be stored ? Couldn't find that in your docs or examples.
By visiting the index page location at http://localhost/
the following thrown:
> next start
> Ready on http://localhost:3000
{ [Error: Cannot find module /home/ubuntu/workspace/.next/dist/pages/_error] code: 'ENOENT' }
Filesystem:
- package.json
- node_modules
- pages
- index.js
index.js
:
import React from 'react'
export default () => (
<div>Welcome to next.js!</div>
)
Thanks for help!
Is there any support for route params like so?
/photos/:id
If not, how would that look with the proposed pages/*.js
structure?
While running Redux example on server with UTC time set, I've got these errors in my browser console because of timezone differences:
next-dev.bundle.js:8985 Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) " data-reactid="1">15:03:39
(server) " data-reactid="1">12:03:39
Possible fix is to change Clock.js :13 from:
const format = t => `${pad(t.getHours())}:${pad(t.getMinutes())}:${pad(t.getSeconds())}`
to:
const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
For tests
this looks awesome but I also really like TypeScript.
is there any way to integrate typescript into the workflow?
Would you plan to support vue.js as an alternative to react?
I expected next --help
to be a thing:
❯ next --help
> Ready on http://localhost:3000
> Couldn't find a `pages` directory. Please create one under the project root
next build
is currently undocumented. My goal was to discover its purpose without reading the code. 😛
Having animated route transitions would be nice, as this is one of the many benefits through client-side routing. Doing so should be left up to the user in my opinion (some people prefer CSS transitions over more fine-grained control with react-motion
etc). As I understand it, one would need to modify the top-level App component.
The client entry file seems to look for a globally assigned __NEXT_DATA__.app
variable but I can't find any documentation on that.
In https://zeit.co/blog/next#data-fetching-is-up-to-the-developer, export class exports React.Component {
should be export default class extends React.Component {
.
In the React context, when building an app I'm used to the concept of containers and components. It appears to me that "pages" are somewhat equivalent to containers within next.js.
Is there a recommended way to add an application layout container such that I could specify for example global <Header/>
and <Footer/>
components with the router determining which content to display within (the page)? Similar to how the popular react-router
package match
function can be configured on the server.
Using the next.js default router and pages folder as is, to achieve this do I have no option but to duplicate <Header/>
and <Footer/>
across all pages?
It'd be nice to add hooks for webpack, and describe on the README (similarly to #26) how to for example add require('./something.css')
support.
Via eslintConfig
in package
preferrably
Hey!
Really cool project. I was just following the demo on the site and I did the following:
brew install node
mkdir foo
cd foo
npm init
npm install next ---save
mkdir pages
vim pages/index.js
next
and then !
command not found: next
shoot
oh..
./node_modules/next/dist/bin/next
that works.
I'm a noob JavaScript developer, should I have some sort of relative path setup for that?
Just a heads up, thanks!
$ node -v
v7.0.0
$ npm -v
3.10.8
$ tree . -L 2
.
├── package.json
└── pages
└── index.js
$ cat pages/index.js
import React from 'react'
export default () => {
<div>Welcome to next.js!</div>
}
$ cat package.json
{
"name": "next-play",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"next": "^1.0.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "next"
},
"author": "",
"license": "ISC"
}
$ npm start
> [email protected] start /Users/ext.dmosher/code/next-play
> next
> Ready on http://localhost:3000
Warning: Component(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
{ Invariant Violation: Component(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
at invariant (/Users/ext.dmosher/code/next-play/node_modules/fbjs/lib/invariant.js:38:15)
at ReactCompositeComponentWrapper.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactCompositeComponent.js:194:121)
at Object.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactReconciler.js:47:35)
at ReactCompositeComponentWrapper.performInitialMount (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactCompositeComponent.js:370:34)
at ReactCompositeComponentWrapper.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactCompositeComponent.js:257:21)
at Object.mountComponent (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactReconciler.js:47:35)
at /Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactServerRendering.js:46:36
at ReactServerRenderingTransaction.perform (/Users/ext.dmosher/code/next-play/node_modules/react/lib/Transaction.js:138:20)
at renderToStringImpl (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactServerRendering.js:44:24)
at renderToString (/Users/ext.dmosher/code/next-play/node_modules/react/lib/ReactServerRendering.js:74:10) name: 'Invariant Violation', framesToPop: 1 }
We can have a declarative way of ensuring an element appears at-most-once in the <head>
. We de-dupe based on the id
attribute of an element. It could also be key
but not sure if that interferes with React internals.
<Head>
<style id="woot">{`
/* this element will be appended at-most-once */
/* even if it appears in multiple components */
`}</style>
</Head>
I think it would be great to have parameter in URL functionality (for example /users/:id
) while still keeping the simplicity of next
itself.
My proposition is to do this for structure:
pages/
index.js
users/
_id.js
id.js
will be seen as a parameter path and will receive id
as prop. You could also go further and make it like this to map /users/:id/friends/:friendid
:
pages/
index.js
users/
_id/
index.js
friends/
_friendid.js
If the id is not specified (eg. /users/
) then we'll first check if there is an index.js
and otherwise use _id.js
.
I created this issue to see if others are interested in this and to see what everyones thoughts/feedback is on this. I'm willing to build this if this is a wanted feature! 😄
Some of the modules are specified with a caret while some are not. Is this intentional?
"devDependencies": {
"babel-eslint": "^7.0.0",
"babel-plugin-transform-remove-strict-mode": "0.0.2",
"benchmark": "2.1.1",
"gulp": "3.9.1",
"gulp-ava": "0.14.1",
"gulp-babel": "6.1.2",
"gulp-benchmark": "^1.1.1",
"gulp-cached": "1.1.0",
"gulp-notify": "2.2.0",
"husky": "^0.11.9",
"run-sequence": "1.2.2",
"standard": "^8.4.0",
"webpack-stream": "3.2.0"
}
next
fails to build the bundle if installed using npm@latest-2
.
First off, spot on! next.js
is an awesome idea!
I tried the framework by hacking down an Index
component which is hooked up to a firebase
instance. Unfortunately the firebase
library holds it's state internally, which brakes the component after performing a hard reload:
import React, { Component } from 'react';
import firebase from 'firebase';
class Index extends Component {
constructor() {
super();
this.state = {
users: []
};
}
componentWillMount() {
firebase.initializeApp({
apiKey: '...',
authDomain: '...',
databaseURL: '...',
storageBucket: '...',
messagingSenderId: '...'
});
firebase.database().ref('/users/').on('child_added', data => {
this.setState({
users: [...this.state.users, data.val()]
});
});
}
render() {
const { users } = this.state;
return (
<div>
{users.map(user =>
<div key={user.id}>{user.name}</div>
)}
</div>
);
}
}
export default Index;
next build
next start
Error in browser console:
VM3895:2 You are currently using minified code outside of NODE_ENV === 'production'. This means that you are running a slower development build of Redux. You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) to ensure you have the correct code for your production build.
Is there a way to use NODE_ENV === 'production' with Next.js build/start scripts?
Following the readme example, it indicates to install next with npm install next --save
. I couldnt get the example to work this way.
zsh: command not found: next
Shouldn't this be npm install -g next
so that the next command is global?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.