diff --git a/.github/ISSUE_TEMPLATE/1.Bug_report.md b/.github/ISSUE_TEMPLATE/1.Bug_report.md
index 6172fe14ec482..6c10e9edc66b8 100644
--- a/.github/ISSUE_TEMPLATE/1.Bug_report.md
+++ b/.github/ISSUE_TEMPLATE/1.Bug_report.md
@@ -12,21 +12,25 @@ A clear and concise description of what the bug is.
## To Reproduce
Steps to reproduce the behavior, please provide code snippets or a repository:
+
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
## Expected behavior
+
A clear and concise description of what you expected to happen.
## Screenshots
+
If applicable, add screenshots to help explain your problem.
## System information
- - OS: [e.g. macOS, Windows]
- - Browser (if applies) [e.g. chrome, safari]
- - Version of Next.js: [e.g. 6.0.2]
+
+- OS: [e.g. macOS, Windows]
+- Browser (if applies) [e.g. chrome, safari]
+- Version of Next.js: [e.g. 6.0.2]
## Additional context
diff --git a/.github/ISSUE_TEMPLATE/2.Feature_request.md b/.github/ISSUE_TEMPLATE/2.Feature_request.md
index 6d6da1091c57d..92a257d1a7e80 100644
--- a/.github/ISSUE_TEMPLATE/2.Feature_request.md
+++ b/.github/ISSUE_TEMPLATE/2.Feature_request.md
@@ -6,13 +6,17 @@ about: Create a feature request for the Next.js core
# Feature request
## Is your feature request related to a problem? Please describe.
+
A clear and concise description of what you want and what your use case is.
## Describe the solution you'd like
+
A clear and concise description of what you want to happen.
## Describe alternatives you've considered
+
A clear and concise description of any alternative solutions or features you've considered.
## Additional context
+
Add any other context or screenshots about the feature request here.
diff --git a/.github/ISSUE_TEMPLATE/3.Example_Bug_report.md b/.github/ISSUE_TEMPLATE/3.Example_Bug_report.md
index be1f0d71892d1..a1640aee8e591 100644
--- a/.github/ISSUE_TEMPLATE/3.Example_Bug_report.md
+++ b/.github/ISSUE_TEMPLATE/3.Example_Bug_report.md
@@ -6,28 +6,35 @@ about: Create a bug report for one of the Next.js examples
# Examples bug report
## Example name
+
Provide the example name
## Describe the bug
+
A clear and concise description of what the bug is.
## To Reproduce
+
Steps to reproduce the behavior, please provide code snippets or a repository:
+
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
## Expected behavior
+
A clear and concise description of what you expected to happen.
## Screenshots
+
If applicable, add screenshots to help explain your problem.
## System information
- - OS: [e.g. macOS, Windows]
- - Browser (if applies) [e.g. chrome, safari]
- - Version of Next.js: [e.g. 6.0.2]
+
+- OS: [e.g. macOS, Windows]
+- Browser (if applies) [e.g. chrome, safari]
+- Version of Next.js: [e.g. 6.0.2]
## Additional context
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
index 09c934f1b8947..f264ef949da55 100644
--- a/CODE_OF_CONDUCT.md
+++ b/CODE_OF_CONDUCT.md
@@ -1,28 +1,28 @@
## Code of Conduct
- ### Our Pledge
+### Our Pledge
- In the interest of fostering an open and welcoming environment, we as
+In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
- ### Our Standards
+### Our Standards
- Examples of behavior that contributes to creating a positive environment
+Examples of behavior that contributes to creating a positive environment
include:
- - Using welcoming and inclusive language
+- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members
- Examples of unacceptable behavior by participants include:
+Examples of unacceptable behavior by participants include:
- - The use of sexualized language or imagery and unwelcome sexual attention or
+- The use of sexualized language or imagery and unwelcome sexual attention or
advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
@@ -31,44 +31,44 @@ include:
- Other conduct which could reasonably be considered inappropriate in a
professional setting
- ### Our Responsibilities
+### Our Responsibilities
- Project maintainers are responsible for clarifying the standards of acceptable
+Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
- Project maintainers have the right and responsibility to remove, edit, or
+Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
- ### Scope
+### Scope
- This Code of Conduct applies both within project spaces and in public spaces
+This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
- ### Enforcement
+### Enforcement
- Instances of abusive, harassing, or otherwise unacceptable behavior may be
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [abuse@zeit.co](mailto:abuse@zeit.co). All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
- Project maintainers who do not follow or enforce the Code of Conduct in good
+Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
- ### Attribution
+### Attribution
- This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
- [homepage]: http://contributor-covenant.org
+[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
diff --git a/README-zh-CN.md b/README-zh-CN.md
index d617f60e8cb13..c306a19ad0f62 100644
--- a/README-zh-CN.md
+++ b/README-zh-CN.md
@@ -113,7 +113,7 @@ npm install --save next react react-dom
新建 `./pages/index.js` 到你的项目中:
```jsx
-export default () =>
Welcome to next.js!
;
+export default () =>
Welcome to next.js!
```
运行 `npm run dev` 命令并打开 `http://localhost:3000`。 要使用其他端口,你可以运行 `npm run dev -- -p `.
@@ -134,9 +134,9 @@ export default () =>
Welcome to next.js!
;
每个页面只会导入`import`中绑定以及被用到的代码. 这意味着页面不会加载不必要的代码
```jsx
-import cowsay from "cowsay-browser";
+import cowsay from 'cowsay-browser'
-export default () =>
`. Runs 3000 http requests.
+
```
npm run bench:stateless
```
- Stateless application which renders `
This is row {i}
` 10.000 times. Runs 500 http requests.
+
```
npm run bench:stateless-big
```
diff --git a/errors/cant-override-next-props.md b/errors/cant-override-next-props.md
index d47b6b4d9ffe1..35bfc02c82f09 100644
--- a/errors/cant-override-next-props.md
+++ b/errors/cant-override-next-props.md
@@ -6,7 +6,7 @@ In your `pages/_app.js` you returned an object from `getInitialProps` that conta
#### Possible Ways to Fix It
-Look in your _app.js component's `getInitialProps` function and make sure neither of these property names are present in the object returned.
+Look in your \_app.js component's `getInitialProps` function and make sure neither of these property names are present in the object returned.
### Useful Links
diff --git a/errors/config-resolve-alias.md b/errors/config-resolve-alias.md
index 3669e124de18f..feacf2e3a62eb 100644
--- a/errors/config-resolve-alias.md
+++ b/errors/config-resolve-alias.md
@@ -1,4 +1,4 @@
-# Invalid webpack resolve alias
+# Invalid webpack resolve alias
#### Why This Error Occurred
diff --git a/errors/conflicting-amp-tag.md b/errors/conflicting-amp-tag.md
index 6e5d87445288c..522aeb6fed30c 100644
--- a/errors/conflicting-amp-tag.md
+++ b/errors/conflicting-amp-tag.md
@@ -2,7 +2,7 @@
#### Why This Error Occurred
-In AMP mode Next.js adds certain necessary tags automatically to comply with the AMP standard. You added a tag using `next/head` that conflicts with one of these automatically added tags.
+In AMP mode Next.js adds certain necessary tags automatically to comply with the AMP standard. You added a tag using `next/head` that conflicts with one of these automatically added tags.
#### Possible Ways to Fix It
diff --git a/errors/doc-crossorigin-deprecated.md b/errors/doc-crossorigin-deprecated.md
index 6a4c8913ebf11..48b99e30013d4 100644
--- a/errors/doc-crossorigin-deprecated.md
+++ b/errors/doc-crossorigin-deprecated.md
@@ -11,7 +11,7 @@ Add the config option:
```js
// next.config.js
module.exports = {
- crossOrigin: 'anonymous'
+ crossOrigin: 'anonymous',
}
```
diff --git a/errors/get-initial-props-as-an-instance-method.md b/errors/get-initial-props-as-an-instance-method.md
index d9c58e617f182..bc1e9faed09b0 100644
--- a/errors/get-initial-props-as-an-instance-method.md
+++ b/errors/get-initial-props-as-an-instance-method.md
@@ -10,11 +10,11 @@ Use the static keyword.
```js
export default class YourEntryComponent extends React.Component {
- static getInitialProps () {
+ static getInitialProps() {
return {}
}
- render () {
+ render() {
return 'foo'
}
}
@@ -23,7 +23,7 @@ export default class YourEntryComponent extends React.Component {
or
```js
-const YourEntryComponent = function () {
+const YourEntryComponent = function() {
return 'foo'
}
diff --git a/errors/multi-tabs.md b/errors/multi-tabs.md
index 9b3b832069824..bf4f3f3d4abe3 100644
--- a/errors/multi-tabs.md
+++ b/errors/multi-tabs.md
@@ -10,4 +10,3 @@ More info here: https://tools.ietf.org/html/rfc6202#section-5.1
- Don't have too many tabs open to the same Next.js site open in development in the same browser at the same time.
- If using Firefox you can increase this limit by navigating to `about:config` and setting `network.http.max-persistent-connections-per-server` to a higher number
-
diff --git a/errors/next-export-serverless.md b/errors/next-export-serverless.md
index 56e7a1e5a07a0..f0224f770cda8 100644
--- a/errors/next-export-serverless.md
+++ b/errors/next-export-serverless.md
@@ -6,4 +6,4 @@ Next.js can only handle exporting when the `target` is set to `server` (this is
#### Possible Ways to Fix It
-Change `target` to `server`, run `next build`, then run `next export` again.
\ No newline at end of file
+Change `target` to `server`, run `next build`, then run `next export` again.
diff --git a/errors/no-document-title.md b/errors/no-document-title.md
index c71b6d5f6d007..53a3fa92a3d7b 100644
--- a/errors/no-document-title.md
+++ b/errors/no-document-title.md
@@ -1,4 +1,4 @@
-# `` should not be used in _document.js's ``
+# `` should not be used in \_document.js's ``
#### Why This Error Occurred
@@ -10,12 +10,12 @@ Set `` in `pages/_app.js` instead:
```js
// pages/_app.js
-import App, {Container} from 'next/app'
+import App, { Container } from 'next/app'
import Head from 'next/head'
import React from 'react'
export default class MyApp extends App {
- static async getInitialProps ({ Component, ctx }) {
+ static async getInitialProps({ Component, ctx }) {
let pageProps = {}
if (Component.getInitialProps) {
@@ -25,7 +25,7 @@ export default class MyApp extends App {
return { pageProps }
}
- render () {
+ render() {
const { Component, pageProps } = this.props
return (
@@ -40,7 +40,6 @@ export default class MyApp extends App {
}
```
-
### Useful Links
- [The issue this was reported in: #4596](https://github.com/zeit/next.js/issues/4596)
diff --git a/errors/no-on-app-updated-hook.md b/errors/no-on-app-updated-hook.md
index ec0e0524f88fe..c2ce7c5d7eacd 100644
--- a/errors/no-on-app-updated-hook.md
+++ b/errors/no-on-app-updated-hook.md
@@ -20,6 +20,6 @@ This is code for that:
window.onbeforeunload = function(e) {
// Get the application state (usually from a store like Redux)
const appState = {}
- localStorage.setItem('app-state', JSON.stringify(appState));
-};
+ localStorage.setItem('app-state', JSON.stringify(appState))
+}
```
diff --git a/errors/no-router-instance.md b/errors/no-router-instance.md
index 2381b0e72d6d1..504ce29ecd803 100644
--- a/errors/no-router-instance.md
+++ b/errors/no-router-instance.md
@@ -2,8 +2,8 @@
#### Why This Error Occurred
-During SSR you might have tried to access a router method `push`, `replace`, `back`, which is not supported.
+During SSR you might have tried to access a router method `push`, `replace`, `back`, which is not supported.
#### Possible Ways to Fix It
-Move any calls to router methods to `componentDidMount` or add a check such as `typeof window !== 'undefined'` before calling the methods
\ No newline at end of file
+Move any calls to router methods to `componentDidMount` or add a check such as `typeof window !== 'undefined'` before calling the methods
diff --git a/errors/promise-in-next-config.md b/errors/promise-in-next-config.md
index 781bf04972a87..7fb48b3b00419 100644
--- a/errors/promise-in-next-config.md
+++ b/errors/promise-in-next-config.md
@@ -8,7 +8,7 @@ The webpack function in `next.config.js` returned a promise which is not support
module.exports = {
webpack: async function(config) {
return config
- }
+ },
}
```
diff --git a/errors/serverless-publicRuntimeConfig.md b/errors/serverless-publicRuntimeConfig.md
index e6feecbe19111..deb4ca5cecd93 100644
--- a/errors/serverless-publicRuntimeConfig.md
+++ b/errors/serverless-publicRuntimeConfig.md
@@ -3,6 +3,7 @@
#### Why This Error Occurred
In the `serverless` target environment `next.config.js` is not loaded, so we don't support `publicRuntimeConfig`.
+
#### Possible Ways to Fix It
Use config option `env` to set **build time** variables like such:
@@ -11,12 +12,12 @@ Use config option `env` to set **build time** variables like such:
// next.config.js
module.exports = {
env: {
- special: "value"
- }
+ special: 'value',
+ },
}
```
```js
// pages/index.js
console.log(process.env.special) // value
-```
\ No newline at end of file
+```
diff --git a/errors/threw-undefined.md b/errors/threw-undefined.md
index 79dd763b2bb8e..0d4129ef4f115 100644
--- a/errors/threw-undefined.md
+++ b/errors/threw-undefined.md
@@ -4,7 +4,6 @@
Somewhere in your code you `throw` an `undefined` value. Since this isn't a valid error there isn't a stack trace. We show this error instead to let you know what to look for.
-
#### Possible Ways to Fix It
Look in your pages and find where an error could be throwing `undefined`
diff --git a/errors/url-deprecated.md b/errors/url-deprecated.md
index 3152f1427773b..d583128789469 100644
--- a/errors/url-deprecated.md
+++ b/errors/url-deprecated.md
@@ -22,7 +22,7 @@ import { withRouter } from 'next/router'
class Page extends React.Component {
render() {
- const {router} = this.props
+ const { router } = this.props
console.log(router)
return
{router.pathname}
}
diff --git a/examples/custom-server-actionhero/README.md b/examples/custom-server-actionhero/README.md
index 5acfb98033886..f70e37f9b424a 100644
--- a/examples/custom-server-actionhero/README.md
+++ b/examples/custom-server-actionhero/README.md
@@ -43,62 +43,65 @@ yarn start
```js
// initializers/next.js
-const {Initializer, api} = require('actionhero')
+const { Initializer, api } = require('actionhero')
const next = require('next')
module.exports = class NextInitializer extends Initializer {
- constructor () {
+ constructor() {
super()
this.name = 'next'
}
- async initialize () {
+ async initialize() {
api.next = {
- render: async (connection) => {
- if (connection.type !== 'web') { throw new Error('Connections for NEXT apps must be of type "web"') }
+ render: async connection => {
+ if (connection.type !== 'web') {
+ throw new Error('Connections for NEXT apps must be of type "web"')
+ }
const req = connection.rawConnection.req
const res = connection.rawConnection.res
return api.next.handle(req, res)
- }
+ },
}
- api.next.dev = (api.env === 'development')
- if (api.next.dev) { api.log('Running next in development mode...') }
+ api.next.dev = api.env === 'development'
+ if (api.next.dev) {
+ api.log('Running next in development mode...')
+ }
- api.next.app = next({dev: api.next.dev})
+ api.next.app = next({ dev: api.next.dev })
api.next.handle = api.next.app.getRequestHandler()
await api.next.app.prepare()
}
- async stop () {
+ async stop() {
await api.next.app.close()
}
}
```
-2. Create an action which will run the above `api.next.render(connection)`. Note that we will not be relying on ActionHero to respond to the client's request in this case, and leave that up to next (via: `data.toRender = false`)
+2. Create an action which will run the above `api.next.render(connection)`. Note that we will not be relying on ActionHero to respond to the client's request in this case, and leave that up to next (via: `data.toRender = false`)
```js
// actions/next.js
-const {Action, api} = require('actionhero')
+const { Action, api } = require('actionhero')
module.exports = class CreateChatRoom extends Action {
- constructor () {
+ constructor() {
super()
this.name = 'render'
this.description = 'I render the next.js react website'
}
- async run (data) {
+ async run(data) {
data.toRender = false
return api.next.render(data.connection)
}
}
-
```
-3. Tell ActionHero to use the api rather than the file server as the top-level route in `api.config.servers.web.rootEndpointType = 'api'`. This will allows "/" to listen to API requests. Also update `api.config.general.paths.public = [ path.join(__dirname, '/../static') ]`. In this configuration, the next 'static' renderer will take priority over the ActionHero 'public file' api. Note that any static assets (CSS, fonts, etc) will need to be in "./static" rather than "./public".
+3. Tell ActionHero to use the api rather than the file server as the top-level route in `api.config.servers.web.rootEndpointType = 'api'`. This will allows "/" to listen to API requests. Also update `api.config.general.paths.public = [ path.join(__dirname, '/../static') ]`. In this configuration, the next 'static' renderer will take priority over the ActionHero 'public file' api. Note that any static assets (CSS, fonts, etc) will need to be in "./static" rather than "./public".
Note that this is where the websocket server, if you enable it, will place the `ActionheroWebsocketClient` libraray.
@@ -108,14 +111,14 @@ Note that this is where the websocket server, if you enable it, will place the `
// config/routes.js
exports['default'] = {
- routes: (api) => {
+ routes: api => {
return {
get: [
{ path: '/time', action: 'time' },
- { path: '/', matchTrailingPathParts: true, action: 'render' }
- ]
+ { path: '/', matchTrailingPathParts: true, action: 'render' },
+ ],
}
- }
+ },
}
```
diff --git a/examples/custom-server-koa/README.md b/examples/custom-server-koa/README.md
index a1632000844c2..b617d1be04d0f 100644
--- a/examples/custom-server-koa/README.md
+++ b/examples/custom-server-koa/README.md
@@ -53,8 +53,8 @@ The most common Koa middleware for handling the gzip compression is [compress](h
If you need to enable the gzip compression, the most simple way to do so is by wrapping the express-middleware [compression](https://github.com/expressjs/compression) with [koa-connect](https://github.com/vkurchatkin/koa-connect):
```javascript
-const compression = require("compression");
-const koaConnect = require("koa-connect");
+const compression = require('compression')
+const koaConnect = require('koa-connect')
-server.use(koaConnect(compression()));
+server.use(koaConnect(compression()))
```
diff --git a/examples/custom-server-reasonml/README.md b/examples/custom-server-reasonml/README.md
index b08dce119b1eb..cc74993a867c6 100644
--- a/examples/custom-server-reasonml/README.md
+++ b/examples/custom-server-reasonml/README.md
@@ -1,6 +1,7 @@
# Custom server REASONML
# Install it and run:
+
```bash
npm install
npm run dev
@@ -10,21 +11,25 @@ yarn dev
```
# Build the app
+
```bash
yarn next:build
npm run next:build
```
# Run the production app
+
Run this command after yarn build.
+
```bash
yarn start
```
# The idea behind this example
+
ReasonML is an exciting new language and since it can compile directly to JS via bucklescript
-that means that we can power our backend server with REASONML and also have the frontend built with
+that means that we can power our backend server with REASONML and also have the frontend built with
reasonreact, which is covered in another [example](https://github.com/zeit/next.js/tree/canary/examples/with-reasonml).
This example shows how powerful & helpful it can be to build a next js custom server with a typesafe language.
-The example has been built off the `custom-server` example that uses pure `nodejs` to build the custom server.
\ No newline at end of file
+The example has been built off the `custom-server` example that uses pure `nodejs` to build the custom server.
diff --git a/examples/custom-server-reasonml/bsconfig.json b/examples/custom-server-reasonml/bsconfig.json
index 328150f88e630..f04ac0bec3cc7 100644
--- a/examples/custom-server-reasonml/bsconfig.json
+++ b/examples/custom-server-reasonml/bsconfig.json
@@ -11,4 +11,4 @@
},
"suffix": ".bs.js",
"bs-dependencies": []
-}
\ No newline at end of file
+}
diff --git a/examples/custom-server-reasonml/package.json b/examples/custom-server-reasonml/package.json
index df257b981ed80..46f956e38a777 100644
--- a/examples/custom-server-reasonml/package.json
+++ b/examples/custom-server-reasonml/package.json
@@ -23,4 +23,4 @@
"react": "^16.8.6",
"react-dom": "^16.8.6"
}
-}
\ No newline at end of file
+}
diff --git a/examples/custom-server-typescript/nodemon.json b/examples/custom-server-typescript/nodemon.json
index b78f3ea8b7468..f9c1534edff8b 100644
--- a/examples/custom-server-typescript/nodemon.json
+++ b/examples/custom-server-typescript/nodemon.json
@@ -2,4 +2,3 @@
"watch": ["server", "static"],
"exec": "ts-node --project tsconfig.server.json server/index.ts"
}
-
diff --git a/examples/custom-server-typescript/server/index.ts b/examples/custom-server-typescript/server/index.ts
index 43b8285307312..eac0e4f3491c5 100644
--- a/examples/custom-server-typescript/server/index.ts
+++ b/examples/custom-server-typescript/server/index.ts
@@ -7,8 +7,7 @@ const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
-app.prepare()
-.then(() => {
+app.prepare().then(() => {
createServer((req, res) => {
const parsedUrl = parse(req.url!, true)
const { pathname, query } = parsedUrl
@@ -20,9 +19,12 @@ app.prepare()
} else {
handle(req, res, parsedUrl)
}
- })
- .listen(port)
+ }).listen(port)
// tslint:disable-next-line:no-console
- console.log(`> Server listening at http://localhost:${port} as ${dev ? 'development' : process.env.NODE_ENV}`);
+ console.log(
+ `> Server listening at http://localhost:${port} as ${
+ dev ? 'development' : process.env.NODE_ENV
+ }`
+ )
})
diff --git a/examples/public-file-serving/now.json b/examples/public-file-serving/now.json
index 146cb2dea26b8..ca5c3456db8b0 100644
--- a/examples/public-file-serving/now.json
+++ b/examples/public-file-serving/now.json
@@ -3,10 +3,13 @@
"alias": "https://serverless-static-files.now.sh",
"builds": [{ "src": "next.config.js", "use": "@now/next" }],
"routes": [
- { "src": "/_next/static/(?:[^/]+/pages|chunks|runtime)/.+", "headers": { "cache-control": "immutable" } },
+ {
+ "src": "/_next/static/(?:[^/]+/pages|chunks|runtime)/.+",
+ "headers": { "cache-control": "immutable" }
+ },
{
"src": "^/(favicon.ico|manifest.json|humans.txt|sitemap.xml|sitemap.xsl)$",
"headers": { "cache-control": "max-age=300 must-revalidate" }
}
]
-}
\ No newline at end of file
+}
diff --git a/examples/ssr-caching/package.json b/examples/ssr-caching/package.json
index 730ea9b865c7b..92f27fc69aa5a 100644
--- a/examples/ssr-caching/package.json
+++ b/examples/ssr-caching/package.json
@@ -14,4 +14,4 @@
"react-dom": "^16.7.0"
},
"license": "ISC"
-}
\ No newline at end of file
+}
diff --git a/examples/with-apollo-and-redux-saga/README.md b/examples/with-apollo-and-redux-saga/README.md
index 6f6fc12bea354..100b6fdff16e9 100644
--- a/examples/with-apollo-and-redux-saga/README.md
+++ b/examples/with-apollo-and-redux-saga/README.md
@@ -45,15 +45,15 @@ Note that you can access the redux store like you normally would using `react-re
```js
const mapStateToProps = state => ({
- location: state.form.location
-});
+ location: state.form.location,
+})
export default withReduxSaga(
connect(
mapStateToProps,
null
)(Index)
-);
+)
```
`connect` must go inside `withReduxSaga` otherwise `connect` will not be able to find the store.
diff --git a/examples/with-apollo-and-redux/README.md b/examples/with-apollo-and-redux/README.md
index dcf281ec8b0d3..4cd3b377dea8d 100644
--- a/examples/with-apollo-and-redux/README.md
+++ b/examples/with-apollo-and-redux/README.md
@@ -47,15 +47,15 @@ Note that you can access the redux store like you normally would using `react-re
```js
const mapStateToProps = state => ({
- location: state.form.location
-});
+ location: state.form.location,
+})
export default withRedux(
connect(
mapStateToProps,
null
)(Index)
-);
+)
```
### Note:
diff --git a/examples/with-carlo/README.md b/examples/with-carlo/README.md
index 65a022b6fa52d..e5b5aa0008bc8 100644
--- a/examples/with-carlo/README.md
+++ b/examples/with-carlo/README.md
@@ -42,4 +42,4 @@ npm start
## The idea behind the example
-This example show how you can use Next.js with [Carlo](https://github.com/GoogleChromeLabs/carlo). Here we use a [Custom server](https://github.com/zeit/next.js/blob/canary/examples/custom-server/README.md) to fit the carlo configs.
\ No newline at end of file
+This example show how you can use Next.js with [Carlo](https://github.com/GoogleChromeLabs/carlo). Here we use a [Custom server](https://github.com/zeit/next.js/blob/canary/examples/custom-server/README.md) to fit the carlo configs.
diff --git a/examples/with-cerebral/README.md b/examples/with-cerebral/README.md
index c0eb631cc9d01..4c373f5a7c9a7 100644
--- a/examples/with-cerebral/README.md
+++ b/examples/with-cerebral/README.md
@@ -44,31 +44,31 @@ Use [CerebralJS](https://cerebraljs.com/) to manage an apps state and side effec
Declarative CerebralJS:
```js
-[
+;[
setLoading(true),
getUser,
{
success: setUser,
- error: setError
+ error: setError,
},
- setLoading(false)
-];
+ setLoading(false),
+]
```
vs imperative JS:
```js
function getUser() {
- this.isLoading = true;
+ this.isLoading = true
ajax
- .get("/user")
+ .get('/user')
.then(user => {
- this.data = user;
- this.isLoading = false;
+ this.data = user
+ this.isLoading = false
})
.catch(error => {
- this.error = error;
- this.isLoading = false;
- });
+ this.error = error
+ this.isLoading = false
+ })
}
```
diff --git a/examples/with-cloud9/README.md b/examples/with-cloud9/README.md
index b8da480690858..5f5521b4561a2 100644
--- a/examples/with-cloud9/README.md
+++ b/examples/with-cloud9/README.md
@@ -1,6 +1,6 @@
-# With Cloud 9 (c9.io) #
+# With Cloud 9 (c9.io)
-## Install NVM and set node to the latest version ##
+## Install NVM and set node to the latest version
Cloud 9 environment comes with a preinstalled nvm, but its better to use the latest
version - follow the install instructions from the [NVM GitHub page](https://github.com/creationix/nvm)
@@ -14,7 +14,7 @@ nvm alias default 10.12.0
nvm use node
```
-## Create a custom 'server.js' in the project root directory ##
+## Create a custom 'server.js' in the project root directory
// This file doesn't go through babel or webpack transformation.
// Make sure the syntax and sources this file requires are compatible with the current node version you are running
@@ -42,7 +42,7 @@ nvm use node
})
})
-## Change 'package.json' scripts to use that file ##
+## Change 'package.json' scripts to use that file
"scripts": {
"dev": "node server.js",
@@ -50,7 +50,7 @@ nvm use node
"start": "NODE_ENV=production node server.js"
}
-## Use dev preview within the Cloud9 VM IDE ##
+## Use dev preview within the Cloud9 VM IDE
After starting up the server (by using 'Run' button while having server.js open
in the IDE editor or by using "npm run dev" in terminal) you should be able to access web server by
diff --git a/examples/with-custom-reverse-proxy/README.md b/examples/with-custom-reverse-proxy/README.md
index deb32ebf48866..a520c4af9f455 100644
--- a/examples/with-custom-reverse-proxy/README.md
+++ b/examples/with-custom-reverse-proxy/README.md
@@ -35,8 +35,8 @@ yarn dev
This example applies this gist https://gist.github.com/jamsesso/67fd937b74989dc52e33 to Nextjs and provides:
-* Reverse proxy in development mode by add `http-proxy-middleware` to custom server
-* NOT a recommended approach to production scale (hence explicit dev flag) as we should scope proxy as outside UI applications and have separate web server taking care of that.
+- Reverse proxy in development mode by add `http-proxy-middleware` to custom server
+- NOT a recommended approach to production scale (hence explicit dev flag) as we should scope proxy as outside UI applications and have separate web server taking care of that.
Sorry for the extra packages. I belong to the minority camp of writing ES6 code on Windows developers. Essentially you only need `http-proxy-middleware` on top of bare-bone Nextjs setup to run this example.
diff --git a/examples/with-dynamic-app-layout/package.json b/examples/with-dynamic-app-layout/package.json
index 3c2ce7636daa2..c6cf97f83ed6a 100644
--- a/examples/with-dynamic-app-layout/package.json
+++ b/examples/with-dynamic-app-layout/package.json
@@ -1,18 +1,18 @@
{
- "name": "with-dynamic-app-layout",
- "version": "1.0.0",
- "description": "This example features:",
- "main": "index.js",
- "scripts": {
- "dev": "next",
- "build": "next build",
- "start": "next start"
- },
- "dependencies": {
- "next": "latest",
- "react": "^16.7.0",
- "react-dom": "^16.7.0"
- },
- "author": "",
- "license": "ISC"
+ "name": "with-dynamic-app-layout",
+ "version": "1.0.0",
+ "description": "This example features:",
+ "main": "index.js",
+ "scripts": {
+ "dev": "next",
+ "build": "next build",
+ "start": "next start"
+ },
+ "dependencies": {
+ "next": "latest",
+ "react": "^16.7.0",
+ "react-dom": "^16.7.0"
+ },
+ "author": "",
+ "license": "ISC"
}
diff --git a/examples/with-firebase-hosting-and-docker/README.md b/examples/with-firebase-hosting-and-docker/README.md
index 83d9051633316..50e2586310c9e 100644
--- a/examples/with-firebase-hosting-and-docker/README.md
+++ b/examples/with-firebase-hosting-and-docker/README.md
@@ -23,10 +23,10 @@ cd with-firebase-hosting-and-docker
Set up firebase:
-* create a project through the [firebase web console](https://console.firebase.google.com/)
-* grab the projects ID from the web consoles URL: https://console.firebase.google.com/project/
-* update the `.env` with your FB_PROJECTID and FIREBASE_TOKEN ( see .env.example )
-* ADD `serviceAccountKey.json` to your project root
+- create a project through the [firebase web console](https://console.firebase.google.com/)
+- grab the projects ID from the web consoles URL: https://console.firebase.google.com/project/
+- update the `.env` with your FB_PROJECTID and FIREBASE_TOKEN ( see .env.example )
+- ADD `serviceAccountKey.json` to your project root
### Dev next
@@ -58,6 +58,6 @@ If you're having issues, feel free to tag @sampsonjoliver in the [issue you crea
## Important
-* The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
-* `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
-* The [Firebase predeploy](https://firebase.google.com/docs/cli/#predeploy_and_postdeploy_hooks) hooks defined in `firebase.json` will handle linting and compiling of the next app and the functions sourceswhen `firebase deploy` is invoked. The only scripts you should need are `docker:dev`, `docker:serve` and `docker:deploy`.
+- The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
+- `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
+- The [Firebase predeploy](https://firebase.google.com/docs/cli/#predeploy_and_postdeploy_hooks) hooks defined in `firebase.json` will handle linting and compiling of the next app and the functions sourceswhen `firebase deploy` is invoked. The only scripts you should need are `docker:dev`, `docker:serve` and `docker:deploy`.
diff --git a/examples/with-firebase-hosting-and-typescript/README.md b/examples/with-firebase-hosting-and-typescript/README.md
index fc12fac6a914f..35a191813cb1b 100644
--- a/examples/with-firebase-hosting-and-typescript/README.md
+++ b/examples/with-firebase-hosting-and-typescript/README.md
@@ -23,11 +23,11 @@ cd with-firebase-hosting-and-typescript
Set up firebase:
-* install Firebase Tools: `npm i -g firebase-tools`
-* create a project through the [firebase web console](https://console.firebase.google.com/)
-* grab the projects ID from the web consoles URL: https://console.firebase.google.com/project/
-* update the `.firebaserc` default project ID to the newly created project
-* login to the Firebase CLI tool with `firebase login`
+- install Firebase Tools: `npm i -g firebase-tools`
+- create a project through the [firebase web console](https://console.firebase.google.com/)
+- grab the projects ID from the web consoles URL: https://console.firebase.google.com/project/
+- update the `.firebaserc` default project ID to the newly created project
+- login to the Firebase CLI tool with `firebase login`
#### Install project:
@@ -69,10 +69,10 @@ If you're having issues, feel free to tag @sampsonjoliver in the [issue you crea
## Important
-* The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
-* `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
-* The [Firebase predeploy](https://firebase.google.com/docs/cli/#predeploy_and_postdeploy_hooks) hooks defined in `firebase.json` will handle linting and compiling of the next app and the functions sourceswhen `firebase deploy` is invoked. The only scripts you should need are `dev`, `clean` and `deploy`.
-* Specifying [`"engines": {"node": "8"}`](package.json#L5-L7) in the `package.json` is required for firebase functions
+- The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
+- `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
+- The [Firebase predeploy](https://firebase.google.com/docs/cli/#predeploy_and_postdeploy_hooks) hooks defined in `firebase.json` will handle linting and compiling of the next app and the functions sourceswhen `firebase deploy` is invoked. The only scripts you should need are `dev`, `clean` and `deploy`.
+- Specifying [`"engines": {"node": "8"}`](package.json#L5-L7) in the `package.json` is required for firebase functions
to be deployed on Node 8 rather than Node 6
([Firebase Blog Announcement](https://firebase.googleblog.com/2018/08/cloud-functions-for-firebase-config-node-8-timeout-memory-region.html))
. This is matched in by specifying target as `es2017` in [`src/functions/tsconfig.json`](src/functions/tsconfig) so that typescript output somewhat compacter and moderner code.
diff --git a/examples/with-firebase-hosting-and-typescript/firebase.json b/examples/with-firebase-hosting-and-typescript/firebase.json
index f83054d29c49b..ca60567acef99 100644
--- a/examples/with-firebase-hosting-and-typescript/firebase.json
+++ b/examples/with-firebase-hosting-and-typescript/firebase.json
@@ -2,13 +2,13 @@
"functions": {
"source": "dist/functions",
"predeploy": [
- "npm run lint-functions",
- "npm run lint-app",
- "npm run typecheck-app",
- "npm run build-functions",
- "npm run build-app",
- "npm run copy-deps",
- "npm run install-deps"
+ "npm run lint-functions",
+ "npm run lint-app",
+ "npm run typecheck-app",
+ "npm run build-functions",
+ "npm run build-app",
+ "npm run copy-deps",
+ "npm run install-deps"
]
},
"hosting": {
diff --git a/examples/with-firebase-hosting-and-typescript/src/app/tsconfig.json b/examples/with-firebase-hosting-and-typescript/src/app/tsconfig.json
index 8c7b1dc33f471..3a4c85f9053e5 100644
--- a/examples/with-firebase-hosting-and-typescript/src/app/tsconfig.json
+++ b/examples/with-firebase-hosting-and-typescript/src/app/tsconfig.json
@@ -16,11 +16,7 @@
"skipLibCheck": true,
"sourceMap": true,
"noEmit": true,
- "lib": [
- "es6",
- "dom",
- "es2016"
- ],
- "baseUrl": ".",
+ "lib": ["es6", "dom", "es2016"],
+ "baseUrl": "."
}
}
diff --git a/examples/with-firebase-hosting-and-typescript/src/functions/index.ts b/examples/with-firebase-hosting-and-typescript/src/functions/index.ts
index 6ced035b11784..78eccc8c087d1 100644
--- a/examples/with-firebase-hosting-and-typescript/src/functions/index.ts
+++ b/examples/with-firebase-hosting-and-typescript/src/functions/index.ts
@@ -1,11 +1,11 @@
-import * as functions from 'firebase-functions';
-import * as next from 'next';
+import * as functions from 'firebase-functions'
+import * as next from 'next'
-const dev = process.env.NODE_ENV !== 'production';
-const app = next({ dev, conf: { distDir: 'next' } });
-const handle = app.getRequestHandler();
+const dev = process.env.NODE_ENV !== 'production'
+const app = next({ dev, conf: { distDir: 'next' } })
+const handle = app.getRequestHandler()
export const nextApp = functions.https.onRequest((req, res) => {
- console.log('File: ' + req.originalUrl);
- return app.prepare().then(() => handle(req, res));
-});
+ console.log('File: ' + req.originalUrl)
+ return app.prepare().then(() => handle(req, res))
+})
diff --git a/examples/with-firebase-hosting-and-typescript/src/functions/tslint.json b/examples/with-firebase-hosting-and-typescript/src/functions/tslint.json
index c952af3910c16..981bec2a761b4 100644
--- a/examples/with-firebase-hosting-and-typescript/src/functions/tslint.json
+++ b/examples/with-firebase-hosting-and-typescript/src/functions/tslint.json
@@ -74,27 +74,26 @@
// Disallow duplicate imports in the same file.
"no-duplicate-imports": true,
-
// -- Strong Warnings --
// These rules should almost never be needed, but may be included due to legacy code.
// They are left as a warning to avoid frustration with blocked deploys when the developer
// understand the warning and wants to deploy anyway.
// Warn when an empty interface is defined. These are generally not useful.
- "no-empty-interface": {"severity": "warning"},
+ "no-empty-interface": { "severity": "warning" },
// Warn when an import will have side effects.
- "no-import-side-effect": {"severity": "warning"},
+ "no-import-side-effect": { "severity": "warning" },
// Warn when variables are defined with var. Var has subtle meaning that can lead to bugs. Strongly prefer const for
// most values and let for values that will change.
- "no-var-keyword": {"severity": "warning"},
+ "no-var-keyword": { "severity": "warning" },
// Prefer === and !== over == and !=. The latter operators support overloads that are often accidental.
- "triple-equals": {"severity": "warning"},
+ "triple-equals": { "severity": "warning" },
// Warn when using deprecated APIs.
- "deprecation": {"severity": "warning"},
+ "deprecation": { "severity": "warning" },
// -- Light Warnigns --
// These rules are intended to help developers use better style. Simpler code has fewer bugs. These would be "info"
@@ -102,16 +101,16 @@
// prefer for( ... of ... ) to an index loop when the index is only used to fetch an object from an array.
// (Even better: check out utils like .map if transforming an array!)
- "prefer-for-of": {"severity": "warning"},
+ "prefer-for-of": { "severity": "warning" },
// Warns if function overloads could be unified into a single function with optional or rest parameters.
- "unified-signatures": {"severity": "warning"},
+ "unified-signatures": { "severity": "warning" },
// Prefer const for values that will not change. This better documents code.
- "prefer-const": {"severity": "warning"},
+ "prefer-const": { "severity": "warning" },
// Multi-line object liiterals and function calls should have a trailing comma. This helps avoid merge conflicts.
- "trailing-comma": {"severity": "warning"}
+ "trailing-comma": { "severity": "warning" }
},
"defaultSeverity": "error"
diff --git a/examples/with-firebase-hosting/README.md b/examples/with-firebase-hosting/README.md
index 7eb9c9f8a9418..13bb7feb5e442 100644
--- a/examples/with-firebase-hosting/README.md
+++ b/examples/with-firebase-hosting/README.md
@@ -27,11 +27,11 @@ cd with-firebase-hosting
Set up firebase
-* install Firebase Tools: `npm i -g firebase-tools`
-* create a project through the [firebase web console](https://console.firebase.google.com/)
-* grab the projects ID from the web consoles URL: `https://console.firebase.google.com/project/`
-* update the `.firebaserc` default project ID to the newly created project
-* login to the Firebase CLI tool with `firebase login`
+- install Firebase Tools: `npm i -g firebase-tools`
+- create a project through the [firebase web console](https://console.firebase.google.com/)
+- grab the projects ID from the web consoles URL: `https://console.firebase.google.com/project/`
+- update the `.firebaserc` default project ID to the newly created project
+- login to the Firebase CLI tool with `firebase login`
@@ -78,9 +78,9 @@ If you're having issues, feel free to tag @jthegedus in the [issue you create on
## Important
-* The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
-* `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
-* Specifying [`"engines": {"node": "8"}`](package.json#L5-L7) in the `package.json` is required for firebase functions
+- The empty `placeholder.html` file is so Firebase Hosting does not error on an empty `public/` folder and still hosts at the Firebase project URL.
+- `firebase.json` outlines the catchall rewrite rule for our Cloud Function.
+- Specifying [`"engines": {"node": "8"}`](package.json#L5-L7) in the `package.json` is required for firebase functions
to be deployed on Node 8 rather than Node 6
([Firebase Blog Announcement](https://firebase.googleblog.com/2018/08/cloud-functions-for-firebase-config-node-8-timeout-memory-region.html))
. This is matched in [`src/functions/.babelrc`](src/functions/.babelrc) so that babel output somewhat compacter and moderner code.
@@ -89,14 +89,14 @@ If you're having issues, feel free to tag @jthegedus in the [issue you create on
Next App and Next Server development are separated into two different folders:
-* app - `src/app/`
-* server - `src/functions/`
+- app - `src/app/`
+- server - `src/functions/`
If you wish to modify any configuration of the Next App, you should only modify the contents of `src/app`.
For instance, the `.babelrc` in `src/functions` is used only to compile the Firebase Cloud Functions code, which is our the Next Server code. If you wish to customize the `.babelrc` for the Next App compilation, then you should create one at `src/app/.babelrc` and follow the [customization guide](https://github.com/zeit/next.js#customizing-babel-config).
-### _app.js
+### \_app.js
If using `_app.js` you may receive the following error on your deployed Cloud Function:
@@ -104,4 +104,4 @@ If using `_app.js` you may receive the following error on your deployed Cloud Fu
{ Error: Cannot find module '@babel/runtime/regenerator'...
```
-Despite next.js having `@babel/runtime` as a dependency, you must install it as a dependency directly in this project.
\ No newline at end of file
+Despite next.js having `@babel/runtime` as a dependency, you must install it as a dependency directly in this project.
diff --git a/examples/with-jest-flow/README.md b/examples/with-jest-flow/README.md
index b770f78807313..f1387a0d0f53b 100644
--- a/examples/with-jest-flow/README.md
+++ b/examples/with-jest-flow/README.md
@@ -43,5 +43,5 @@ yarn test
This example features:
-* An app with jest tests
-* The [Flow](https://flowtype.org/) static type checker, with the transform-flow-strip-types babel plugin stripping flow type annotations from your output code.
+- An app with jest tests
+- The [Flow](https://flowtype.org/) static type checker, with the transform-flow-strip-types babel plugin stripping flow type annotations from your output code.
diff --git a/examples/with-jest-typescript/README.md b/examples/with-jest-typescript/README.md
index 8050fedc905f3..b308b367f2c51 100644
--- a/examples/with-jest-typescript/README.md
+++ b/examples/with-jest-typescript/README.md
@@ -41,4 +41,4 @@ yarn test
## The idea behind the example
-This example shows a configuration and several examples for a running Jest tests in a NextJS TypeScript app
\ No newline at end of file
+This example shows a configuration and several examples for a running Jest tests in a NextJS TypeScript app
diff --git a/examples/with-jest-typescript/src/modules/auth/types.ts b/examples/with-jest-typescript/src/modules/auth/types.ts
index c234113c8aec3..36dc07076a31f 100644
--- a/examples/with-jest-typescript/src/modules/auth/types.ts
+++ b/examples/with-jest-typescript/src/modules/auth/types.ts
@@ -1,4 +1,4 @@
export interface LoginCredentials {
- email: string;
- password: string;
-}
\ No newline at end of file
+ email: string
+ password: string
+}
diff --git a/examples/with-jest-typescript/src/modules/cars/types.ts b/examples/with-jest-typescript/src/modules/cars/types.ts
index e0f20427edbd2..5a1ee5acad47e 100644
--- a/examples/with-jest-typescript/src/modules/cars/types.ts
+++ b/examples/with-jest-typescript/src/modules/cars/types.ts
@@ -1,10 +1,10 @@
export interface Car {
- make : string;
- model : string;
- engine : string;
- year : number;
- mileage : number;
- equipment : string[];
+ make: string
+ model: string
+ engine: string
+ year: number
+ mileage: number
+ equipment: string[]
}
-export type CarList = Array < Car >;
\ No newline at end of file
+export type CarList = Array
diff --git a/examples/with-jest-typescript/tsconfig.json b/examples/with-jest-typescript/tsconfig.json
index ace24fb16c70d..62bc21628bc35 100644
--- a/examples/with-jest-typescript/tsconfig.json
+++ b/examples/with-jest-typescript/tsconfig.json
@@ -1,33 +1,27 @@
{
- "compileOnSave": false,
- "compilerOptions": {
- "target": "esnext",
- "module": "esnext",
- "jsx": "preserve",
- "allowJs": true,
- "moduleResolution": "node",
- "allowSyntheticDefaultImports": true,
- "noUnusedLocals": true,
- "noUnusedParameters": true,
- "removeComments": false,
- "preserveConstEnums": true,
- "sourceMap": true,
- "skipLibCheck": true,
- "baseUrl": ".",
- "typeRoots": [
- "./node_modules/@types"
- ],
- "lib": [
- "dom",
- "es2015",
- "es2016"
- ]
- },
- "exclude": [
- "node_modules",
- "**/*.spec.ts",
- "**/*.spec.tsx",
- "**/*.test.ts",
- "**/*.test.tsx",
- ]
-}
\ No newline at end of file
+ "compileOnSave": false,
+ "compilerOptions": {
+ "target": "esnext",
+ "module": "esnext",
+ "jsx": "preserve",
+ "allowJs": true,
+ "moduleResolution": "node",
+ "allowSyntheticDefaultImports": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "removeComments": false,
+ "preserveConstEnums": true,
+ "sourceMap": true,
+ "skipLibCheck": true,
+ "baseUrl": ".",
+ "typeRoots": ["./node_modules/@types"],
+ "lib": ["dom", "es2015", "es2016"]
+ },
+ "exclude": [
+ "node_modules",
+ "**/*.spec.ts",
+ "**/*.spec.tsx",
+ "**/*.test.ts",
+ "**/*.test.tsx"
+ ]
+}
diff --git a/examples/with-lingui/components/withLang.js b/examples/with-lingui/components/withLang.js
index 5cd77fd5adfe9..06cc73f5e0a02 100644
--- a/examples/with-lingui/components/withLang.js
+++ b/examples/with-lingui/components/withLang.js
@@ -23,10 +23,7 @@ export default (Component, defaultLang = 'en') =>
const { language, catalogs, ...restProps } = this.props
return (
-
+
)
diff --git a/examples/with-lingui/package.json b/examples/with-lingui/package.json
index 91bfa9aa227bb..c1e6addba6947 100644
--- a/examples/with-lingui/package.json
+++ b/examples/with-lingui/package.json
@@ -30,4 +30,4 @@
"format": "po"
},
"license": "ISC"
-}
\ No newline at end of file
+}
diff --git a/examples/with-mobx-react-lite/README.md b/examples/with-mobx-react-lite/README.md
index 48a421e1f7760..fb4a36f3b4b81 100644
--- a/examples/with-mobx-react-lite/README.md
+++ b/examples/with-mobx-react-lite/README.md
@@ -59,40 +59,40 @@ The initial store data is returned from the `initializeData` function that recyc
```jsx
function initializeData(initialData = store || {}) {
- const { lastUpdate = Date.now(), light } = initialData;
+ const { lastUpdate = Date.now(), light } = initialData
return {
lastUpdate,
- light: Boolean(light)
- };
+ light: Boolean(light),
+ }
}
```
The observable store is created in a function component by passing a plain JavaScript object to the `useObservable` hook. Actions on the observable store (`start` and `stop`) are created in the same scope as the `store` in `store.js` and exported as named exports.
```js
-store = useObservable(initializeData(props.initialData));
+store = useObservable(initializeData(props.initialData))
start = useCallback(
action(() => {
// Async operation that mutates the store
})
-);
+)
stop = () => {
// Does not mutate the store
-};
+}
```
The component creates and exports a new React context provider that will make the store accessible to all of its descendents.
```jsx
-return {children};
+return {children}
```
The store is accessible at any depth by using the `StoreContext`.
```js
-const store = useContext(StoreContext);
+const store = useContext(StoreContext)
```
The clock, under `components/Clock.js`, reacts to changes in the observable `store` by means of the `useObserver` hook.
@@ -106,5 +106,5 @@ return (
))}
// ...
-);
+)
```
diff --git a/examples/with-mobx-state-tree-typescript/stores/store.ts b/examples/with-mobx-state-tree-typescript/stores/store.ts
index 52d37cc80acba..1f1dc1f79f0d1 100644
--- a/examples/with-mobx-state-tree-typescript/stores/store.ts
+++ b/examples/with-mobx-state-tree-typescript/stores/store.ts
@@ -1,6 +1,12 @@
-import { applySnapshot, Instance, SnapshotIn, SnapshotOut, types } from "mobx-state-tree";
+import {
+ applySnapshot,
+ Instance,
+ SnapshotIn,
+ SnapshotOut,
+ types,
+} from 'mobx-state-tree'
-let store: IStore = null as any;
+let store: IStore = null as any
const Store = types
.model({
@@ -8,40 +14,40 @@ const Store = types
lastUpdate: types.Date,
light: false,
})
- .actions((self) => {
- let timer;
+ .actions(self => {
+ let timer
const start = () => {
timer = setInterval(() => {
// mobx-state-tree doesn't allow anonymous callbacks changing data.
// Pass off to another action instead (need to cast self as any
// because typescript doesn't yet know about the actions we're
// adding to self here)
- (self as any).update();
- }, 1000);
- };
+ ;(self as any).update()
+ }, 1000)
+ }
const update = () => {
- self.lastUpdate = new Date(Date.now());
- self.light = true;
- };
+ self.lastUpdate = new Date(Date.now())
+ self.light = true
+ }
const stop = () => {
- clearInterval(timer);
- };
- return { start, stop, update };
- });
+ clearInterval(timer)
+ }
+ return { start, stop, update }
+ })
-export type IStore = Instance;
-export type IStoreSnapshotIn = SnapshotIn;
-export type IStoreSnapshotOut = SnapshotOut;
+export type IStore = Instance
+export type IStoreSnapshotIn = SnapshotIn
+export type IStoreSnapshotOut = SnapshotOut
export const initializeStore = (isServer, snapshot = null) => {
if (isServer) {
- store = Store.create({ foo: 6, lastUpdate: Date.now() });
+ store = Store.create({ foo: 6, lastUpdate: Date.now() })
}
- if (store as any === null) {
- store = Store.create({ foo: 6, lastUpdate: Date.now() });
+ if ((store as any) === null) {
+ store = Store.create({ foo: 6, lastUpdate: Date.now() })
}
if (snapshot) {
- applySnapshot(store, snapshot);
+ applySnapshot(store, snapshot)
}
- return store;
-};
+ return store
+}
diff --git a/examples/with-mobx-state-tree-typescript/tsconfig.json b/examples/with-mobx-state-tree-typescript/tsconfig.json
index 6d284303d217c..57ec3cda5e5ee 100644
--- a/examples/with-mobx-state-tree-typescript/tsconfig.json
+++ b/examples/with-mobx-state-tree-typescript/tsconfig.json
@@ -17,13 +17,7 @@
"sourceMap": true,
"skipLibCheck": true,
"baseUrl": ".",
- "typeRoots": [
- "./node_modules/@types"
- ],
- "lib": [
- "dom",
- "es2015",
- "es2016"
- ]
+ "typeRoots": ["./node_modules/@types"],
+ "lib": ["dom", "es2015", "es2016"]
}
}
diff --git a/examples/with-mobx-state-tree-typescript/tslint.json b/examples/with-mobx-state-tree-typescript/tslint.json
index 0dc58e4c865c5..f2d7a99d260b4 100644
--- a/examples/with-mobx-state-tree-typescript/tslint.json
+++ b/examples/with-mobx-state-tree-typescript/tslint.json
@@ -1,9 +1,5 @@
{
- "extends": [
- "tslint-config-standard",
- "tslint:latest",
- "tslint-react"
- ],
+ "extends": ["tslint-config-standard", "tslint:latest", "tslint-react"],
"rules": {
"indent": [true, "spaces"],
"jsx-no-lambda": false,
@@ -11,10 +7,7 @@
"max-line-length": false,
"no-console": false,
"no-object-literal-type-assertion": false,
- "no-submodule-imports": [
- true,
- "next"
- ],
+ "no-submodule-imports": [true, "next"],
"no-unused-variable": false,
"space-before-function-paren": false,
"ter-indent": [true, 2],
diff --git a/examples/with-react-intl/lang/en.json b/examples/with-react-intl/lang/en.json
index d8df06b128825..d6de3be22bb5e 100644
--- a/examples/with-react-intl/lang/en.json
+++ b/examples/with-react-intl/lang/en.json
@@ -4,4 +4,4 @@
"nav.about": "About",
"description": "An example app integrating React Intl with Next.js",
"greeting": "Hello, World!"
-}
\ No newline at end of file
+}
diff --git a/examples/with-react-multi-carousel/README.md b/examples/with-react-multi-carousel/README.md
index e4cfdfe081ba5..c452c004126ec 100644
--- a/examples/with-react-multi-carousel/README.md
+++ b/examples/with-react-multi-carousel/README.md
@@ -4,7 +4,6 @@ Source code is hosted on the [react-multi-carorusel](https://github.com/YIZHUANG
[![Demo](https://react-multi-carousel.now.sh/)
-
### Usage
Install and run:
@@ -22,7 +21,7 @@ The reason for that is i needed to implement a Carousel component for my own pro
## How does it work with ssr?
-* On the server-side, we detect the user's device to decide how many items we are showing and then using flex-basis to assign * width to the carousel item.
-* On the client-side, old fashion getting width of the container and assign the average of it to each carousel item.
+- On the server-side, we detect the user's device to decide how many items we are showing and then using flex-basis to assign \* width to the carousel item.
+- On the client-side, old fashion getting width of the container and assign the average of it to each carousel item.
The UI part of this example is copy paste from for the sake of simplicity. [with-material-ui](https://github.com/zeit/next.js/tree/canary/examples/with-material-ui)
diff --git a/examples/with-react-multi-carousel/now.json b/examples/with-react-multi-carousel/now.json
index 9d78481eaada9..7769cc4945df1 100644
--- a/examples/with-react-multi-carousel/now.json
+++ b/examples/with-react-multi-carousel/now.json
@@ -1,7 +1,5 @@
{
- "version": 2,
- "name": "nextjs",
- "builds": [
- { "src": "package.json", "use": "@now/next" }
- ]
+ "version": 2,
+ "name": "nextjs",
+ "builds": [{ "src": "package.json", "use": "@now/next" }]
}
diff --git a/examples/with-reasonml-todo/README.md b/examples/with-reasonml-todo/README.md
index 86cb6d1ee43c4..e1fe39d0a6d73 100644
--- a/examples/with-reasonml-todo/README.md
+++ b/examples/with-reasonml-todo/README.md
@@ -1,6 +1,6 @@
# Example app using ReasonML & ReasonReact components
-This example builds upon the original `with-reasonml` example to sho how a
+This example builds upon the original `with-reasonml` example to sho how a
global state object can be used to track state across page within the application.
It is intended to show how to build a simple, stateful application using hooks
diff --git a/examples/with-redux-observable/README.md b/examples/with-redux-observable/README.md
index c524654c84c1c..a8251c735f927 100644
--- a/examples/with-redux-observable/README.md
+++ b/examples/with-redux-observable/README.md
@@ -31,7 +31,6 @@ yarn
yarn dev
```
-
### The idea behind the example
This example is a page that renders information about Star-Wars characters. It
diff --git a/examples/with-redux-saga/README.md b/examples/with-redux-saga/README.md
index 2213f9a0cc7ed..ca03c564c4004 100644
--- a/examples/with-redux-saga/README.md
+++ b/examples/with-redux-saga/README.md
@@ -68,12 +68,12 @@ The digital clock is updated every second using the `runClockSaga` found in `sag
All pages are also being wrapped by `next-redux-saga` using a helper function from `store.js`:
```js
-import withRedux from "next-redux-wrapper";
-import nextReduxSaga from "next-redux-saga";
-import configureStore from "./store";
+import withRedux from 'next-redux-wrapper'
+import nextReduxSaga from 'next-redux-saga'
+import configureStore from './store'
export function withReduxSaga(BaseComponent) {
- return withRedux(configureStore)(nextReduxSaga(BaseComponent));
+ return withRedux(configureStore)(nextReduxSaga(BaseComponent))
}
/**
@@ -90,13 +90,13 @@ export function withReduxSaga(BaseComponent) {
If you need to pass `react-redux` connect args to your page, you could use the following helper instead:
```js
-import withRedux from "next-redux-wrapper";
-import nextReduxSaga from "next-redux-saga";
-import configureStore from "./store";
+import withRedux from 'next-redux-wrapper'
+import nextReduxSaga from 'next-redux-saga'
+import configureStore from './store'
export function withReduxSaga(...connectArgs) {
return BaseComponent =>
- withRedux(configureStore, ...connectArgs)(nextReduxSaga(BaseComponent));
+ withRedux(configureStore, ...connectArgs)(nextReduxSaga(BaseComponent))
}
/**
diff --git a/examples/with-redux/package.json b/examples/with-redux/package.json
index 681921ca6e52e..93cf5165d4076 100644
--- a/examples/with-redux/package.json
+++ b/examples/with-redux/package.json
@@ -1,18 +1,18 @@
{
- "name": "with-redux",
- "version": "1.0.0",
- "scripts": {
- "dev": "next",
- "build": "next build",
- "start": "next start"
- },
- "dependencies": {
- "next": "latest",
- "react": "^16.7.0",
- "redux-devtools-extension": "^2.13.2",
- "react-dom": "^16.7.0",
- "react-redux": "^5.0.1",
- "redux": "^3.6.0"
- },
- "license": "ISC"
- }
\ No newline at end of file
+ "name": "with-redux",
+ "version": "1.0.0",
+ "scripts": {
+ "dev": "next",
+ "build": "next build",
+ "start": "next start"
+ },
+ "dependencies": {
+ "next": "latest",
+ "react": "^16.7.0",
+ "redux-devtools-extension": "^2.13.2",
+ "react-dom": "^16.7.0",
+ "react-redux": "^5.0.1",
+ "redux": "^3.6.0"
+ },
+ "license": "ISC"
+}
diff --git a/examples/with-sentry-simple/README.md b/examples/with-sentry-simple/README.md
index e9b3a4d6d1700..93418892fd2e2 100644
--- a/examples/with-sentry-simple/README.md
+++ b/examples/with-sentry-simple/README.md
@@ -63,8 +63,8 @@ The Sentry DSN should then be updated in `_app.js`.
```js
Sentry.init({
- dsn: 'PUT_YOUR_SENTRY_DSN_HERE'
-});
+ dsn: 'PUT_YOUR_SENTRY_DSN_HERE',
+})
```
_Note: Committing environment variables is not secure and is done here only for demonstration purposes. See the [`with-dotenv`](../with-dotenv) or [`with-now-env`](../with-now-env) for examples of how to set environment variables safely._
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/README.md b/examples/with-sitemap-and-robots-express-server-typescript/README.md
index dab0648fe1ec0..2b98ca1114e76 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/README.md
+++ b/examples/with-sitemap-and-robots-express-server-typescript/README.md
@@ -56,6 +56,7 @@ When you start this example locally:
- robots.txt will be located at http://localhost:8000/robots.txt
In case you want to deploy this example, replace the URL in the following locations with your own domain:
+
- `hostname` in `src/server/sitemap.ts`
- `ROOT_URL` in `src/server/app.ts`
- `Sitemap` at the bottom of `src/server/robots.txt`
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/now.json b/examples/with-sitemap-and-robots-express-server-typescript/now.json
index 42b80ae7ba576..bb166af656ce8 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/now.json
+++ b/examples/with-sitemap-and-robots-express-server-typescript/now.json
@@ -1,6 +1,6 @@
{
"env": {
- "NODE_ENV": "production"
+ "NODE_ENV": "production"
},
"scale": {
"sfo1": {
@@ -9,4 +9,4 @@
}
},
"alias": "https://sitemap-robots-typescript.now.sh"
-}
\ No newline at end of file
+}
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/src/server/app.ts b/examples/with-sitemap-and-robots-express-server-typescript/src/server/app.ts
index d2f9ce03fd2e8..360d4eba41369 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/src/server/app.ts
+++ b/examples/with-sitemap-and-robots-express-server-typescript/src/server/app.ts
@@ -1,29 +1,31 @@
-import * as express from "express";
-import * as next from "next";
-import { addSitemap } from "./sitemap";
+import * as express from 'express'
+import * as next from 'next'
+import { addSitemap } from './sitemap'
-const dev = process.env.NODE_ENV !== "production";
-const port = process.env.PORT || 8000;
+const dev = process.env.NODE_ENV !== 'production'
+const port = process.env.PORT || 8000
const ROOT_URL = dev
? `http://localhost:${port}`
- : "https://sitemap-robots-typescript.now.sh";
+ : 'https://sitemap-robots-typescript.now.sh'
-const app = next({ dev });
-const handle = app.getRequestHandler();
+const app = next({ dev })
+const handle = app.getRequestHandler()
// Nextjs's server prepared
app.prepare().then(() => {
- const server = express();
+ const server = express()
- addSitemap({ server });
+ addSitemap({ server })
- server.get("*", (req, res) => { handle(req, res); });
+ server.get('*', (req, res) => {
+ handle(req, res)
+ })
// starting express server
- server.listen(port, (err) => {
+ server.listen(port, err => {
if (err) {
- throw err;
+ throw err
}
- console.log(`> Ready on ${ROOT_URL}`);
- });
-});
+ console.log(`> Ready on ${ROOT_URL}`)
+ })
+})
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/src/server/posts.ts b/examples/with-sitemap-and-robots-express-server-typescript/src/server/posts.ts
index 1fc4469c13d47..0623b3b750d8e 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/src/server/posts.ts
+++ b/examples/with-sitemap-and-robots-express-server-typescript/src/server/posts.ts
@@ -1,16 +1,16 @@
interface IPost {
- name:string;
- slug:string;
+ name: string
+ slug: string
}
const posts = () => {
- const arrayOfPosts:IPost[] = [];
- const n = 5;
+ const arrayOfPosts: IPost[] = []
+ const n = 5
for (let i = 1; i < n + 1; i += 1) {
- arrayOfPosts.push({ name: `Post ${i}`, slug: `post-${i}` });
+ arrayOfPosts.push({ name: `Post ${i}`, slug: `post-${i}` })
}
- return arrayOfPosts;
-};
+ return arrayOfPosts
+}
-export { IPost, posts };
+export { IPost, posts }
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/src/server/sitemap.ts b/examples/with-sitemap-and-robots-express-server-typescript/src/server/sitemap.ts
index 32f481536765d..229c1c7bca862 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/src/server/sitemap.ts
+++ b/examples/with-sitemap-and-robots-express-server-typescript/src/server/sitemap.ts
@@ -1,45 +1,45 @@
-import * as path from "path";
-import * as sm from "sitemap";
-import { posts } from "./posts";
+import * as path from 'path'
+import * as sm from 'sitemap'
+import { posts } from './posts'
const sitemap = sm.createSitemap({
cacheTime: 600000, // 600 sec - cache purge period
- hostname: "https://sitemap-robots-typescript.now.sh",
-});
+ hostname: 'https://sitemap-robots-typescript.now.sh',
+})
const addSitemap = ({ server }) => {
- const Posts = posts();
+ const Posts = posts()
for (const post of Posts) {
sitemap.add({
- changefreq: "daily",
+ changefreq: 'daily',
priority: 0.9,
url: `/posts/${post.slug}`,
- });
+ })
}
sitemap.add({
- changefreq: "daily",
+ changefreq: 'daily',
priority: 1,
- url: "/a",
- });
+ url: '/a',
+ })
sitemap.add({
- changefreq: "daily",
+ changefreq: 'daily',
priority: 1,
- url: "/b",
- });
+ url: '/b',
+ })
// Note {} in next line is a placeholder filling the spot where the req parameter
// would normally be listed (but isn't listed here since we aren't using it)
- server.get("/sitemap.xml", ({}, res) => {
+ server.get('/sitemap.xml', ({}, res) => {
sitemap.toXML((err, xml) => {
if (err) {
- res.status(500).end();
- return;
+ res.status(500).end()
+ return
}
- res.header("Content-Type", "application/xml");
- res.send(xml);
- });
- });
-};
+ res.header('Content-Type', 'application/xml')
+ res.send(xml)
+ })
+ })
+}
-export { addSitemap };
+export { addSitemap }
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.express.json b/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.express.json
index da376a498f3af..4efa10c193df5 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.express.json
+++ b/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.express.json
@@ -17,15 +17,9 @@
"preserveConstEnums": true,
"sourceMap": true,
"skipLibCheck": true,
- "typeRoots": [
- "./node_modules/@types"
- ],
+ "typeRoots": ["./node_modules/@types"],
"outDir": "./dist/server",
- "lib": [
- "dom",
- "es2015",
- "es2016"
- ]
+ "lib": ["dom", "es2015", "es2016"]
},
"include": ["./src/server/**/*"]
}
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.next.json b/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.next.json
index 9e56e62ac7f61..853628a6f5e20 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.next.json
+++ b/examples/with-sitemap-and-robots-express-server-typescript/tsconfig.next.json
@@ -17,15 +17,9 @@
"preserveConstEnums": true,
"sourceMap": true,
"skipLibCheck": true,
- "typeRoots": [
- "./node_modules/@types"
- ],
+ "typeRoots": ["./node_modules/@types"],
"outDir": "./dist",
- "lib": [
- "dom",
- "es2015",
- "es2016"
- ]
+ "lib": ["dom", "es2015", "es2016"]
},
"include": ["./src/**/*"],
"exclude": ["./src/server/**/*"]
diff --git a/examples/with-sitemap-and-robots-express-server-typescript/tslint.json b/examples/with-sitemap-and-robots-express-server-typescript/tslint.json
index 0dc58e4c865c5..f2d7a99d260b4 100644
--- a/examples/with-sitemap-and-robots-express-server-typescript/tslint.json
+++ b/examples/with-sitemap-and-robots-express-server-typescript/tslint.json
@@ -1,9 +1,5 @@
{
- "extends": [
- "tslint-config-standard",
- "tslint:latest",
- "tslint-react"
- ],
+ "extends": ["tslint-config-standard", "tslint:latest", "tslint-react"],
"rules": {
"indent": [true, "spaces"],
"jsx-no-lambda": false,
@@ -11,10 +7,7 @@
"max-line-length": false,
"no-console": false,
"no-object-literal-type-assertion": false,
- "no-submodule-imports": [
- true,
- "next"
- ],
+ "no-submodule-imports": [true, "next"],
"no-unused-variable": false,
"space-before-function-paren": false,
"ter-indent": [true, 2],
diff --git a/examples/with-sitemap-and-robots-express-server/README.md b/examples/with-sitemap-and-robots-express-server/README.md
index 00e6d6354c3b6..fbff3700bb8fe 100644
--- a/examples/with-sitemap-and-robots-express-server/README.md
+++ b/examples/with-sitemap-and-robots-express-server/README.md
@@ -57,6 +57,7 @@ When you start this example locally:
- robots.txt will be located at http://localhost:8000/robots.txt
In case you want to deploy this example, replace the URL in the following locations with your own domain:
+
- `hostname` in `server/sitemap.js`
- `ROOT_URL` in `server/app.js`
- `Sitemap` at the bottom of `robots.txt`
diff --git a/examples/with-sitemap-and-robots-express-server/now.json b/examples/with-sitemap-and-robots-express-server/now.json
index 02ed5e70b6526..aa36e4bab8345 100644
--- a/examples/with-sitemap-and-robots-express-server/now.json
+++ b/examples/with-sitemap-and-robots-express-server/now.json
@@ -1,6 +1,6 @@
{
"env": {
- "NODE_ENV": "production"
+ "NODE_ENV": "production"
},
"scale": {
"sfo1": {
@@ -9,4 +9,4 @@
}
},
"alias": "https://sitemap-robots.now.sh"
-}
\ No newline at end of file
+}
diff --git a/examples/with-ts-node/server/index.ts b/examples/with-ts-node/server/index.ts
index 6d15fa39f36cf..1497de98c8106 100644
--- a/examples/with-ts-node/server/index.ts
+++ b/examples/with-ts-node/server/index.ts
@@ -2,15 +2,15 @@ import { createServer } from 'http'
import { parse } from 'url'
import * as next from 'next'
-const port = parseInt(process.env.PORT, 10) || 3000;
-const dev = process.env.NODE_ENV !== 'production';
-const app = next({ dev });
-const handle = app.getRequestHandler();
+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(() => {
createServer((req, res) => {
- const parsedUrl = parse(req.url, true);
- const { pathname, query } = parsedUrl;
+ const parsedUrl = parse(req.url, true)
+ const { pathname, query } = parsedUrl
if (pathname === '/a') {
app.render(req, res, '/a', query)
@@ -19,9 +19,8 @@ app.prepare().then(() => {
} else {
handle(req, res, parsedUrl)
}
- })
- .listen(port, (err) => {
+ }).listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
-});
+})
diff --git a/examples/with-ts-node/tsconfig.json b/examples/with-ts-node/tsconfig.json
index 87a7898ab8014..ec2e8f75e0542 100644
--- a/examples/with-ts-node/tsconfig.json
+++ b/examples/with-ts-node/tsconfig.json
@@ -15,13 +15,7 @@
"skipLibCheck": true,
"rootDir": ".",
"baseUrl": ".",
- "typeRoots": [
- "./node_modules/@types"
- ],
- "lib": [
- "dom",
- "es2015",
- "es2016"
- ]
+ "typeRoots": ["./node_modules/@types"],
+ "lib": ["dom", "es2015", "es2016"]
}
}
diff --git a/examples/with-typescript-styled-components/tsconfig.json b/examples/with-typescript-styled-components/tsconfig.json
index 9bccadf45eeef..a5a071f65e061 100644
--- a/examples/with-typescript-styled-components/tsconfig.json
+++ b/examples/with-typescript-styled-components/tsconfig.json
@@ -15,6 +15,6 @@
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": true,
- "esModuleInterop": true,
+ "esModuleInterop": true
}
}
diff --git a/examples/with-typescript/interfaces/index.ts b/examples/with-typescript/interfaces/index.ts
index 6f5f6e663af59..bd2fc1ec4c80a 100644
--- a/examples/with-typescript/interfaces/index.ts
+++ b/examples/with-typescript/interfaces/index.ts
@@ -5,6 +5,6 @@
// import User from 'path/to/interfaces';
export type User = {
- id: number,
- name: string,
+ id: number
+ name: string
}
diff --git a/examples/with-typescript/tsconfig.json b/examples/with-typescript/tsconfig.json
index 382a0ac315510..c65399cb28e5d 100644
--- a/examples/with-typescript/tsconfig.json
+++ b/examples/with-typescript/tsconfig.json
@@ -6,10 +6,7 @@
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"jsx": "preserve",
- "lib": [
- "dom",
- "es2017"
- ],
+ "lib": ["dom", "es2017"],
"module": "esnext",
"moduleResolution": "node",
"noEmit": true,
@@ -21,11 +18,6 @@
"strict": true,
"target": "esnext"
},
- "exclude": [
- "node_modules"
- ],
- "include": [
- "**/*.ts",
- "**/*.tsx"
- ]
+ "exclude": ["node_modules"],
+ "include": ["**/*.ts", "**/*.tsx"]
}
diff --git a/examples/with-typescript/utils/sample-api.ts b/examples/with-typescript/utils/sample-api.ts
index 07ae8754062a9..a326dfa976fa2 100644
--- a/examples/with-typescript/utils/sample-api.ts
+++ b/examples/with-typescript/utils/sample-api.ts
@@ -1,4 +1,4 @@
-import { User } from "../interfaces";
+import { User } from '../interfaces'
/** Dummy user data. */
export const dataArray: User[] = [
@@ -6,7 +6,7 @@ export const dataArray: User[] = [
{ id: 102, name: 'Bob' },
{ id: 103, name: 'Caroline' },
{ id: 104, name: 'Dave' },
-];
+]
/**
* Calls a mock API which finds a user by ID from the list above.
@@ -14,7 +14,7 @@ export const dataArray: User[] = [
* Throws an error if not found.
*/
export async function findData(id: number | string) {
- const selected = dataArray.find((data) => data.id === Number(id))
+ const selected = dataArray.find(data => data.id === Number(id))
if (!selected) {
throw new Error('Cannot find user')
diff --git a/examples/with-typings-for-css-modules/style.css.d.ts b/examples/with-typings-for-css-modules/style.css.d.ts
index 36996950a1ddb..eeebb52704b08 100644
--- a/examples/with-typings-for-css-modules/style.css.d.ts
+++ b/examples/with-typings-for-css-modules/style.css.d.ts
@@ -1,3 +1,3 @@
-export const example: string;
-export const example__description: string;
-export const exampleDescription: string;
+export const example: string
+export const example__description: string
+export const exampleDescription: string
diff --git a/examples/with-typings-for-css-modules/tsconfig.json b/examples/with-typings-for-css-modules/tsconfig.json
index 06b51be310ede..b358694983ed7 100644
--- a/examples/with-typings-for-css-modules/tsconfig.json
+++ b/examples/with-typings-for-css-modules/tsconfig.json
@@ -15,4 +15,4 @@
"preserveConstEnums": true,
"sourceMap": true
}
-}
\ No newline at end of file
+}
diff --git a/examples/with-yarn-workspaces/package.json b/examples/with-yarn-workspaces/package.json
index 99be3b76589a8..60a794a3f006d 100644
--- a/examples/with-yarn-workspaces/package.json
+++ b/examples/with-yarn-workspaces/package.json
@@ -1,6 +1,8 @@
{
"private": true,
- "workspaces": ["packages/*"],
+ "workspaces": [
+ "packages/*"
+ ],
"scripts": {
"dev": "yarn --cwd packages/web-app dev",
"build": "yarn --cwd packages/web-app build",
diff --git a/examples/with-zones/blog/now.json b/examples/with-zones/blog/now.json
index cd0f93b816af2..79c8f30c9086f 100644
--- a/examples/with-zones/blog/now.json
+++ b/examples/with-zones/blog/now.json
@@ -1,13 +1,11 @@
{
- "version": 2,
- "name": "with-zones-blog",
- "alias": "with-zones-blog.nextjs.org",
- "build": {
- "env": {
- "DEPLOY": "true"
- }
- },
- "builds": [
- { "src": "package.json", "use": "@now/next" }
- ]
-}
\ No newline at end of file
+ "version": 2,
+ "name": "with-zones-blog",
+ "alias": "with-zones-blog.nextjs.org",
+ "build": {
+ "env": {
+ "DEPLOY": "true"
+ }
+ },
+ "builds": [{ "src": "package.json", "use": "@now/next" }]
+}
diff --git a/examples/with-zones/home/now.json b/examples/with-zones/home/now.json
index a7ced4f31364e..cdede10bbd8f7 100644
--- a/examples/with-zones/home/now.json
+++ b/examples/with-zones/home/now.json
@@ -1,16 +1,12 @@
{
- "version": 2,
- "name": "with-zones-home",
- "alias": "with-zones.nextjs.org",
- "build": {
- "env": {
- "DEPLOY": "true"
- }
- },
- "builds": [
- { "src": "package.json", "use": "@now/next" }
- ],
- "routes": [
- { "src": "/blog", "dest": "https://with-zones-blog.nextjs.org" }
- ]
-}
\ No newline at end of file
+ "version": 2,
+ "name": "with-zones-home",
+ "alias": "with-zones.nextjs.org",
+ "build": {
+ "env": {
+ "DEPLOY": "true"
+ }
+ },
+ "builds": [{ "src": "package.json", "use": "@now/next" }],
+ "routes": [{ "src": "/blog", "dest": "https://with-zones-blog.nextjs.org" }]
+}
diff --git a/examples/with-zones/rules-dev.json b/examples/with-zones/rules-dev.json
index efa6027cdfa09..fa3350a131371 100644
--- a/examples/with-zones/rules-dev.json
+++ b/examples/with-zones/rules-dev.json
@@ -1,6 +1,6 @@
{
"rules": [
- {"pathname": "/blog", "dest": "http://localhost:5000"},
- {"pathname": "/**", "dest": "http://localhost:4000"}
+ { "pathname": "/blog", "dest": "http://localhost:5000" },
+ { "pathname": "/**", "dest": "http://localhost:4000" }
]
}
diff --git a/lerna.json b/lerna.json
index a374ee370efc2..579e2ae82a42b 100644
--- a/lerna.json
+++ b/lerna.json
@@ -1,19 +1,14 @@
{
"npmClient": "yarn",
"useWorkspaces": true,
- "packages": [
- "packages/*"
- ],
+ "packages": ["packages/*"],
"command": {
"version": {
"exact": true
},
"publish": {
"npmClient": "npm",
- "allowBranch": [
- "master",
- "canary"
- ],
+ "allowBranch": ["master", "canary"],
"registry": "https://registry.npmjs.org/"
}
},
diff --git a/package.json b/package.json
index b68bddc49ee7b..8c9a5ca0c7538 100644
--- a/package.json
+++ b/package.json
@@ -17,7 +17,7 @@
"coveralls": "cat ./test/coverage/lcov.info | coveralls",
"lint": "lerna run typescript && standard && standard --parser typescript-eslint-parser --plugin typescript \"packages/**/*.ts\"",
"lint-fix": "standard --fix && standard --fix --parser typescript-eslint-parser --plugin typescript \"packages/**/*.ts\"",
- "prettier": "prettier --write \"examples/**/*.js\" && yarn lint-fix",
+ "prettier": "prettier --write \"**/*.{ts,md}\" \"{packages,examples}/**/*.{js,json}\" && yarn lint-fix",
"typescript": "lerna run typescript",
"prepublish": "lerna run prepublish",
"publish-canary": "lerna version prerelease --preid canary --force-publish && release --pre",
@@ -33,15 +33,13 @@
"git add"
],
"*.js": [
+ "prettier --write",
"standard --fix",
"git add"
],
"*.{ts,tsx}": [
- "tslint -c tslint.json --fix",
- "git add"
- ],
- "packages/**/bin/*": [
- "standard --fix",
+ "prettier --write",
+ "standard --fix --parser typescript-eslint-parser --plugin typescript",
"git add"
]
},
@@ -103,7 +101,6 @@
"standard": "12.0.1",
"taskr": "1.1.0",
"tree-kill": "1.2.1",
- "tslint": "5.16.0",
"typescript": "3.4.5",
"typescript-eslint-parser": "22.0.0",
"wait-port": "0.2.2",
diff --git a/packages/next-bundle-analyzer/index.js b/packages/next-bundle-analyzer/index.js
index de09b33a3b8bd..19ea5bbd2a324 100644
--- a/packages/next-bundle-analyzer/index.js
+++ b/packages/next-bundle-analyzer/index.js
@@ -6,7 +6,9 @@ module.exports = ({ enabled = true } = {}) => (nextConfig = {}) => {
config.plugins.push(
new BundleAnalyzerPlugin({
analyzerMode: 'static',
- reportFilename: options.isServer ? '../analyze/server.html' : './analyze/client.html'
+ reportFilename: options.isServer
+ ? '../analyze/server.html'
+ : './analyze/client.html'
})
)
}
diff --git a/packages/next-bundle-analyzer/readme.md b/packages/next-bundle-analyzer/readme.md
index fa69257f42cec..18aa9dedeb114 100644
--- a/packages/next-bundle-analyzer/readme.md
+++ b/packages/next-bundle-analyzer/readme.md
@@ -19,8 +19,10 @@ yarn add @next/bundle-analyzer
Create a next.config.js (and make sure you have next-bundle-analyzer set up)
```js
-const withBundleAnalyzer = require("@next/bundle-analyzer")({ enabled: process.env.ANALYZE === "true" });
-module.exports = withBundleAnalyzer({});
+const withBundleAnalyzer = require('@next/bundle-analyzer')({
+ enabled: process.env.ANALYZE === 'true',
+})
+module.exports = withBundleAnalyzer({})
```
Then you can run the command below:
diff --git a/packages/next-mdx/readme.md b/packages/next-mdx/readme.md
index 79b2a70466e22..6b3c0cf7f64bb 100644
--- a/packages/next-mdx/readme.md
+++ b/packages/next-mdx/readme.md
@@ -30,13 +30,9 @@ Optionally you can provide [MDX options](https://github.com/mdx-js/mdx#options):
// next.config.js
const withMDX = require('@next/mdx')({
options: {
- mdPlugins: [
-
- ],
- hastPlugins: [
-
- ]
- }
+ mdPlugins: [],
+ hastPlugins: [],
+ },
})
module.exports = withMDX()
```
@@ -49,7 +45,7 @@ const withMDX = require('@next/mdx')()
module.exports = withMDX({
webpack(config, options) {
return config
- }
+ },
})
```
@@ -58,7 +54,7 @@ Optionally you can match other file extensions for MDX compilation, by default o
```js
// next.config.js
const withMDX = require('@next/mdx')({
- extension: /\.(md|mdx)$/
+ extension: /\.(md|mdx)$/,
})
module.exports = withMDX()
```
@@ -70,9 +66,9 @@ Define the `pagesExtensions` option to have Next.js handle `.mdx` files in the `
```js
// next.config.js
const withMDX = require('@next/mdx')({
- extension: /\.mdx?$/
+ extension: /\.mdx?$/,
})
module.exports = withMDX({
- pageExtensions: ['js', 'jsx', 'mdx']
+ pageExtensions: ['js', 'jsx', 'mdx'],
})
```
diff --git a/packages/next-server/dynamic.d.ts b/packages/next-server/dynamic.d.ts
index e3eca5332e103..73a3c2391c171 100644
--- a/packages/next-server/dynamic.d.ts
+++ b/packages/next-server/dynamic.d.ts
@@ -1,2 +1,2 @@
export * from './dist/lib/dynamic'
-export {default} from './dist/lib/dynamic'
+export { default } from './dist/lib/dynamic'
diff --git a/packages/next-server/head.d.ts b/packages/next-server/head.d.ts
index 393b748a3693b..a474f2d17b022 100644
--- a/packages/next-server/head.d.ts
+++ b/packages/next-server/head.d.ts
@@ -1,2 +1,2 @@
export * from './dist/lib/head'
-export {default} from './dist/lib/head'
+export { default } from './dist/lib/head'
diff --git a/packages/next-server/index.d.ts b/packages/next-server/index.d.ts
index 71df82686d68f..a59671c2036c0 100644
--- a/packages/next-server/index.d.ts
+++ b/packages/next-server/index.d.ts
@@ -1,2 +1,2 @@
-import Server, {ServerConstructor} from './dist/server/next-server'
+import Server, { ServerConstructor } from './dist/server/next-server'
export default function(options: ServerConstructor): Server
diff --git a/packages/next-server/lib/amp.ts b/packages/next-server/lib/amp.ts
index 0acc53f00b0be..116ca6d96e913 100644
--- a/packages/next-server/lib/amp.ts
+++ b/packages/next-server/lib/amp.ts
@@ -1,10 +1,10 @@
import React from 'react'
-import {AmpModeContext} from './amphtml-context'
+import { AmpModeContext } from './amphtml-context'
export function isAmp({
- enabled= false,
- hybrid= false,
- hasQuery= false,
+ enabled = false,
+ hybrid = false,
+ hasQuery = false,
} = {}) {
return enabled && (!hybrid || (hybrid && hasQuery))
}
@@ -15,11 +15,8 @@ export function useAmp() {
return isAmp(ampMode) // && ampMode.hasQuery
}
-export function withAmp(
- Component: any,
- { hybrid = false } = {},
-): any {
- function WithAmpWrapper(props= {}) {
+export function withAmp(Component: any, { hybrid = false } = {}): any {
+ function WithAmpWrapper(props = {}) {
const ampMode = React.useContext(AmpModeContext)
ampMode.enabled = true
ampMode.hybrid = hybrid
diff --git a/packages/next-server/lib/constants.ts b/packages/next-server/lib/constants.ts
index bb832b95aa4b5..2a2834aba5da8 100644
--- a/packages/next-server/lib/constants.ts
+++ b/packages/next-server/lib/constants.ts
@@ -10,10 +10,7 @@ export const SERVER_DIRECTORY = 'server'
export const SERVERLESS_DIRECTORY = 'serverless'
export const CONFIG_FILE = 'next.config.js'
export const BUILD_ID_FILE = 'BUILD_ID'
-export const BLOCKED_PAGES = [
- '/_document',
- '/_app',
-]
+export const BLOCKED_PAGES = ['/_document', '/_app']
export const CLIENT_PUBLIC_FILES_PATH = 'public'
export const CLIENT_STATIC_FILES_PATH = 'static'
export const CLIENT_STATIC_FILES_RUNTIME = 'runtime'
diff --git a/packages/next-server/lib/loadable-context.ts b/packages/next-server/lib/loadable-context.ts
index dafe8a72a7cac..503127c2c9751 100644
--- a/packages/next-server/lib/loadable-context.ts
+++ b/packages/next-server/lib/loadable-context.ts
@@ -3,4 +3,6 @@ import * as React from 'react'
type CaptureFn = (moduleName: string) => void
// @ts-ignore for some reason the React types don't like this, but it's correct.
-export const LoadableContext: React.Context = React.createContext(null)
+export const LoadableContext: React.Context = React.createContext(
+ null
+)
diff --git a/packages/next-server/lib/loadable.d.ts b/packages/next-server/lib/loadable.d.ts
index 86ccc1a86a377..1c68ec67aa27c 100644
--- a/packages/next-server/lib/loadable.d.ts
+++ b/packages/next-server/lib/loadable.d.ts
@@ -9,6 +9,6 @@ declare namespace LoadableExport {
}
}
-declare const LoadableExport: LoadableExport.ILoadable;
+declare const LoadableExport: LoadableExport.ILoadable
export = LoadableExport
diff --git a/packages/next-server/lib/loadable.js b/packages/next-server/lib/loadable.js
index 38f0b4cffa162..758b077c272c7 100644
--- a/packages/next-server/lib/loadable.js
+++ b/packages/next-server/lib/loadable.js
@@ -136,9 +136,13 @@ function createLoadableComponent (loadFn, options) {
}
// Client only
- if (!initialized && typeof window !== 'undefined' && typeof opts.webpack === 'function') {
+ if (
+ !initialized &&
+ typeof window !== 'undefined' &&
+ typeof opts.webpack === 'function'
+ ) {
const moduleIds = opts.webpack()
- READY_INITIALIZERS.push((ids) => {
+ READY_INITIALIZERS.push(ids => {
for (const moduleId of moduleIds) {
if (ids.indexOf(moduleId) !== -1) {
return init()
@@ -237,7 +241,7 @@ function createLoadableComponent (loadFn, options) {
this.setState({ error: null, loading: true, timedOut: false })
res = loadFn(opts.loader)
this._loadModule()
- };
+ }
render () {
if (this.state.loading || this.state.error) {
@@ -292,8 +296,8 @@ Loadable.preloadAll = () => {
})
}
-Loadable.preloadReady = (ids) => {
- return new Promise((resolve) => {
+Loadable.preloadReady = ids => {
+ return new Promise(resolve => {
const res = () => {
initialized = true
return resolve()
diff --git a/packages/next-server/lib/mitt.ts b/packages/next-server/lib/mitt.ts
index 7def05b0ed3c9..e0e3a90ec036f 100644
--- a/packages/next-server/lib/mitt.ts
+++ b/packages/next-server/lib/mitt.ts
@@ -19,7 +19,7 @@ type Handler = (...evts: any[]) => void
export type MittEmitter = {
on(type: string, handler: Handler): void
off(type: string, handler: Handler): void
- emit(type: string, ...evts: any[]): void,
+ emit(type: string, ...evts: any[]): void
}
export default function mitt(): MittEmitter {
@@ -27,7 +27,7 @@ export default function mitt(): MittEmitter {
return {
on(type: string, handler: Handler) {
- (all[type] || (all[type] = [])).push(handler)
+ ;(all[type] || (all[type] = [])).push(handler)
},
off(type: string, handler: Handler) {
@@ -38,7 +38,9 @@ export default function mitt(): MittEmitter {
},
emit(type: string, ...evts: any[]) {
- (all[type] || []).slice().map((handler: Handler) => { handler(...evts) })
+ ;(all[type] || []).slice().map((handler: Handler) => {
+ handler(...evts)
+ })
},
}
}
diff --git a/packages/next-server/lib/router/router.ts b/packages/next-server/lib/router/router.ts
index aa0e77a065f18..d4551adb8747a 100644
--- a/packages/next-server/lib/router/router.ts
+++ b/packages/next-server/lib/router/router.ts
@@ -1,15 +1,19 @@
/* global __NEXT_DATA__ */
// tslint:disable:no-console
-import { ParsedUrlQuery } from 'querystring';
-import { ComponentType } from 'react';
-import { parse } from 'url';
+import { ParsedUrlQuery } from 'querystring'
+import { ComponentType } from 'react'
+import { parse } from 'url'
-import mitt, { MittEmitter } from '../mitt';
+import mitt, { MittEmitter } from '../mitt'
import {
- AppContextType, formatWithValidation, getURL, loadGetInitialProps, NextPageContext,
-} from '../utils';
-import { rewriteUrlForNextExport } from './rewrite-url-for-export';
-import { getRouteRegex } from './utils';
+ AppContextType,
+ formatWithValidation,
+ getURL,
+ loadGetInitialProps,
+ NextPageContext,
+} from '../utils'
+import { rewriteUrlForNextExport } from './rewrite-url-for-export'
+import { getRouteRegex } from './utils'
function toRoute(path: string): string {
return path.replace(/\/$/, '') || '/'
@@ -19,17 +23,17 @@ export type BaseRouter = {
route: string
pathname: string
query: ParsedUrlQuery
- asPath: string,
+ asPath: string
}
type RouteInfo = {
- Component: ComponentType,
- props?: any,
+ Component: ComponentType
+ props?: any
err?: Error
- error?: any,
+ error?: any
}
-type Subscription = (data: {App?: ComponentType} & RouteInfo) => void
+type Subscription = (data: { App?: ComponentType } & RouteInfo) => void
type BeforePopStateCallback = (state: any) => boolean
@@ -41,7 +45,7 @@ export default class Router implements BaseRouter {
/**
* Map of all components loaded in `Router`
*/
- components: {[pathname: string]: RouteInfo}
+ components: { [pathname: string]: RouteInfo }
subscriptions: Set
componentLoadCancel: (() => void) | null
pageLoader: any
@@ -49,7 +53,24 @@ export default class Router implements BaseRouter {
static events: MittEmitter = mitt()
- constructor(pathname: string, query: ParsedUrlQuery, as: string, { initialProps, pageLoader, App, Component, err }: {initialProps: any, pageLoader: any, Component: ComponentType, App: ComponentType, err?: Error}) {
+ constructor(
+ pathname: string,
+ query: ParsedUrlQuery,
+ as: string,
+ {
+ initialProps,
+ pageLoader,
+ App,
+ Component,
+ err,
+ }: {
+ initialProps: any
+ pageLoader: any
+ Component: ComponentType
+ App: ComponentType
+ err?: Error
+ }
+ ) {
// represents the current component key
this.route = toRoute(pathname)
@@ -79,7 +100,11 @@ export default class Router implements BaseRouter {
if (typeof window !== 'undefined') {
// in order for `e.state` to work on the `onpopstate` event
// we have to register the initial route upon initialization
- this.changeState('replaceState', formatWithValidation({ pathname, query }), as)
+ this.changeState(
+ 'replaceState',
+ formatWithValidation({ pathname, query }),
+ as
+ )
window.addEventListener('popstate', this.onPopState)
window.addEventListener('unload', () => {
@@ -87,7 +112,10 @@ export default class Router implements BaseRouter {
// navigating back from an external site
if (history.state) {
const { url, as, options }: any = history.state
- this.changeState('replaceState', url, as, { ...options, fromExternal: true })
+ this.changeState('replaceState', url, as, {
+ ...options,
+ fromExternal: true,
+ })
}
})
}
@@ -109,7 +137,11 @@ export default class Router implements BaseRouter {
// Actually, for (1) we don't need to nothing. But it's hard to detect that event.
// So, doing the following for (1) does no harm.
const { pathname, query } = this
- this.changeState('replaceState', formatWithValidation({ pathname, query }), getURL())
+ this.changeState(
+ 'replaceState',
+ formatWithValidation({ pathname, query }),
+ getURL()
+ )
return
}
@@ -128,11 +160,13 @@ export default class Router implements BaseRouter {
const { url, as, options } = e.state
if (process.env.NODE_ENV !== 'production') {
if (typeof url === 'undefined' || typeof as === 'undefined') {
- console.warn('`popstate` event triggered but `event.state` did not have `url` or `as` https://err.sh/zeit/next.js/popstate-state-empty')
+ console.warn(
+ '`popstate` event triggered but `event.state` did not have `url` or `as` https://err.sh/zeit/next.js/popstate-state-empty'
+ )
}
}
this.replace(url, as, options)
- };
+ }
update(route: string, Component: ComponentType) {
const data = this.components[route]
@@ -185,7 +219,12 @@ export default class Router implements BaseRouter {
return this.change('replaceState', url, as, options)
}
- change(method: string, _url: string, _as: string, options: any): Promise {
+ change(
+ method: string,
+ _url: string,
+ _as: string,
+ options: any
+ ): Promise {
return new Promise((resolve, reject) => {
// If url and as provided as an object representation,
// we'll format them into the string version here.
@@ -234,11 +273,13 @@ export default class Router implements BaseRouter {
const { re: routeRegex, groups } = getRouteRegex(route)
const routeMatch = routeRegex.exec(as)
if (!routeMatch) {
- console.error("Your ``'s `as` value is incompatible with the `href` value. This is invalid.")
+ console.error(
+ "Your ``'s `as` value is incompatible with the `href` value. This is invalid."
+ )
return resolve(false)
}
- Object.keys(groups).forEach((slugName) => {
+ Object.keys(groups).forEach(slugName => {
const m = routeMatch[groups[slugName]]
if (m !== undefined) {
query[slugName] = decodeURIComponent(m)
@@ -250,7 +291,7 @@ export default class Router implements BaseRouter {
// If shallow is true and the route exists in the router cache we reuse the previous result
// @ts-ignore pathname is always a string
- this.getRouteInfo(route, pathname, query, as, shallow).then((routeInfo) => {
+ this.getRouteInfo(route, pathname, query, as, shallow).then(routeInfo => {
const { error } = routeInfo
if (error && error.cancelled) {
@@ -294,7 +335,13 @@ export default class Router implements BaseRouter {
}
}
- getRouteInfo(route: string, pathname: string, query: any, as: string, shallow: boolean = false): Promise {
+ getRouteInfo(
+ route: string,
+ pathname: string,
+ query: any,
+ as: string,
+ shallow: boolean = false
+ ): Promise {
const cachedRouteInfo = this.components[route]
// If there is a shallow route transition possible
@@ -308,69 +355,90 @@ export default class Router implements BaseRouter {
return resolve(cachedRouteInfo)
}
- this.fetchComponent(route).then((Component) => resolve({Component}), reject)
- }) as Promise).then((routeInfo: RouteInfo) => {
- const { Component } = routeInfo
-
- if (process.env.NODE_ENV !== 'production') {
- const { isValidElementType } = require('react-is')
- if (!isValidElementType(Component)) {
- throw new Error(`The default export is not a React Component in page: "${pathname}"`)
+ this.fetchComponent(route).then(
+ Component => resolve({ Component }),
+ reject
+ )
+ }) as Promise)
+ .then((routeInfo: RouteInfo) => {
+ const { Component } = routeInfo
+
+ if (process.env.NODE_ENV !== 'production') {
+ const { isValidElementType } = require('react-is')
+ if (!isValidElementType(Component)) {
+ throw new Error(
+ `The default export is not a React Component in page: "${pathname}"`
+ )
+ }
}
- }
- return (new Promise((resolve, reject) => {
- const ctx = { pathname, query, asPath: as }
- this.getInitialProps(Component, ctx).then((props) => {
- routeInfo.props = props
- this.components[route] = routeInfo
- resolve(routeInfo)
- }, reject)
- }) as Promise)
- }).catch((err) => {
- return (new Promise((resolve) => {
- if (err.code === 'PAGE_LOAD_ERROR') {
- // If we can't load the page it could be one of following reasons
- // 1. Page doesn't exists
- // 2. Page does exist in a different zone
- // 3. Internal error while loading the page
-
- // So, doing a hard reload is the proper way to deal with this.
- window.location.href = as
-
- // Changing the URL doesn't block executing the current code path.
- // So, we need to mark it as a cancelled error and stop the routing logic.
- err.cancelled = true
- // @ts-ignore TODO: fix the control flow here
- return resolve({ error: err })
- }
+ return new Promise((resolve, reject) => {
+ const ctx = { pathname, query, asPath: as }
+ this.getInitialProps(Component, ctx).then(props => {
+ routeInfo.props = props
+ this.components[route] = routeInfo
+ resolve(routeInfo)
+ }, reject)
+ }) as Promise
+ })
+ .catch(err => {
+ return new Promise(resolve => {
+ if (err.code === 'PAGE_LOAD_ERROR') {
+ // If we can't load the page it could be one of following reasons
+ // 1. Page doesn't exists
+ // 2. Page does exist in a different zone
+ // 3. Internal error while loading the page
+
+ // So, doing a hard reload is the proper way to deal with this.
+ window.location.href = as
+
+ // Changing the URL doesn't block executing the current code path.
+ // So, we need to mark it as a cancelled error and stop the routing logic.
+ err.cancelled = true
+ // @ts-ignore TODO: fix the control flow here
+ return resolve({ error: err })
+ }
- if (err.cancelled) {
- // @ts-ignore TODO: fix the control flow here
- return resolve({ error: err })
- }
+ if (err.cancelled) {
+ // @ts-ignore TODO: fix the control flow here
+ return resolve({ error: err })
+ }
- resolve(this.fetchComponent('/_error').then((Component) => {
- const routeInfo: RouteInfo = { Component, err }
- const ctx = { err, pathname, query }
- return (new Promise((resolve) => {
- this.getInitialProps(Component, ctx).then((props) => {
- routeInfo.props = props
- routeInfo.error = err
- resolve(routeInfo)
- }, (gipErr) => {
- console.error('Error in error page `getInitialProps`: ', gipErr)
- routeInfo.error = err
- routeInfo.props = {}
- resolve(routeInfo)
+ resolve(
+ this.fetchComponent('/_error').then(Component => {
+ const routeInfo: RouteInfo = { Component, err }
+ const ctx = { err, pathname, query }
+ return new Promise(resolve => {
+ this.getInitialProps(Component, ctx).then(
+ props => {
+ routeInfo.props = props
+ routeInfo.error = err
+ resolve(routeInfo)
+ },
+ gipErr => {
+ console.error(
+ 'Error in error page `getInitialProps`: ',
+ gipErr
+ )
+ routeInfo.error = err
+ routeInfo.props = {}
+ resolve(routeInfo)
+ }
+ )
+ }) as Promise
})
- }) as Promise)
- }))
- }) as Promise)
- })
+ )
+ }) as Promise
+ })
}
- set(route: string, pathname: string, query: any, as: string, data: RouteInfo): void {
+ set(
+ route: string,
+ pathname: string,
+ query: any,
+ as: string,
+ data: RouteInfo
+ ): void {
this.route = route
this.pathname = pathname
this.query = query
@@ -388,11 +456,11 @@ export default class Router implements BaseRouter {
onlyAHashChange(as: string): boolean {
if (!this.asPath) return false
- const [ oldUrlNoHash, oldHash ] = this.asPath.split('#')
- const [ newUrlNoHash, newHash ] = as.split('#')
+ const [oldUrlNoHash, oldHash] = this.asPath.split('#')
+ const [newUrlNoHash, newHash] = as.split('#')
// Makes sure we scroll to the provided hash if the url/hash are the same
- if (newHash && (oldUrlNoHash === newUrlNoHash) && (oldHash === newHash)) {
+ if (newHash && oldUrlNoHash === newUrlNoHash && oldHash === newHash) {
return true
}
@@ -409,7 +477,7 @@ export default class Router implements BaseRouter {
}
scrollToHash(as: string): void {
- const [ , hash ] = as.split('#')
+ const [, hash] = as.split('#')
// Scroll to top if the hash is just `#` with no value
if (hash === '') {
window.scrollTo(0, 0)
@@ -442,7 +510,11 @@ export default class Router implements BaseRouter {
prefetch(url: string): Promise {
return new Promise((resolve, reject) => {
// Prefetch is not supported in development mode because it would trigger on-demand-entries
- if (process.env.NODE_ENV !== 'production' || process.env.__NEXT_EXPERIMENTAL_DEBUG) return
+ if (
+ process.env.NODE_ENV !== 'production' ||
+ process.env.__NEXT_EXPERIMENTAL_DEBUG
+ )
+ return
const { pathname } = parse(url)
// @ts-ignore pathname is always defined
@@ -453,14 +525,16 @@ export default class Router implements BaseRouter {
async fetchComponent(route: string): Promise {
let cancelled = false
- const cancel = this.componentLoadCancel = () => {
+ const cancel = (this.componentLoadCancel = () => {
cancelled = true
- }
+ })
const Component = await this.pageLoader.loadPage(route)
if (cancelled) {
- const error: any = new Error(`Abort fetching component for route: "${route}"`)
+ const error: any = new Error(
+ `Abort fetching component for route: "${route}"`
+ )
error.cancelled = true
throw error
}
@@ -472,13 +546,22 @@ export default class Router implements BaseRouter {
return Component
}
- async getInitialProps(Component: ComponentType, ctx: NextPageContext): Promise {
+ async getInitialProps(
+ Component: ComponentType,
+ ctx: NextPageContext
+ ): Promise {
let cancelled = false
- const cancel = () => { cancelled = true }
+ const cancel = () => {
+ cancelled = true
+ }
this.componentLoadCancel = cancel
const { Component: App } = this.components['/_app']
- const props = await loadGetInitialProps>(App, { Component, router: this, ctx })
+ const props = await loadGetInitialProps>(App, {
+ Component,
+ router: this,
+ ctx,
+ })
if (cancel === this.componentLoadCancel) {
this.componentLoadCancel = null
@@ -503,7 +586,7 @@ export default class Router implements BaseRouter {
notify(data: RouteInfo): void {
const { Component: App } = this.components['/_app']
- this.subscriptions.forEach((fn) => fn({ ...data, App }))
+ this.subscriptions.forEach(fn => fn({ ...data, App }))
}
subscribe(fn: Subscription): () => void {
diff --git a/packages/next-server/lib/router/utils.ts b/packages/next-server/lib/router/utils.ts
index e1920fd4883f3..f91190b8c345e 100644
--- a/packages/next-server/lib/router/utils.ts
+++ b/packages/next-server/lib/router/utils.ts
@@ -1,9 +1,9 @@
export function getRouteRegex(
- route: string,
+ route: string
): { re: RegExp; groups: { [groupName: string]: number } } {
const escapedRoute = (route.replace(/\/$/, '') || '/').replace(
/[|\\{}()[\]^$+*?.-]/g,
- '\\$&',
+ '\\$&'
)
const groups: { [groupName: string]: number } = {}
@@ -16,7 +16,7 @@ export function getRouteRegex(
$1.replace(/\\\$$/, '').replace(/\\([|\\{}()[\]^$+*?.-])/g, '$1')
] = groupIndex++),
$1.lastIndexOf('$') === $1.length - 1 ? '(?:/([^/]+?))?' : '/([^/]+?)'
- ),
+ )
)
return {
diff --git a/packages/next-server/lib/utils.ts b/packages/next-server/lib/utils.ts
index d7ac463e79c1f..cde63e20c4fb9 100644
--- a/packages/next-server/lib/utils.ts
+++ b/packages/next-server/lib/utils.ts
@@ -13,7 +13,7 @@ export type NextComponentType<
IP = {},
P = {}
> = ComponentType
& {
- getInitialProps?(context: C): Promise,
+ getInitialProps?(context: C): Promise
}
export type DocumentType = NextComponentType<
@@ -33,23 +33,23 @@ export type Enhancer = (Component: C) => C
export type ComponentsEnhancer =
| {
enhanceApp?: Enhancer
- enhanceComponent?: Enhancer,
+ enhanceComponent?: Enhancer
}
| Enhancer
export type RenderPageResult = {
html: string
head?: Array
- dataOnly?: true,
+ dataOnly?: true
}
export type RenderPage = (
- options?: ComponentsEnhancer,
+ options?: ComponentsEnhancer
) => RenderPageResult | Promise
export type BaseContext = {
res?: ServerResponse
- [k: string]: any,
+ [k: string]: any
}
export type NEXT_DATA = {
@@ -63,7 +63,7 @@ export type NEXT_DATA = {
runtimeConfig?: { [key: string]: any }
nextExport?: boolean
dynamicIds?: string[]
- err?: Error & { statusCode?: number },
+ err?: Error & { statusCode?: number }
}
/**
@@ -100,11 +100,11 @@ export interface NextPageContext {
export type AppContextType = {
Component: NextComponentType
router: R
- ctx: NextPageContext,
+ ctx: NextPageContext
}
export type AppInitialProps = {
- pageProps: any,
+ pageProps: any
}
export type AppPropsType<
@@ -112,15 +112,15 @@ export type AppPropsType<
P = {}
> = AppInitialProps & {
Component: NextComponentType
- router: R,
+ router: R
}
export type DocumentContext = NextPageContext & {
- renderPage: RenderPage,
+ renderPage: RenderPage
}
export type DocumentInitialProps = RenderPageResult & {
- styles?: React.ReactElement[],
+ styles?: React.ReactElement[]
}
export type DocumentProps = DocumentInitialProps & {
@@ -133,8 +133,8 @@ export type DocumentProps = DocumentInitialProps & {
devFiles: string[]
files: string[]
dynamicImports: ManifestItem[]
- assetPrefix?: string,
- canonicalBase: string,
+ assetPrefix?: string
+ canonicalBase: string
}
/**
@@ -180,7 +180,7 @@ export async function loadGetInitialProps<
if (process.env.NODE_ENV !== 'production') {
if (Component.prototype && Component.prototype.getInitialProps) {
const message = `"${getDisplayName(
- Component,
+ Component
)}.getInitialProps()" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information.`
throw new Error(message)
}
@@ -201,20 +201,18 @@ export async function loadGetInitialProps<
// if page component doesn't have getInitialProps
// set cache-control header to stale-while-revalidate
if (ctx.Component && !ctx.Component.getInitialProps) {
- const customAppGetInitialProps = (Component as any).origGetInitialProps && (
+ const customAppGetInitialProps =
+ (Component as any).origGetInitialProps &&
(Component as any).origGetInitialProps !== Component.getInitialProps
- )
if (!customAppGetInitialProps && res && res.setHeader) {
- res.setHeader(
- 'Cache-Control', 's-maxage=86400, stale-while-revalidate',
- )
+ res.setHeader('Cache-Control', 's-maxage=86400, stale-while-revalidate')
}
}
if (!props) {
const message = `"${getDisplayName(
- Component,
+ Component
)}.getInitialProps()" should resolve to an object. But found "${props}" instead.`
throw new Error(message)
}
@@ -239,14 +237,14 @@ export const urlObjectKeys = [
export function formatWithValidation(
url: UrlObject,
- options?: URLFormatOptions,
+ options?: URLFormatOptions
) {
if (process.env.NODE_ENV === 'development') {
if (url !== null && typeof url === 'object') {
- Object.keys(url).forEach((key) => {
+ Object.keys(url).forEach(key => {
if (urlObjectKeys.indexOf(key) === -1) {
console.warn(
- `Unknown key passed via urlObject into url.format: ${key}`,
+ `Unknown key passed via urlObject into url.format: ${key}`
)
}
})
diff --git a/packages/next-server/server/config.ts b/packages/next-server/server/config.ts
index 4c646044e0a21..687e2b0064a36 100644
--- a/packages/next-server/server/config.ts
+++ b/packages/next-server/server/config.ts
@@ -4,7 +4,7 @@ import { CONFIG_FILE } from '../lib/constants'
const targets = ['server', 'serverless']
-const defaultConfig: {[key: string]: any} = {
+const defaultConfig: { [key: string]: any } = {
env: [],
webpack: null,
webpackDevMiddleware: null,
@@ -28,7 +28,7 @@ const defaultConfig: {[key: string]: any} = {
cpus: Math.max(
1,
(Number(process.env.CIRCLE_NODE_TOTAL) ||
- (os.cpus() || { length: 1 }).length) - 1,
+ (os.cpus() || { length: 1 }).length) - 1
),
dynamicRouting: false,
autoExport: false,
@@ -41,10 +41,10 @@ const defaultConfig: {[key: string]: any} = {
},
}
-function assignDefaults(userConfig: {[key: string]: any}) {
+function assignDefaults(userConfig: { [key: string]: any }) {
Object.keys(userConfig).forEach((key: string) => {
const maybeObject = userConfig[key]
- if ((!!maybeObject) && (maybeObject.constructor === Object)) {
+ if (!!maybeObject && maybeObject.constructor === Object) {
userConfig[key] = {
...(defaultConfig[key] || {}),
...userConfig[key],
@@ -61,14 +61,18 @@ function normalizeConfig(phase: string, config: any) {
if (typeof config.then === 'function') {
throw new Error(
- '> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config.md',
+ '> Promise returned in next config. https://err.sh/zeit/next.js/promise-in-next-config.md'
)
}
}
return config
}
-export default function loadConfig(phase: string, dir: string, customConfig: any) {
+export default function loadConfig(
+ phase: string,
+ dir: string,
+ customConfig: any
+) {
if (customConfig) {
return assignDefaults({ configOrigin: 'server', ...customConfig })
}
@@ -79,16 +83,25 @@ export default function loadConfig(phase: string, dir: string, customConfig: any
// If config file was found
if (path && path.length) {
const userConfigModule = require(path)
- const userConfig = normalizeConfig(phase, userConfigModule.default || userConfigModule)
+ const userConfig = normalizeConfig(
+ phase,
+ userConfigModule.default || userConfigModule
+ )
if (userConfig.target && !targets.includes(userConfig.target)) {
- throw new Error(`Specified target is invalid. Provided: "${userConfig.target}" should be one of ${targets.join(', ')}`)
+ throw new Error(
+ `Specified target is invalid. Provided: "${
+ userConfig.target
+ }" should be one of ${targets.join(', ')}`
+ )
}
if (userConfig.amp && userConfig.amp.canonicalBase) {
- const { canonicalBase } = userConfig.amp || {} as any
+ const { canonicalBase } = userConfig.amp || ({} as any)
userConfig.amp = userConfig.amp || {}
- userConfig.amp.canonicalBase = (canonicalBase.endsWith('/')
- ? canonicalBase.slice(0, -1) : canonicalBase) || ''
+ userConfig.amp.canonicalBase =
+ (canonicalBase.endsWith('/')
+ ? canonicalBase.slice(0, -1)
+ : canonicalBase) || ''
}
return assignDefaults({ configOrigin: CONFIG_FILE, ...userConfig })
diff --git a/packages/next-server/server/get-dynamic-import-bundles.ts b/packages/next-server/server/get-dynamic-import-bundles.ts
index 12df48fe07c47..5612cb779b9c7 100644
--- a/packages/next-server/server/get-dynamic-import-bundles.ts
+++ b/packages/next-server/server/get-dynamic-import-bundles.ts
@@ -1,22 +1,28 @@
export type ManifestItem = {
- id: number|string,
- name: string,
- file: string,
- publicPath: string,
+ id: number | string
+ name: string
+ file: string
+ publicPath: string
}
-export type Manifest = {[moduleId: string]: ManifestItem[]}
+export type Manifest = { [moduleId: string]: ManifestItem[] }
type DynamicImportBundles = Set
// Based on https://github.com/jamiebuilds/react-loadable/pull/132
-export function getDynamicImportBundles(manifest: Manifest, moduleIds: string[]): DynamicImportBundles {
- return moduleIds.reduce((bundles: DynamicImportBundles, moduleId: string): DynamicImportBundles => {
- if (typeof manifest[moduleId] === 'undefined') {
- return bundles
- }
+export function getDynamicImportBundles(
+ manifest: Manifest,
+ moduleIds: string[]
+): DynamicImportBundles {
+ return moduleIds.reduce(
+ (bundles: DynamicImportBundles, moduleId: string): DynamicImportBundles => {
+ if (typeof manifest[moduleId] === 'undefined') {
+ return bundles
+ }
- manifest[moduleId].map((item) => bundles.add(item))
- return bundles
- }, new Set())
+ manifest[moduleId].map(item => bundles.add(item))
+ return bundles
+ },
+ new Set()
+ )
}
diff --git a/packages/next-server/server/get-page-files.ts b/packages/next-server/server/get-page-files.ts
index de1670f3ef16e..9d79e60d32b66 100644
--- a/packages/next-server/server/get-page-files.ts
+++ b/packages/next-server/server/get-page-files.ts
@@ -1,13 +1,16 @@
import { normalizePagePath } from './normalize-page-path'
export type BuildManifest = {
- devFiles: string[],
+ devFiles: string[]
pages: {
- [page: string]: string[],
- },
+ [page: string]: string[]
+ }
}
-export function getPageFiles(buildManifest: BuildManifest, page: string): string[] {
+export function getPageFiles(
+ buildManifest: BuildManifest,
+ page: string
+): string[] {
const normalizedPage = normalizePagePath(page)
let files = buildManifest.pages[normalizedPage]
@@ -17,7 +20,9 @@ export function getPageFiles(buildManifest: BuildManifest, page: string): string
if (!files) {
// tslint:disable-next-line
- console.warn(`Could not find files for ${normalizedPage} in .next/build-manifest.json`)
+ console.warn(
+ `Could not find files for ${normalizedPage} in .next/build-manifest.json`
+ )
return []
}
diff --git a/packages/next-server/server/lib/path-match.ts b/packages/next-server/server/lib/path-match.ts
index 3c71e4ac06ff3..c452810e14ac3 100644
--- a/packages/next-server/server/lib/path-match.ts
+++ b/packages/next-server/server/lib/path-match.ts
@@ -9,7 +9,7 @@ export default () => {
const keys: any[] = []
const re = pathToRegexp(path, keys, {})
- return (pathname: string|undefined, params?: any) => {
+ return (pathname: string | undefined, params?: any) => {
const m = re.exec(pathname)
if (!m) return false
diff --git a/packages/next-server/server/lib/recursive-readdir-sync.ts b/packages/next-server/server/lib/recursive-readdir-sync.ts
index f5f755d1a797a..9ef1367269e82 100644
--- a/packages/next-server/server/lib/recursive-readdir-sync.ts
+++ b/packages/next-server/server/lib/recursive-readdir-sync.ts
@@ -7,7 +7,11 @@ import { join } from 'path'
* @param {string=dir`} rootDir Used to replace the initial path, only the relative path is left, it's faster than path.relative.
* @returns Array holding all relative paths
*/
-export function recursiveReadDirSync(dir: string, arr: string[] = [], rootDir = dir): string[] {
+export function recursiveReadDirSync(
+ dir: string,
+ arr: string[] = [],
+ rootDir = dir
+): string[] {
const result = fs.readdirSync(dir)
result.forEach((part: string) => {
diff --git a/packages/next-server/server/load-components.ts b/packages/next-server/server/load-components.ts
index 80789d983bed4..ac69bbfb5b42e 100644
--- a/packages/next-server/server/load-components.ts
+++ b/packages/next-server/server/load-components.ts
@@ -18,14 +18,14 @@ export type LoadComponentsReturnType = {
reactLoadableManifest?: any
Document?: any
DocumentMiddleware?: any
- App?: any,
+ App?: any
}
export async function loadComponents(
distDir: string,
buildId: string,
pathname: string,
- serverless: boolean,
+ serverless: boolean
): Promise {
if (serverless) {
const Component = await requirePage(pathname, distDir, serverless)
@@ -37,7 +37,7 @@ export async function loadComponents(
CLIENT_STATIC_FILES_PATH,
buildId,
'pages',
- '_document',
+ '_document'
)
const appPath = join(
distDir,
@@ -45,7 +45,7 @@ export async function loadComponents(
CLIENT_STATIC_FILES_PATH,
buildId,
'pages',
- '_app',
+ '_app'
)
const DocumentMod = require(documentPath)
diff --git a/packages/next-server/server/next-server.ts b/packages/next-server/server/next-server.ts
index b650ddde48b4f..8afd4b34f2ab1 100644
--- a/packages/next-server/server/next-server.ts
+++ b/packages/next-server/server/next-server.ts
@@ -37,7 +37,7 @@ export type ServerConstructor = {
dir?: string
staticMarkup?: boolean
quiet?: boolean
- conf?: NextConfig,
+ conf?: NextConfig
}
export default class Server {
@@ -55,10 +55,10 @@ export default class Server {
buildId: string
generateEtags: boolean
runtimeConfig?: { [key: string]: any }
- assetPrefix?: string,
- canonicalBase: string,
+ assetPrefix?: string
+ canonicalBase: string
autoExport: boolean
- dev?: boolean,
+ dev?: boolean
}
router: Router
private dynamicRoutes?: Array<{ page: string; match: RouteMatch }>
@@ -130,7 +130,7 @@ export default class Server {
private handleRequest(
req: IncomingMessage,
res: ServerResponse,
- parsedUrl?: UrlWithParsedQuery,
+ parsedUrl?: UrlWithParsedQuery
): Promise {
// Parse url if parsedUrl not provided
if (!parsedUrl || typeof parsedUrl !== 'object') {
@@ -144,7 +144,7 @@ export default class Server {
}
res.statusCode = 200
- return this.run(req, res, parsedUrl).catch((err) => {
+ return this.run(req, res, parsedUrl).catch(err => {
this.logError(err)
res.statusCode = 500
res.end('Internal Server Error')
@@ -187,7 +187,7 @@ export default class Server {
const p = join(
this.distDir,
CLIENT_STATIC_FILES_PATH,
- ...(params.path || []),
+ ...(params.path || [])
)
await this.serveStatic(req, res, p, parsedUrl)
},
@@ -257,7 +257,7 @@ export default class Server {
private async handleApiRequest(
req: IncomingMessage,
res: ServerResponse,
- pathname: string,
+ pathname: string
) {
const resolverFunction = await this.resolveApiRequest(pathname)
if (resolverFunction === null) {
@@ -278,7 +278,7 @@ export default class Server {
return getPagePath(
pathname,
this.distDir,
- this.nextConfig.target === 'serverless',
+ this.nextConfig.target === 'serverless'
)
}
@@ -288,7 +288,7 @@ export default class Server {
const serverBuildPath = join(this.distDir, SERVER_DIRECTORY)
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
- publicFiles.forEach((path) => {
+ publicFiles.forEach(path => {
const unixPath = path.replace(/\\/g, '/')
// Only include public files that will not replace a page path
if (!pagesManifest[unixPath]) {
@@ -307,23 +307,23 @@ export default class Server {
private getDynamicRoutes() {
const manifest = require(this.buildManifest)
- const dynamicRoutedPages = Object.keys(manifest.pages).filter((p) =>
- p.includes('/$'),
+ const dynamicRoutedPages = Object.keys(manifest.pages).filter(p =>
+ p.includes('/$')
)
return dynamicRoutedPages
- .map((page) => ({
+ .map(page => ({
page,
match: getRouteMatch(page),
}))
.sort((a, b) =>
- Math.sign(a.page.match(/\/\$/g)!.length - b.page.match(/\/\$/g)!.length),
+ Math.sign(a.page.match(/\/\$/g)!.length - b.page.match(/\/\$/g)!.length)
)
}
private async run(
req: IncomingMessage,
res: ServerResponse,
- parsedUrl: UrlWithParsedQuery,
+ parsedUrl: UrlWithParsedQuery
) {
try {
const fn = this.router.match(req, res, parsedUrl)
@@ -350,7 +350,7 @@ export default class Server {
private async sendHTML(
req: IncomingMessage,
res: ServerResponse,
- html: string,
+ html: string
) {
const { generateEtags, poweredByHeader } = this.renderOpts
return sendHTML(req, res, html, { generateEtags, poweredByHeader })
@@ -361,7 +361,7 @@ export default class Server {
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {},
- parsedUrl?: UrlWithParsedQuery,
+ parsedUrl?: UrlWithParsedQuery
): Promise {
const url: any = req.url
if (isInternalUrl(url)) {
@@ -389,7 +389,7 @@ export default class Server {
private async findPageComponents(
pathname: string,
- query: ParsedUrlQuery = {},
+ query: ParsedUrlQuery = {}
) {
const serverless =
!this.renderOpts.dev && this.nextConfig.target === 'serverless'
@@ -400,7 +400,7 @@ export default class Server {
this.distDir,
this.buildId,
(pathname === '/' ? '/index' : pathname) + '.amp',
- serverless,
+ serverless
)
} catch (err) {
if (err.code !== 'ENOENT') throw err
@@ -410,7 +410,7 @@ export default class Server {
this.distDir,
this.buildId,
pathname,
- serverless,
+ serverless
)
}
@@ -420,7 +420,7 @@ export default class Server {
pathname: string,
query: ParsedUrlQuery = {},
result: LoadComponentsReturnType,
- opts: any,
+ opts: any
) {
// handle static page
if (typeof result.Component === 'string') {
@@ -450,22 +450,22 @@ export default class Server {
}: {
amphtml?: boolean
hasAmp?: boolean
- dataOnly?: boolean,
- } = {},
+ dataOnly?: boolean
+ } = {}
): Promise {
return this.findPageComponents(pathname, query)
.then(
- (result) => {
+ result => {
return this.renderToHTMLWithComponents(
req,
res,
pathname,
query,
result,
- { ...this.renderOpts, amphtml, hasAmp, dataOnly },
+ { ...this.renderOpts, amphtml, hasAmp, dataOnly }
)
},
- (err) => {
+ err => {
if (err.code !== 'ENOENT' || !this.dynamicRoutes) {
return Promise.reject(err)
}
@@ -477,22 +477,22 @@ export default class Server {
}
return this.findPageComponents(dynamicRoute.page, query).then(
- (result) =>
+ result =>
this.renderToHTMLWithComponents(
req,
res,
dynamicRoute.page,
{ ...query, ...params },
result,
- { ...this.renderOpts, amphtml, hasAmp, dataOnly },
- ),
+ { ...this.renderOpts, amphtml, hasAmp, dataOnly }
+ )
)
}
return Promise.reject(err)
- },
+ }
)
- .catch((err) => {
+ .catch(err => {
if (err && err.code === 'ENOENT') {
res.statusCode = 404
return this.renderErrorToHTML(null, req, res, pathname, query)
@@ -509,11 +509,11 @@ export default class Server {
req: IncomingMessage,
res: ServerResponse,
pathname: string,
- query: ParsedUrlQuery = {},
+ query: ParsedUrlQuery = {}
): Promise {
res.setHeader(
'Cache-Control',
- 'no-cache, no-store, max-age=0, must-revalidate',
+ 'no-cache, no-store, max-age=0, must-revalidate'
)
const html = await this.renderErrorToHTML(err, req, res, pathname, query)
if (html === null) {
@@ -527,7 +527,7 @@ export default class Server {
req: IncomingMessage,
res: ServerResponse,
_pathname: string,
- query: ParsedUrlQuery = {},
+ query: ParsedUrlQuery = {}
) {
const result = await this.findPageComponents('/_error', query)
return this.renderToHTMLWithComponents(req, res, '/_error', query, result, {
@@ -539,7 +539,7 @@ export default class Server {
public async render404(
req: IncomingMessage,
res: ServerResponse,
- parsedUrl?: UrlWithParsedQuery,
+ parsedUrl?: UrlWithParsedQuery
): Promise {
const url: any = req.url
const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(url, true)
@@ -554,7 +554,7 @@ export default class Server {
req: IncomingMessage,
res: ServerResponse,
path: string,
- parsedUrl?: UrlWithParsedQuery,
+ parsedUrl?: UrlWithParsedQuery
): Promise {
if (!this.isServeableUrl(path)) {
return this.render404(req, res, parsedUrl)
@@ -594,7 +594,7 @@ export default class Server {
throw new Error(
`Could not find a valid build in the '${
this.distDir
- }' directory! Try building your app with 'next build' before starting the server.`,
+ }' directory! Try building your app with 'next build' before starting the server.`
)
}
diff --git a/packages/next-server/server/optimize-amp.ts b/packages/next-server/server/optimize-amp.ts
index 86676943c59df..6457e5d617480 100644
--- a/packages/next-server/server/optimize-amp.ts
+++ b/packages/next-server/server/optimize-amp.ts
@@ -1,9 +1,9 @@
-import { ParsedUrlQuery } from "querystring"
+import { ParsedUrlQuery } from 'querystring'
interface IOptimizerConfig {
- transforms?: string[],
- validAmp?: boolean,
- verbose?: boolean,
+ transforms?: string[]
+ validAmp?: boolean
+ verbose?: boolean
}
interface IOptimizer {
@@ -16,7 +16,10 @@ interface IOptimizeOptions {
query?: ParsedUrlQuery
}
-export default async function optimize(html: string, { amphtml, query }: IOptimizeOptions): Promise {
+export default async function optimize(
+ html: string,
+ { amphtml, query }: IOptimizeOptions
+): Promise {
let ampOptimizer: IOptimizer
try {
ampOptimizer = require('amp-toolbox-optimizer')
diff --git a/packages/next-server/server/require.ts b/packages/next-server/server/require.ts
index 3db2aab76004d..f8bc3fc787ef3 100644
--- a/packages/next-server/server/require.ts
+++ b/packages/next-server/server/require.ts
@@ -1,7 +1,11 @@
import fs from 'fs'
-import {join} from 'path'
-import {promisify} from 'util'
-import {PAGES_MANIFEST, SERVER_DIRECTORY, SERVERLESS_DIRECTORY} from '../lib/constants'
+import { join } from 'path'
+import { promisify } from 'util'
+import {
+ PAGES_MANIFEST,
+ SERVER_DIRECTORY,
+ SERVERLESS_DIRECTORY,
+} from '../lib/constants'
import { normalizePagePath } from './normalize-page-path'
const readFile = promisify(fs.readFile)
@@ -12,8 +16,15 @@ export function pageNotFoundError(page: string): Error {
return err
}
-export function getPagePath(page: string, distDir: string, serverless: boolean): string {
- const serverBuildPath = join(distDir, serverless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY)
+export function getPagePath(
+ page: string,
+ distDir: string,
+ serverless: boolean
+): string {
+ const serverBuildPath = join(
+ distDir,
+ serverless ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
+ )
const pagesManifest = require(join(serverBuildPath, PAGES_MANIFEST))
try {
@@ -36,7 +47,11 @@ export function getPagePath(page: string, distDir: string, serverless: boolean):
return join(serverBuildPath, pagesManifest[page])
}
-export function requirePage(page: string, distDir: string, serverless: boolean): any {
+export function requirePage(
+ page: string,
+ distDir: string,
+ serverless: boolean
+): any {
const pagePath = getPagePath(page, distDir, serverless)
if (pagePath.endsWith('.html')) {
return readFile(pagePath, 'utf8')
diff --git a/packages/next-server/server/router.ts b/packages/next-server/server/router.ts
index 087c02b5752cc..446c48592bfc7 100644
--- a/packages/next-server/server/router.ts
+++ b/packages/next-server/server/router.ts
@@ -14,8 +14,8 @@ export type Route = {
req: IncomingMessage,
res: ServerResponse,
params: Params,
- parsedUrl: UrlWithParsedQuery,
- ) => void,
+ parsedUrl: UrlWithParsedQuery
+ ) => void
}
export default class Router {
@@ -31,7 +31,7 @@ export default class Router {
match(
req: IncomingMessage,
res: ServerResponse,
- parsedUrl: UrlWithParsedQuery,
+ parsedUrl: UrlWithParsedQuery
) {
const { pathname } = parsedUrl
for (const route of this.routes) {
diff --git a/packages/next-server/server/send-html.ts b/packages/next-server/server/send-html.ts
index 6fb5e955f70b4..a344a1c0d0c15 100644
--- a/packages/next-server/server/send-html.ts
+++ b/packages/next-server/server/send-html.ts
@@ -1,9 +1,17 @@
-import {IncomingMessage, ServerResponse} from 'http'
+import { IncomingMessage, ServerResponse } from 'http'
import generateETag from 'etag'
import fresh from 'fresh'
import { isResSent } from '../lib/utils'
-export function sendHTML(req: IncomingMessage, res: ServerResponse, html: string, { generateEtags, poweredByHeader }: {generateEtags: boolean, poweredByHeader: boolean}) {
+export function sendHTML(
+ req: IncomingMessage,
+ res: ServerResponse,
+ html: string,
+ {
+ generateEtags,
+ poweredByHeader,
+ }: { generateEtags: boolean; poweredByHeader: boolean }
+) {
if (isResSent(res)) return
const etag = generateEtags ? generateETag(html) : undefined
diff --git a/packages/next-server/server/serve-static.ts b/packages/next-server/server/serve-static.ts
index e96c593b32cfc..823cb1dfeef76 100644
--- a/packages/next-server/server/serve-static.ts
+++ b/packages/next-server/server/serve-static.ts
@@ -1,14 +1,18 @@
-import {IncomingMessage, ServerResponse} from 'http'
+import { IncomingMessage, ServerResponse } from 'http'
import send from 'send'
// since send doesn't support wasm yet
send.mime.define({ 'application/wasm': ['wasm'] })
-export function serveStatic(req: IncomingMessage, res: ServerResponse, path: string): Promise {
+export function serveStatic(
+ req: IncomingMessage,
+ res: ServerResponse,
+ path: string
+): Promise {
return new Promise((resolve, reject) => {
send(req, path)
.on('directory', () => {
- // We don't allow directories to be read.
+ // We don't allow directories to be read.
const err: any = new Error('No directory access')
err.code = 'ENOENT'
reject(err)
diff --git a/packages/next-server/server/utils.ts b/packages/next-server/server/utils.ts
index 94ff61d09d4ec..5e1a6be70d7e5 100644
--- a/packages/next-server/server/utils.ts
+++ b/packages/next-server/server/utils.ts
@@ -1,9 +1,6 @@
import { BLOCKED_PAGES } from '../lib/constants'
-const internalPrefixes = [
- /^\/_next\//,
- /^\/static\//,
-]
+const internalPrefixes = [/^\/_next\//, /^\/static\//]
export function isInternalUrl(url: string): boolean {
for (const prefix of internalPrefixes) {
@@ -16,7 +13,7 @@ export function isInternalUrl(url: string): boolean {
}
export function isBlockedPage(pathname: string): boolean {
- return (BLOCKED_PAGES.indexOf(pathname) !== -1)
+ return BLOCKED_PAGES.indexOf(pathname) !== -1
}
export function cleanAmpPath(pathname: string): string {
diff --git a/packages/next-server/taskfile-typescript.js b/packages/next-server/taskfile-typescript.js
index 87945a728359c..5f5c633d83aae 100644
--- a/packages/next-server/taskfile-typescript.js
+++ b/packages/next-server/taskfile-typescript.js
@@ -39,7 +39,13 @@ try {
}
// update file's data
- file.data = Buffer.from(result.outputText.replace(/process\.env\.__NEXT_VERSION/, `"${require('./package.json').version}"`), 'utf8')
+ file.data = Buffer.from(
+ result.outputText.replace(
+ /process\.env\.__NEXT_VERSION/,
+ `"${require('./package.json').version}"`
+ ),
+ 'utf8'
+ )
})
}
} catch (err) {
diff --git a/packages/next-server/taskfile.js b/packages/next-server/taskfile.js
index 1c7593ff0f418..bc24e77c9e874 100644
--- a/packages/next-server/taskfile.js
+++ b/packages/next-server/taskfile.js
@@ -1,12 +1,18 @@
const notifier = require('node-notifier')
export async function lib (task, opts) {
- await task.source(opts.src || 'lib/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/lib')
+ await task
+ .source(opts.src || 'lib/**/*.+(js|ts|tsx)')
+ .typescript({ module: 'commonjs' })
+ .target('dist/lib')
notify('Compiled lib files')
}
export async function server (task, opts) {
- await task.source(opts.src || 'server/**/*.+(js|ts|tsx)').typescript({ module: 'commonjs' }).target('dist/server')
+ await task
+ .source(opts.src || 'server/**/*.+(js|ts|tsx)')
+ .typescript({ module: 'commonjs' })
+ .target('dist/server')
notify('Compiled server files')
}
diff --git a/packages/next-server/tsconfig.json b/packages/next-server/tsconfig.json
index 681bfa21fefc2..f033b0dad1fa0 100644
--- a/packages/next-server/tsconfig.json
+++ b/packages/next-server/tsconfig.json
@@ -7,9 +7,5 @@
"moduleResolution": "node",
"jsx": "react"
},
- "exclude": [
- "./dist/**",
- "./*.d.ts",
- "./constants.d.ts"
- ]
+ "exclude": ["./dist/**", "./*.d.ts", "./constants.d.ts"]
}
diff --git a/packages/next-server/types/index.d.ts b/packages/next-server/types/index.d.ts
index c2848292bd9d5..56b4e1541cb8c 100644
--- a/packages/next-server/types/index.d.ts
+++ b/packages/next-server/types/index.d.ts
@@ -1 +1 @@
-declare module 'react-ssr-prepass'
\ No newline at end of file
+declare module 'react-ssr-prepass'
diff --git a/packages/next/README.md b/packages/next/README.md
index 630e69c39e8b8..2a0d73eed09ac 100644
--- a/packages/next/README.md
+++ b/packages/next/README.md
@@ -135,7 +135,6 @@ So far, we get:
- Server rendering and indexing of `./pages`
- Static file serving. `./static/` is mapped to `/static/` (given you [create a `./static/` directory](#static-file-serving-eg-images) inside your project)
-
### Automatic code splitting
Every `import` you declare gets bundled and served with each page. That means pages never load unnecessary code!
@@ -161,7 +160,6 @@ export default CowsayHi
-
We bundle [styled-jsx](https://github.com/zeit/styled-jsx) to provide support for isolated scoped CSS. The aim is to support "shadow CSS" similar to Web Components, which unfortunately [do not support server-rendering and are JS-only](https://github.com/w3c/webcomponents/issues/71).
```jsx
@@ -213,7 +211,6 @@ Please see the [styled-jsx documentation](https://www.npmjs.com/package/styled-j
-
It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles:
```jsx
@@ -268,7 +265,6 @@ _Note: Don't name the `static` or `public` directory anything else. The names ca
-
We expose a built-in component for appending elements to the `` of the page.
```jsx
@@ -335,7 +331,6 @@ _Note: `` and `` elements need to be contained as **direct** childr
-
When you need state, lifecycle hooks or **initial data population** you can export a `React.Component` (instead of a stateless function, like shown above):
```jsx
@@ -408,7 +403,6 @@ Next.js does not ship a routes manifest with every possible route in the applica
-
Client-side transitions between routes can be enabled via a `` component.
**Basic Example**
@@ -502,7 +496,6 @@ To inject the `pathname`, `query` or `asPath` in your component, you can use [wi
-
The component `` can also receive a URL object and it will automatically format it to create the URL string.
```jsx
@@ -611,7 +604,6 @@ The default behaviour of `` is to scroll to the top of the page. When ther
-
You can also do client-side page transitions using the `next/router`
```jsx
@@ -675,7 +667,7 @@ import Router from 'next/router'
const handler = () => {
Router.push({
pathname: '/about',
- query: { name: 'Zeit' }
+ query: { name: 'Zeit' },
})
}
@@ -741,7 +733,6 @@ Router.events.on('routeChangeError', (err, url) => {
-
Shallow routing allows you to change the URL without running `getInitialProps`. You'll receive the updated `pathname` and the `query` via the `router` prop (injected using [`withRouter`](#using-a-higher-order-component)), without losing state.
You can do this by invoking either `Router.push` or `Router.replace` with the `shallow: true` option. Here's an example:
@@ -786,7 +777,6 @@ componentDidUpdate(prevProps) {
-
If you want to access the `router` object inside any component in your app, you can use the `withRouter` Higher-Order Component. Here's how to use it:
```jsx
@@ -795,7 +785,7 @@ import { withRouter } from 'next/router'
function ActiveLink({ children, router, href }) {
const style = {
marginRight: 10,
- color: router.pathname === href ? 'red' : 'black'
+ color: router.pathname === href ? 'red' : 'black',
}
const handleClick = e => {
@@ -826,7 +816,6 @@ The above `router` object comes with an API similar to [`next/router`](#imperati
-
Next.js has an API which allows you to prefetch pages.
Since Next.js server-renders your pages, this allows all the future interaction paths of your app to be instant. Effectively Next.js gives you the great initial download performance of a _website_, with the ahead-of-time download capabilities of an _app_. [Read more](https://zeit.co/blog/next#anticipation-is-the-key-to-performance).
@@ -933,7 +922,6 @@ export default withRouter(MyLink)
-
Typically you start your next server with `next start`. It's possible, however, to start a server 100% programmatically in order to customize routes, use route patterns, etc.
When using a custom server with a server file, for example called `server.js`, make sure you update the scripts key in `package.json` to:
@@ -1007,7 +995,7 @@ To disable this behavior & prevent routing based on files in `/pages`, simply se
```js
// next.config.js
module.exports = {
- useFileSystemPublicRoutes: false
+ useFileSystemPublicRoutes: false,
}
```
@@ -1064,7 +1052,6 @@ app.prepare().then(() => {
-
Next.js supports TC39 [dynamic import proposal](https://github.com/tc39/proposal-dynamic-import) for JavaScript.
With that, you could import JavaScript modules (inc. React Components) dynamically and work with them.
@@ -1130,7 +1117,7 @@ import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/hello2'),
{
- loading: () =>
...
+ loading: () =>
...
,
}
)
@@ -1155,7 +1142,7 @@ import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(
() => import('../components/hello3'),
{
- ssr: false
+ ssr: false,
}
)
@@ -1181,7 +1168,7 @@ const HelloBundle = dynamic({
modules: () => {
const components = {
Hello1: () => import('../components/hello1'),
- Hello2: () => import('../components/hello2')
+ Hello2: () => import('../components/hello2'),
}
return components
@@ -1192,7 +1179,7 @@ const HelloBundle = dynamic({
- )
+ ),
})
function DynamicBundle() {
@@ -1212,7 +1199,6 @@ export default DynamicBundle
-
Next.js uses the `App` component to initialize pages. You can override it and control the page initialization. Which allows you to do amazing things like:
- Persisting layout between page changes
@@ -1261,7 +1247,6 @@ export default MyApp
-
- Is rendered on the server side
- Is used to change the initial server side rendered document markup
- Commonly used to implement server side rendering for css-in-js libraries like [styled-components](/examples/with-styled-components) or [emotion](/examples/with-emotion). [styled-jsx](https://github.com/zeit/styled-jsx) is included with Next.js by default.
@@ -1326,7 +1311,7 @@ class MyDocument extends Document {
// useful for wrapping the whole react tree
enhanceApp: App => App,
// useful for wrapping in a per-page basis
- enhanceComponent: Component => Component
+ enhanceComponent: Component => Component,
})
// Run the parent `getInitialProps` using `ctx` that now includes our custom `renderPage`
@@ -1450,7 +1435,7 @@ You can specify a name to use for a custom build directory. For example, the fol
```js
// next.config.js
module.exports = {
- distDir: 'build'
+ distDir: 'build',
}
```
@@ -1461,7 +1446,7 @@ You can disable etag generation for HTML pages depending on your cache strategy.
```js
// next.config.js
module.exports = {
- generateEtags: false
+ generateEtags: false,
}
```
@@ -1475,8 +1460,8 @@ module.exports = {
// period (in ms) where the server will keep pages in the buffer
maxInactiveAge: 25 * 1000,
// number of pages that should be kept simultaneously without being disposed
- pagesBufferLength: 2
- }
+ pagesBufferLength: 2,
+ },
}
```
@@ -1489,7 +1474,7 @@ Aimed at modules like [`@next/mdx`](https://github.com/zeit/next.js/tree/canary/
```js
// next.config.js
module.exports = {
- pageExtensions: ['mdx', 'jsx', 'js']
+ pageExtensions: ['mdx', 'jsx', 'js'],
}
```
@@ -1503,7 +1488,7 @@ module.exports = {
generateBuildId: async () => {
// For example get the latest git commit hash here
return 'my-build-id'
- }
+ },
}
```
@@ -1518,7 +1503,7 @@ module.exports = {
}
return null
- }
+ },
}
```
@@ -1541,7 +1526,6 @@ NODE_OPTIONS="--inspect" next
-
Some commonly asked for features are available as modules:
- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css)
@@ -1563,7 +1547,7 @@ module.exports = withMDX(
webpack(config, options) {
// Further custom configuration here
return config
- }
+ },
})
)
```
@@ -1580,16 +1564,14 @@ module.exports = {
// Important: return the modified config
// Example using webpack option
- config.plugins.push(
- new webpack.IgnorePlugin(/\/__tests__\//),
- )
+ config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
return config
},
webpackDevMiddleware: config => {
// Perform customizations to webpack dev middleware config
// Important: return the modified config
return config
- }
+ },
}
```
@@ -1616,13 +1598,13 @@ module.exports = {
options.defaultLoaders.babel,
{
loader: '@mdx-js/loader',
- options: pluginOptions.options
- }
- ]
+ options: pluginOptions.options,
+ },
+ ],
})
return config
- }
+ },
}
```
@@ -1635,7 +1617,6 @@ module.exports = {
-
In order to extend our usage of `babel`, you can simply define a `.babelrc` file at the root of your app. This file is optional.
If found, we're going to consider it the _source of truth_, therefore it needs to define what next needs as well, which is the `next/babel` preset.
@@ -1700,8 +1681,8 @@ You can add the `env` key in `next.config.js`:
// next.config.js
module.exports = {
env: {
- customKey: 'value'
- }
+ customKey: 'value',
+ },
}
```
@@ -1715,24 +1696,24 @@ function Index() {
export default Index
```
+
> **Warning:** Note that it is not possible to destructure process.env variables due to the webpack `DefinePlugin` replacing process.env.XXXX inline at build time
```js
// Will not work
-const { CUSTOM_KEY, CUSTOM_SECRET } = process.env;
-AuthMethod({ key: CUSTOM_KEY, secret: CUSTOM_SECRET });
+const { CUSTOM_KEY, CUSTOM_SECRET } = process.env
+AuthMethod({ key: CUSTOM_KEY, secret: CUSTOM_SECRET })
// Will work as replaced inline
-AuthMethod({ key: process.env.CUSTOM_KEY, secret: process.env.CUSTOM_SECRET });
+AuthMethod({ key: process.env.CUSTOM_KEY, secret: process.env.CUSTOM_SECRET })
```
-
#### Runtime configuration
> **Warning:** Note that this option is not available when using `target: 'serverless'`
> **Warning:** Generally you want to use build-time configuration to provide your configuration.
-The reason for this is that runtime configuration adds a small rendering / initialization overhead.
+> The reason for this is that runtime configuration adds a small rendering / initialization overhead.
The `next/config` module gives your app access to the `publicRuntimeConfig` and `serverRuntimeConfig` stored in your `next.config.js`.
@@ -1746,12 +1727,12 @@ module.exports = {
serverRuntimeConfig: {
// Will only be available on the server side
mySecret: 'secret',
- secondSecret: process.env.SECOND_SECRET // Pass through env variables
+ secondSecret: process.env.SECOND_SECRET, // Pass through env variables
},
publicRuntimeConfig: {
// Will be available on both server and client
- staticFolder: '/static'
- }
+ staticFolder: '/static',
+ },
}
```
@@ -1787,7 +1768,7 @@ To set up a CDN, you can set up the `assetPrefix` setting and configure your CDN
const isProd = process.env.NODE_ENV === 'production'
module.exports = {
// You may only need to add assetPrefix in the production.
- assetPrefix: isProd ? 'https://cdn.mydomain.com' : ''
+ assetPrefix: isProd ? 'https://cdn.mydomain.com' : '',
}
```
@@ -1798,7 +1779,7 @@ If your CDN is on a separate domain and you would like assets to be requested us
```js
// next.config.js
module.exports = {
- crossOrigin: 'anonymous'
+ crossOrigin: 'anonymous',
}
```
@@ -1839,7 +1820,7 @@ To enable **serverless mode** in Next.js, add the `serverless` build `target` in
```js
// next.config.js
module.exports = {
- target: 'serverless'
+ target: 'serverless',
}
```
@@ -1956,45 +1937,43 @@ export default Page
To enable AMP support for a page, first enable experimental AMP support in your `next.config.js` and then import `withAmp` from `next/amp` and wrap your page's component in it.
### AMP First Page
+
```js
// pages/about.js
import { withAmp } from 'next/amp'
export default withAmp(function AboutPage(props) {
- return (
-