Skip to content

Instantly share code, notes, and snippets.

@inouetakuya
Last active March 1, 2019 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inouetakuya/4b231c5e634e5e7d0f80856d3eb3691d to your computer and use it in GitHub Desktop.
Save inouetakuya/4b231c5e634e5e7d0f80856d3eb3691d to your computer and use it in GitHub Desktop.
Nuxt 公式ドキュメント翻訳 2019 春の陣の翻訳対象
diff --git a/en/api/components-no-ssr.md b/en/api/components-no-ssr.md
index 1be8149..21536a7 100644
--- a/en/api/components-no-ssr.md
+++ b/en/api/components-no-ssr.md
@@ -43,6 +43,4 @@ description: Skip component rendering on server side(rendering), and display pla
</template>
```
-> Note that `<no-ssr />` can only contain at most ONE child component/element.
-
This component is a clone of [egoist/vue-no-ssr](https://github.com/egoist/vue-no-ssr). Thanks [@egoist](https://github.com/egoist)!
diff --git a/en/api/components-nuxt-child.md b/en/api/components-nuxt-child.md
index ed705fc..b3f9fc8 100644
--- a/en/api/components-nuxt-child.md
+++ b/en/api/components-nuxt-child.md
@@ -46,6 +46,40 @@ To display the `child.vue` component, we have to insert `<nuxt-child/>` inside `
</template>
```
+`<nuxt-child/>` accepts `keep-alive` and `keep-alive-props`:
+
+```html
+<template>
+ <div>
+ <nuxt-child keep-alive :keep-alive-props="{ exclude: ['modal'] }" />
+ </div>
+</template>
+
+<!-- will be converted into something like this -->
+<div>
+ <keep-alive :exclude="['modal']">
+ <router-view />
+ </keep-alive>
+</div>
+```
+
> Child components can also receive properties like a regular Vue component.
To see an example, take a look at the [nested-routes example](/examples/nested-routes).
+
+## Named View
+
+> Introduced with Nuxt v2.4.0
+
+`<nuxt-child/>` accepts `name` prop to render named-view:
+
+```html
+<template>
+ <div>
+ <nuxt-child name="top" />
+ <nuxt-child />
+ </div>
+</template>
+```
+
+To see an example, take a look at the [named-views example](/examples/named-views).
diff --git a/en/api/components-nuxt-link.md b/en/api/components-nuxt-link.md
index 3642443..2a2aff9 100644
--- a/en/api/components-nuxt-link.md
+++ b/en/api/components-nuxt-link.md
@@ -5,9 +5,9 @@ description: Link the pages between them with nuxt-link.
# The &lt;nuxt-link&gt; Component
-> This component is used to link the page components between them.
+> This component is used to provide navigations between page components.
-At the moment, `<nuxt-link>` is the same as [`<router-link>`](https://router.vuejs.org/en/api/router-link.html), so we recommend you to see how to use it on the [Vue Router documentation](https://router.vuejs.org/en/api/router-link.html).
+The `<nuxt-link>` component is an essential of Nuxt. It **should be used to navigate** through your application, similar to the `<router-link>` component in a traditional Vue App. In fact, `<nuxt-link>` is a wrapper component for [`<router-link>`](https://router.vuejs.org/api/#router-link). That means it takes the same properties and can be used in the same manner. Read the [Vue Router documentation](https://router.vuejs.org/api/#router-link) for more information.
Example (`pages/index.vue`):
@@ -15,7 +15,8 @@ Example (`pages/index.vue`):
<template>
<div>
<h1>Home page</h1>
- <nuxt-link to="/about">About</nuxt-link>
+ <nuxt-link to="/about">About (internal link that belongs to the Nuxt App)</nuxt-link>
+ <a href="https://nuxtjs.org">External Link to another page</a>
</div>
</template>
```
diff --git a/en/api/components-nuxt.md b/en/api/components-nuxt.md
index 81268d3..2e094d9 100644
--- a/en/api/components-nuxt.md
+++ b/en/api/components-nuxt.md
@@ -8,6 +8,7 @@ description: Display the page components inside a layout.
> This component is used only in [layouts](/guide/views#layouts) to display the page components.
**Props**:
+
- nuxtChildKey: `string`
- This prop will be set to `<router-view/>`, useful to make transitions inside a dynamic page and different route.
- Default: `$route.fullPath`
@@ -25,3 +26,9 @@ Example (`layouts/default.vue`):
```
To see an example, take a look at the [layouts example](/examples/layouts).
+
+- name: `string` (_introduced with Nuxt v2.4.0_)
+ - This prop will be set to `<router-view/>`, used to render named-view of page component.
+ - Default: `default`
+
+To see an example, take a look at the [named-views example](/examples/named-views).
diff --git a/en/api/configuration-build.md b/en/api/configuration-build.md
index a27f603..7993428 100644
--- a/en/api/configuration-build.md
+++ b/en/api/configuration-build.md
@@ -19,7 +19,7 @@ If an object, see available properties [here](https://github.com/webpack-contrib
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
analyze: true,
// or
@@ -30,7 +30,11 @@ module.exports = {
}
```
-<p class="Alert Alert--teal">**Info:** you can use the command `nuxt build --analyze` or `nuxt build -a` to build your application and launch the bundle analyzer on [http://localhost:8888](http://localhost:8888).</p>
+<div class="Alert Alert--teal">
+
+**Info:** you can use the command `nuxt build --analyze` or `nuxt build -a` to build your application and launch the bundle analyzer on [http://localhost:8888](http://localhost:8888).
+
+</div>
## babel
@@ -41,14 +45,14 @@ module.exports = {
```js
{
- presets: ['vue-app']
+ presets: ['@nuxt/babel-preset-app']
}
```
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
babel: {
presets: ['es2015', 'stage-0']
@@ -62,7 +66,7 @@ module.exports = {
- Type: `Boolean`
- Default: `false`
-> Enable cache of [uglifyjs-webpack-plugin ](https://github.com/webpack-contrib/uglifyjs-webpack-plugin#options) and [cache-loader](https://github.com/webpack-contrib/cache-loader#cache-loader)
+> Enable cache of [terser-webpack-plugin ](https://github.com/webpack-contrib/terser-webpack-plugin#options) and [cache-loader](https://github.com/webpack-contrib/cache-loader#cache-loader)
## cssSourceMap
@@ -85,13 +89,23 @@ See [webpack-dev-middleware](https://github.com/webpack/webpack-dev-middleware)
The extend is called twice, one time for the server bundle, and one time for the client bundle. The arguments of the method are:
-1. webpack config object,
-2. object with the following keys (all boolean): `isDev`, `isClient`, `isServer`, `loaders`.
+1. The Webpack config object,
+2. An object with the following keys (all boolean except `loaders`): `isDev`, `isClient`, `isServer`, `loaders`.
+
+
+<div class="Alert Alert--orange">
+
+ **Warning:**
+ The `isClient` and `isServer` keys provided in are separate from the keys available in [`context`](/api/context).
+ They are **not** deprecated. Do not use `process.client` and `process.server` here as they are `undefined` at this point.
+
+</div>
+
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
extend (config, { isClient }) {
// Extend only webpack config for client-bundle
@@ -103,7 +117,7 @@ module.exports = {
}
```
-If you want to see more about our default webpack configuration, take a look at our [webpack directory](https://github.com/nuxt/nuxt.js/tree/master/lib/builder/webpack).
+If you want to see more about our default webpack configuration, take a look at our [webpack directory](https://github.com/nuxt/nuxt.js/tree/dev/packages/webpack/src/config).
### loaders in extend
@@ -112,7 +126,7 @@ If you want to see more about our default webpack configuration, take a look at
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
extend (config, { isClient, loaders: { vue } }) {
// Extend only webpack config for client-bundle
@@ -131,7 +145,14 @@ module.exports = {
- Type: `Boolean`
- Default: `false`
-Using `extract-text-webpack-plugin` to extract the CSS in the main chunk into a separate CSS file (auto injected with template), which allows the file to be individually cached. This is recommended when there is a lot of shared CSS. CSS inside async components will remain inlined as JavaScript strings and handled by vue-style-loader.
+Using [`mini-extract-css-plugin`](https://github.com/webpack-contrib/mini-css-extract-plugin) under the hood, all your CSS will be extracted into separate files, usually one per component. This allows caching your CSS and JavaScript separately and is worth a try in case you have a lot of global or shared CSS.
+
+<div class="Alert Alert--teal">
+
+**Note:** There was a bug prior to Vue 2.5.18 that removed critical CSS imports when using this options.
+
+</div>
+
## filenames
@@ -144,7 +165,7 @@ Using `extract-text-webpack-plugin` to extract the CSS in the main chunk into a
{
app: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js',
chunk: ({ isDev }) => isDev ? '[name].js' : '[chunkhash].js',
- css: ({ isDev }) => isDev ? '[name].js' : '[contenthash].css',
+ css: ({ isDev }) => isDev ? '[name].css' : '[contenthash].css',
img: ({ isDev }) => isDev ? '[path][name].[ext]' : 'img/[hash:7].[ext]',
font: ({ isDev }) => isDev ? '[path][name].[ext]' : 'fonts/[hash:7].[ext]',
video: ({ isDev }) => isDev ? '[path][name].[ext]' : 'videos/[hash:7].[ext]'
@@ -154,7 +175,7 @@ Using `extract-text-webpack-plugin` to extract the CSS in the main chunk into a
This example changes fancy chunk names to numerical ids (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
filenames: {
chunk: ({ isDev }) => isDev ? '[name].js' : '[id].[chunkhash].js'
@@ -163,7 +184,7 @@ module.exports = {
}
```
-To understand a bit more about the use of manifest and vendor, take a look at this [webpack documentation](https://webpack.js.org/guides/code-splitting-libraries/).
+To understand a bit more about the use of manifests, take a look at this [webpack documentation](https://webpack.js.org/guides/code-splitting-libraries/).
## hotMiddleware
@@ -171,6 +192,30 @@ To understand a bit more about the use of manifest and vendor, take a look at th
See [webpack-hot-middleware](https://github.com/glenjamin/webpack-hot-middleware) for available options.
+## html.minify
+
+- Type: `Object`
+- Default:
+
+```js
+{
+ collapseBooleanAttributes: true,
+ decodeEntities: true,
+ minifyCSS: true,
+ minifyJS: true,
+ processConditionalComments: true,
+ removeEmptyAttributes: true,
+ removeRedundantAttributes: true,
+ trimCustomFragments: true,
+ useShortDoctype: true
+}
+```
+
+**Attention:** If you make changes to `html.minify`, they won't be merged with the defaults!
+
+Configuration for the [html-minifier](https://github.com/kangax/html-minifier) plugin used to minify
+HTML files created during the build process (will be applied for *all modes*).
+
## loaders
> Customize options of Nuxt.js integrated webpack loaders.
@@ -249,6 +294,11 @@ See [webpack-hot-middleware](https://github.com/glenjamin/webpack-hot-middleware
```js
{
+ minimize: true,
+ minimizer: [
+ // terser-webpack-plugin
+ // optimize-css-assets-webpack-plugin
+ ],
splitChunks: {
chunks: 'all',
automaticNameDelimiter: '.',
@@ -260,7 +310,21 @@ See [webpack-hot-middleware](https://github.com/glenjamin/webpack-hot-middleware
The default value of `splitChunks.name` is `true` in `dev` or `analyze` mode.
-webpack [optimization](https://webpack.js.org/configuration/optimization/)
+You can set `minimizer` to a customized Array of plugins or set `minimize` to `false` to disable all minimizers.
+(`minimize` is being disabled for development by default)
+
+See [Webpack Optimization](https://webpack.js.org/configuration/optimization).
+
+## optimizeCSS
+
+- Type: `Object` or `Boolean`
+- Default:
+ - `false`
+ - `{}` when extractCSS is enabled
+
+OptimizeCSSAssets plugin options.
+
+See [NMFR/optimize-css-assets-webpack-plugin](https://github.com/NMFR/optimize-css-assets-webpack-plugin).
## parallel
@@ -279,13 +343,13 @@ webpack [optimization](https://webpack.js.org/configuration/optimization/)
Example (`nuxt.config.js`):
```js
-const webpack = require('webpack')
-
-module.exports = {
+import webpack from 'webpack'
+import { version } from './package.json'
+export default {
build: {
plugins: [
new webpack.DefinePlugin({
- 'process.VERSION': require('./package.json').version
+ 'process.VERSION': version
})
]
}
@@ -296,9 +360,10 @@ module.exports = {
> Customize [PostCSS Loader](https://github.com/postcss/postcss-loader#usage) plugins.
-- Type: `Array`, `Object` (recommended), `Function` or `Boolean`
+- Type: `Array` (legacy, will override defaults), `Object` (recommended), `Function` or `Boolean`
+
+ **Note:** Nuxt.js has applied [PostCSS Preset Env](https://github.com/csstools/postcss-preset-env). By default it enables [Stage 2 features](https://cssdb.org/) and [Autoprefixer](https://github.com/postcss/autoprefixer), you can use `build.postcss.preset` to configure it.
- **Note:** Nuxt.js has applied [PostCSS Preset Env](https://github.com/csstools/postcss-preset-env). By default it enables [Stage 2 features](https://cssdb.org/) and [Autoprefixer](https://github.com/postcss/autoprefixer), you can use `build.postcss.preset` to config it.
- Default:
```js
@@ -308,14 +373,17 @@ module.exports = {
'postcss-url': {},
'postcss-preset-env': {},
'cssnano': { preset: 'default' } // disabled in dev mode
- }
+ },
+ order: 'cssnanoLast'
}
```
+Your custom plugin settings will be merged with the default plugins (unless you are using an `Array` instead of an `Object`).
+
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
postcss: {
plugins: {
@@ -336,6 +404,28 @@ module.exports = {
}
```
+If the postcss configuration is an `Object`, `order` can be used for defining the plugin order:
+
+- Type: `Array` (ordered plugin names), `String` (order preset name), `Function`
+- Default: `cssnanoLast` (put `cssnano` in last)
+
+Example (`nuxt.config.js`):
+
+```js
+export default {
+ build: {
+ postcss: {
+ // preset name
+ order: 'cssnanoLast',
+ // ordered plugin names
+ order: ['postcss-import', 'postcss-preset-env', 'cssnano']
+ // Function to calculate plugin order
+ order: (names, presets) => presets.cssnanoLast(names)
+ }
+ }
+}
+```
+
## profile
- Type: `Boolean`
@@ -353,7 +443,7 @@ module.exports = {
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
publicPath: 'https://cdn.nuxtjs.org'
}
@@ -362,6 +452,13 @@ module.exports = {
Then, when launching `nuxt build`, upload the content of `.nuxt/dist/client` directory to your CDN and voilà!
+## quiet
+
+> Suppresses most of the build output log
+
+- Type: `Boolean`
+- Default: Enabled when a `CI` or `test` environment is detected by [std-env](https://github.com/blindmedia/std-env)
+
## splitChunks
- Type: `Object`
@@ -392,13 +489,19 @@ This option is automatically set based on `mode` value if not provided.
- Type: `Object`
- Default: `{}`
+<div class="Alert Alert--orange">
+
+**Warning:** This property is deprecated. Please use the [style-resources-modules](https://github.com/nuxt-community/style-resources-module/) instead for improved performance and better DX!
+
+</div>
+
This is useful when you need to inject some variables and mixins in your pages without having to import them every time.
Nuxt.js uses https://github.com/yenshih/style-resources-loader to achieve this behaviour.
You need to specify the patterns/path you want to include for the given pre-processors: `less`, `sass`, `scss` or `stylus`
-:warning: You cannot use path aliases here (`~` and `@`), you need to use relative or absolute paths.
+You cannot use path aliases here (`~` and `@`), you need to use relative or absolute paths.
`nuxt.config.js`:
@@ -428,7 +531,7 @@ You need to specify the patterns/path you want to include for the given pre-proc
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
build: {
templates: [
{
@@ -445,44 +548,44 @@ module.exports = {
Templates are rendered using [`lodash.template`](https://lodash.com/docs/#template) you can learn more about using them [here](https://github.com/learn-co-students/javascript-lodash-templates-v-000).
-## transpile
-
-- Type: `Array<string | RegExp>`
-- Default: `[]`
-
-If you want to transpile specific dependencies with Babel, you can add them in `build.transpile`. Item in transpile can be string or regex object for matching dependencies file name.
-
-## vendor
-
-> Nuxt.js lets you add modules inside the `vendor.bundle.js` file to reduce the size of the application bundle. This is especially helpful when using external modules (like `axios` for example).
-
-- Type: `Array`
+## terser
-To add a module/file inside the vendor bundle, add the `build.vendor` key inside `nuxt.config.js`:
+- Type: `Object` or `Boolean`
+- Default:
```js
-module.exports = {
- build: {
- vendor: ['axios']
+{
+ parallel: true,
+ cache: false,
+ sourceMap: false,
+ extractComments: {
+ filename: 'LICENSES'
+ },
+ terserOptions: {
+ output: {
+ comments: /^\**!|@preserve|@license|@cc_on/
+ }
}
}
```
-You can also give a path to a file, like a custom lib you created:
+Terser plugin options. Set to `false` to disable this plugin.
-```js
-module.exports = {
- build: {
- vendor: [
- 'axios',
- '~/plugins/my-lib.js'
- ]
- }
-}
-```
+`sourceMap` will be enabled when webpack `config.devtool` matches `source-?map`
+
+See [webpack-contrib/terser-webpack-plugin](https://github.com/webpack-contrib/terser-webpack-plugin).
+
+## transpile
+
+- Type: `Array<string | RegExp>`
+- Default: `[]`
+
+If you want to transpile specific dependencies with Babel, you can add them in `build.transpile`. Each item in transpile can be a package name, or a string or regex object matching the dependency's file name.
## vueLoader
+> Note: This config has been removed since Nuxt 2.0, please use [`build.loaders.vue`](#loaders)instead.
+
- Type: `Object`
- Default:
@@ -507,7 +610,7 @@ module.exports = {
- Type: `Array<String>`
```js
-module.exports = {
+export default {
build: {
watch: [
'~/.nuxt/support.js'
diff --git a/en/api/configuration-builddir.md b/en/api/configuration-builddir.md
index 57489cd..df0cf5c 100644
--- a/en/api/configuration-builddir.md
+++ b/en/api/configuration-builddir.md
@@ -13,7 +13,7 @@ description: Define the dist directory for your Nuxt.js application
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
buildDir: 'nuxt-dist'
}
```
diff --git a/en/api/configuration-css.md b/en/api/configuration-css.md
index 4190311..ba4ce7d 100644
--- a/en/api/configuration-css.md
+++ b/en/api/configuration-css.md
@@ -19,7 +19,7 @@ npm install --save-dev node-sass sass-loader
In `nuxt.config.js`, add the CSS resources:
```js
-module.exports = {
+export default {
css: [
// Load a Node.js module directly (here it's a Sass file)
'bulma',
diff --git a/en/api/configuration-dev.md b/en/api/configuration-dev.md
index 744091c..fdfbb6b 100644
--- a/en/api/configuration-dev.md
+++ b/en/api/configuration-dev.md
@@ -22,7 +22,7 @@ Example:
`nuxt.config.js`
```js
-module.exports = {
+export default {
dev: (process.env.NODE_ENV !== 'production')
}
```
@@ -42,15 +42,11 @@ app.use(nuxt.render)
// Build only in dev mode
if (config.dev) {
new Builder(nuxt).build()
- .catch((error) => {
- console.error(error)
- process.exit(1)
- })
}
// Listen the server
app.listen(port, '0.0.0.0').then(() => {
- nuxt.showOpen()
+ console.log(`Server is listening on port: ${port}`)
})
```
diff --git a/en/api/configuration-dir.md b/en/api/configuration-dir.md
index 82de6e1..728b368 100644
--- a/en/api/configuration-dir.md
+++ b/en/api/configuration-dir.md
@@ -24,7 +24,7 @@ description: Define the custom directories for your Nuxt.js application
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
dir: {
assets: 'custom-assets',
layouts: 'custom-layouts',
diff --git a/en/api/configuration-env.md b/en/api/configuration-env.md
index 95a62bd..d377f9c 100644
--- a/en/api/configuration-env.md
+++ b/en/api/configuration-env.md
@@ -12,7 +12,7 @@ description: Share environment variables between client and server.
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
@@ -21,12 +21,12 @@ module.exports = {
This lets you create a `baseUrl` property that will be equal to the `BASE_URL` environment variable if defined, otherwise, equal to `'http://localhost:3000'`.
-Then, I can access my `baseUrl` variable with 2 ways:
+Then, I can access my `baseUrl` variable in 2 ways:
1. Via `process.env.baseUrl`.
2. Via `context.env.baseUrl`, see [context API](/api/context).
-You can use the `env` property for giving public token for example.
+You can use the `env` property for giving a public token for example.
For the example above, we can use it to configure [axios](https://github.com/mzabriskie/axios).
@@ -48,18 +48,18 @@ If you define environment variables starting with `NUXT_ENV_` in the build phase
## process.env == {}
-Note that Nuxt uses webpack's `definePlugin` to define the environmental variable. This means that the actual `process` or `process.env` from Node.js is neither available nor defined. Each of the env properties defined in nuxt.config.js is individually mapped to `process.env.xxxx` and converted during compilation.
+Note that Nuxt uses webpack's `definePlugin` to define the environmental variable. This means that the actual `process` or `process.env` from Node.js is neither available nor defined. Each of the `env` properties defined in nuxt.config.js is individually mapped to `process.env.xxxx` and converted during compilation.
Meaning, `console.log(process.env)` will output `{}` but `console.log(process.env.you_var)` will still output your value. When webpack compiles your code, it replaces all instances of `process.env.your_var` to the value you've set it to. ie: `env.test = 'testing123'`. If you use `process.env.test` in your code somewhere, it is actually translated to 'testing123'.
before
-```
+```js
if (process.env.test == 'testing123')
```
after
-```
+```js
if ('testing123' == 'testing123')
```
diff --git a/en/api/configuration-generate.md b/en/api/configuration-generate.md
index e66f53f..90e7e0a 100644
--- a/en/api/configuration-generate.md
+++ b/en/api/configuration-generate.md
@@ -34,33 +34,8 @@ Interval between two render cycles to avoid flooding a potential API with API ca
## minify
-- Type: `Object`
-- Default:
-
-```js
-minify: {
- collapseBooleanAttributes: true,
- collapseWhitespace: false,
- decodeEntities: true,
- minifyCSS: true,
- minifyJS: true,
- processConditionalComments: true,
- removeAttributeQuotes: false,
- removeComments: false,
- removeEmptyAttributes: true,
- removeOptionalTags: false,
- removeRedundantAttributes: true,
- removeScriptTypeAttributes: false,
- removeStyleLinkTypeAttributes: false,
- removeTagWhitespace: false,
- sortAttributes: true,
- sortClassName: false,
- trimCustomFragments: true,
- useShortDoctype: true
-}
-```
-
-You can change the default configuration of [html-minifier](https://github.com/kangax/html-minifier) used by Nuxt.js to minify HTML files created during generation.
+- **Deprecated!**
+- Use [build.html.minify](/api/configuration-build#html-minify) instead
## routes
@@ -84,7 +59,7 @@ If you want Nuxt.js to generate routes with dynamic params, you need to set an a
We add routes for `/users/:id` in `nuxt.config.js`:
```js
-module.exports = {
+export default {
generate: {
routes: [
'/users/1',
@@ -122,9 +97,9 @@ Great, but what if we have **dynamic params**?
`nuxt.config.js`
```js
-const axios = require('axios')
+import axios from 'axios'
-module.exports = {
+export default {
generate: {
routes: function () {
return axios.get('https://my-api/users')
@@ -143,14 +118,14 @@ module.exports = {
`nuxt.config.js`
```js
-const axios = require('axios')
+import axios from 'axios'
-module.exports = {
+export default {
generate: {
routes: function (callback) {
axios.get('https://my-api/users')
.then((res) => {
- var routes = res.data.map((user) => {
+ const routes = res.data.map((user) => {
return '/users/' + user.id
})
callback(null, routes)
@@ -168,9 +143,9 @@ In the example above, we're using the `user.id` from the server to generate the
`nuxt.config.js`
```js
-const axios = require('axios')
+import axios from 'axios'
-module.exports = {
+export default {
generate: {
routes: function () {
return axios.get('https://my-api/users')
diff --git a/en/api/configuration-global-name.md b/en/api/configuration-global-name.md
new file mode 100644
index 0000000..a693db5
--- /dev/null
+++ b/en/api/configuration-global-name.md
@@ -0,0 +1,42 @@
+---
+title: "API: The globalName Property"
+description: Nuxt.js lets you customize the global ID used in the main HTML template as well as the main Vue instance name and other options.
+---
+
+# The globalName Property
+
+> Nuxt.js lets you customize the global ID used in the main HTML template as well as the main Vue instance name and other options.
+
+- Type: `String`
+- Default: `nuxt`
+
+Example:
+
+`nuxt.config.js`
+
+```js
+{
+ globalName: 'myCustomName'
+}
+```
+
+It needs to be a valid JavaScript identifier.
+
+## The globals property
+
+> Customizes specific global names which are based on `globalName` by default.
+
+- Type: `Object`
+- Default:
+
+```js
+{
+ id: globalName => `__${globalName}`,
+ nuxt: globalName => `$${globalName}`,
+ context: globalName => `__${globalName.toUpperCase()}__`,
+ pluginPrefix: globalName => globalName,
+ readyCallback: globalName => `on${_.capitalize(globalName)}Ready`,
+ loadedCallback: globalName => `_on${_.capitalize(globalName)}Loaded`
+},
+```
+
diff --git a/en/api/configuration-head.md b/en/api/configuration-head.md
index 3cf1e5c..39e5a72 100644
--- a/en/api/configuration-head.md
+++ b/en/api/configuration-head.md
@@ -5,17 +5,20 @@ description: Nuxt.js let you define all default meta for your application inside
# The head Property
-> Nuxt.js let you define all default meta for your application inside `nuxt.config.js`, use the same `head` property:
+> Nuxt.js let you define all default meta for your application inside `nuxt.config.js`, use the same `head` property
- Type: `Object`
+An example `nuxt.config.js`:
```js
-module.exports = {
+export default {
head: {
titleTemplate: '%s - Nuxt.js',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
+
+ // hid is used as unique identifier. Do not use `vmid` for it as it will not work
{ hid: 'description', name: 'description', content: 'Meta description' }
]
}
@@ -24,4 +27,10 @@ module.exports = {
To know the list of options you can give to `head`, take a look at [vue-meta documentation](https://github.com/declandewet/vue-meta#recognized-metainfo-properties).
-<p class="Alert Alert--teal"><b>INFO:</b> You can also use `head` in the page components and access to the component data through `this`, see [component head property](/api/pages-head).</p>
+You can also use `head` in your components and access to the component data through `this` ([read more](/api/pages-head)).
+
+<div class="Alert Alert--teal">
+
+<b>Info:</b> To avoid duplicated meta tags when used in child component, set up an unique identifier with the `hid` key for your meta elements ([read more](https://github.com/declandewet/vue-meta#lists-of-tags)).
+
+</div>
diff --git a/en/api/configuration-hooks.md b/en/api/configuration-hooks.md
index bdc8b35..32f4fef 100644
--- a/en/api/configuration-hooks.md
+++ b/en/api/configuration-hooks.md
@@ -36,3 +36,116 @@ Internally, hooks follow a naming pattern using colons (e.g., `build:done`). For
- [ModulesContainer hooks](https://nuxtjs.org/api/internals-module-container#hooks)
- [Builder hooks](https://nuxtjs.org/api/internals-builder#hooks)
- [Generator hooks](https://nuxtjs.org/api/internals-generator#hooks)
+
+## Examples
+
+### Redirect to router.base when not on root
+
+Let´s say you want to serve pages as `/portal` instead of `/`.
+
+This is maybe an edge-case, and the point of _nuxt.config.js_’ `router.base` is for when a Web server will serve Nuxt elsewhere than the domain root.
+
+But when in local development, hitting _localhost_, when router.base is not / returns a 404.
+In order to prevent this, you can setup a Hook.
+
+Maybe redirecting is not the best use-case for a production Web site, but this will help you leverage Hooks.
+
+To begin, you [can change `router.base`](/api/configuration-router#base); Update your `nuxt.config.js`:
+
+```js
+// nuxt.config.js
+import hooks from './hooks'
+export default {
+ router: {
+ base: '/portal'
+ }
+ hooks: hooks(this)
+}
+```
+
+Then, create a few files;
+
+1. `hooks/index.js`, Hooks module
+
+ ```js
+ // file: hooks/index.js
+ import render from './render'
+
+ export default nuxtConfig => ({
+ render: render(nuxtConfig)
+ })
+ ```
+
+1. `hooks/render.js`, Render hook
+
+ ```js
+ // file: hooks/render.js
+ import redirectRootToPortal from './route-redirect-portal'
+
+ export default nuxtConfig => {
+ const router = Reflect.has(nuxtConfig, 'router') ? nuxtConfig.router : {}
+ const base = Reflect.has(router, 'base') ? router.base : '/portal'
+
+ return {
+ /**
+ * 'render:setupMiddleware'
+ * {@link node_modules/nuxt/lib/core/renderer.js}
+ */
+ setupMiddleware(app) {
+ app.use('/', redirectRootToPortal(base))
+ }
+ }
+ }
+ ```
+
+1. `hooks/route-redirect-portal.js`, The Middleware itself
+
+ ```js
+ // file: hooks/route-redirect-portal.js
+
+ /**
+ * Nuxt middleware hook to redirect from / to /portal (or whatever we set in nuxt.config.js router.base)
+ *
+ * Should be the same version as connect
+ * {@link node_modules/connect/package.json}
+ */
+ import parseurl from 'parseurl'
+
+ /**
+ * Connect middleware to handle redirecting to desired Web Applicatin Context Root.
+ *
+ * Notice that Nuxt docs lacks explaning how to use hooks.
+ * This is a sample router to help explain.
+ *
+ * See nice implementation for inspiration:
+ * - https://github.com/nuxt/nuxt.js/blob/dev/examples/with-cookies/plugins/cookies.js
+ * - https://github.com/yyx990803/launch-editor/blob/master/packages/launch-editor-middleware/index.js
+ *
+ * [http_class_http_clientrequest]: https://nodejs.org/api/http.html#http_class_http_clientrequest
+ * [http_class_http_serverresponse]: https://nodejs.org/api/http.html#http_class_http_serverresponse
+ *
+ * @param {http.ClientRequest} req Node.js internal client request object [http_class_http_clientrequest]
+ * @param {http.ServerResponse} res Node.js internal response [http_class_http_serverresponse]
+ * @param {Function} next middleware callback
+ */
+ export default desiredContextRoot =>
+ function projectHooksRouteRedirectPortal(req, res, next) {
+ const desiredContextRootRegExp = new RegExp(`^${desiredContextRoot}`)
+ const _parsedUrl = Reflect.has(req, '_parsedUrl') ? req._parsedUrl : null
+ const url = _parsedUrl !== null ? _parsedUrl : parseurl(req)
+ const startsWithDesired = desiredContextRootRegExp.test(url.pathname)
+ const isNotProperContextRoot = desiredContextRoot !== url.pathname
+ if (isNotProperContextRoot && startsWithDesired === false) {
+ const pathname = url.pathname === null ? '' : url.pathname
+ const search = url.search === null ? '' : url.search
+ const Location = desiredContextRoot + pathname + search
+ res.writeHead(302, {
+ Location
+ })
+ res.end()
+ }
+ next()
+ }
+ ```
+
+Then, whenever a colleague in development accidentally hits `/` to reach the development web development service, Nuxt will automatically redirect to `/portal`
diff --git a/en/api/configuration-ignore.md b/en/api/configuration-ignore.md
index 8b7ac35..06dcf4f 100644
--- a/en/api/configuration-ignore.md
+++ b/en/api/configuration-ignore.md
@@ -15,7 +15,7 @@ By default all files which start with `-` will be ignored, such as `store/-foo.j
# The ignore Property
- Type: `Array`
-- Default: `['**/*.test.*']`
+- Default: `['**/*.test.*', '**/*.spec.*']`
> More customizable than `ignorePrefix`: all files matching glob patterns specified inside `ignore` will be ignored in building.
diff --git a/en/api/configuration-loading-indicator.md b/en/api/configuration-loading-indicator.md
index d21e918..7adca2f 100644
--- a/en/api/configuration-loading-indicator.md
+++ b/en/api/configuration-loading-indicator.md
@@ -7,13 +7,11 @@ description: Show fancy loading indicator while SPA page is loading!
> Show fancy loading indicator while SPA page is loading!
-When running Nuxt.js in SPA mode, there is no content from the server side on the first page load.
-So, instead of showing a blank page while the page loads, we may show a spinner.
+When running Nuxt.js in SPA mode, there is no content from the server side on the first page load. So, instead of showing a blank page while the page loads, we may show a spinner.
-This property can have 3 different types: `string` or `false` or `object`.
-If a string value is provided it is converted to object style.
+This property can have 3 different types: `string` or `false` or `object`. If a string value is provided it is converted to object style.
-Default value is:
+Default value is:
```js
{
name: 'circle',
@@ -24,8 +22,7 @@ Default value is:
## Built-in indicators
-These indicators are ported from awesome [Spinkit](http://tobiasahlin.com/spinkit) project.
-You can use its demo page to preview spinners.
+These indicators are ported from awesome [Spinkit](http://tobiasahlin.com/spinkit) project. You can use its demo page to preview spinners.
- circle
- cube-grid
@@ -43,7 +40,6 @@ Built-in indicators support `color` and `background` options.
## Custom indicators
-If you need your own special indicator, a String value or Name key can also be a path to an html template of indicator source code!
-All of the options are passed to the template, too.
+If you need your own special indicator, a String value or Name key can also be a path to an html template of indicator source code! All of the options are passed to the template, too.
-Nuxt's built-in [source code](https://github.com/nuxt/nuxt.js/tree/dev/lib/app/views/loading) is also available if you need a base!
+Nuxt's built-in [source code](https://github.com/nuxt/nuxt.js/tree/dev/packages/vue-app/template/views/loading) is also available if you need a base!
diff --git a/en/api/configuration-loading.md b/en/api/configuration-loading.md
index 5bd7495..238d48a 100644
--- a/en/api/configuration-loading.md
+++ b/en/api/configuration-loading.md
@@ -23,7 +23,7 @@ export default {
}
```
-> If you want to start it in the `mounted` method, make sure to use ` this.$nextTick`, because $loading may not be available immediately.
+> If you want to start it in the `mounted` method, make sure to use ` this.$nextTick`, because $loading may not be available immediately.
## Disable the Progress Bar
@@ -32,7 +32,7 @@ export default {
If you don't want to display the progress bar between the routes, simply add `loading: false` in your `nuxt.config.js` file:
```js
-module.exports = {
+export default {
loading: false
}
```
@@ -48,13 +48,16 @@ List of properties to customize the progress bar.
| `color` | String | `'black'` | CSS color of the progress bar |
| `failedColor` | String | `'red'` | CSS color of the progress bar when an error appended while rendering the route (if `data` or `fetch` sent back an error for example). |
| `height` | String | `'2px'` | Height of the progress bar (used in the `style` property of the progress bar) |
+| `throttle` | Number | `200` | In ms, wait for the specified time before displaying the progress bar. Useful for preventing the bar from flashing. |
| `duration` | Number | `5000` | In ms, the maximum duration of the progress bar, Nuxt.js assumes that the route will be rendered before 5 seconds. |
+| `continuous` | Boolean | `false` | Keep animating progress bar when loading takes longer than `duration`. |
+| `css` | Boolean | `true` | Set to false to remove default progress bar styles (and add your own). |
| `rtl` | Boolean | `false` | Set the direction of the progress bar from right to left. |
For a blue progress bar with 5px of height, we update the `nuxt.config.js` to the following:
```js
-module.exports = {
+export default {
loading: {
color: 'blue',
height: '5px'
@@ -72,8 +75,8 @@ You can create your own component that Nuxt.js will call instead of its default
| Method | Required | Description |
|--------|----------|-------------|
-| `start()` | Required | Called when a route changes, this is here where you display your component. |
-| `finish()` | Required | Called when a route is loaded (and data fetched), this is here where you hide your component. |
+| `start()` | Required | Called when a route changes, this is where you display your component. |
+| `finish()` | Required | Called when a route is loaded (and data fetched), this is where you hide your component. |
| `fail()` | *Optional* | Called when a route couldn't be loaded (failed to fetch data for example). |
| `increase(num)` | *Optional* | Called during loading the route component, `num` is an Integer < 100. |
@@ -120,7 +123,20 @@ export default {
Then, we update our `nuxt.config.js` to tell Nuxt.js to use our component:
```js
-module.exports = {
+export default {
loading: '~/components/loading.vue'
}
```
+
+## Internals of the Progress Bar
+
+Unfortunately it is not possible for the Loading component to know in advance how long e.g. loading a new page will take. Therefore it is not possible to accurately animate the progress bar to 100% of the loading time.
+
+Nuxt's loading component partially solves this by letting you set the `duration`, this should be set to a _guestimate_ of how long the loading process will take. Unless you use a custom loading component, the progress bar will always move from 0% to 100% in `duration` time (regardless of actual progression). When the loading takes longer than `duration` time, the progress bar will stay at 100% until the loading finishes.
+
+You can change the default behaviour by setting `continuous` to true, then after reaching 100% the progress bar will start shrinking back to 0% again in `duration` time. When the loading is still not finished after reaching 0% it will start growing from 0% to 100% again, this repeats until the loading finishes.
+
+*Example of a continuous progress bar:*
+
+
+<img src="/api-continuous-loading.gif" alt="continuous loading"/>
diff --git a/en/api/configuration-modern.md b/en/api/configuration-modern.md
new file mode 100644
index 0000000..d6bb3d5
--- /dev/null
+++ b/en/api/configuration-modern.md
@@ -0,0 +1,34 @@
+---
+title: "API: The modern Property"
+description: Build and server a modern bundle
+---
+
+# The modern Property
+
+> This feature is inspired by [vue-cli modern mode](https://cli.vuejs.org/guide/browser-compatibility.html#modern-mode)
+
+- Type: `String` or `Boolean`
+ - Default: false
+ - Possible values:
+ - `'client'`: Serve both, the modern bundle `<script type="module">` and the legacy bundle `<script nomodule>` scripts, also provide a `<link rel="modulepreload">` for the modern bundle. Every browser that understands the `module` type will load the modern bundle while older browsers fall back to the legacy (transpiled) one.
+ - `'server'` or `true`: The Node.js server will check browser version based on the user agent and serve the corresponding modern or legacy bundle.
+ - `false`: Disable modern build
+
+The two versions of bundles are:
+
+1. Modern bundle: targeting modern browsers that support ES modules
+1. Legacy bundle: targeting older browsers based on babel config (IE9 compatible by default).
+
+**Info:** you can use commands `nuxt build/start --modern=[type]` or `nuxt build/start -m=[type]` to build/start modern bundles, so you can specify modern commands inside the `package.json` scripts:
+
+```json
+{
+ "scripts": {
+ "build:modern": "nuxt build --modern=server",
+ "start:modern": "nuxt start --modern=server"
+ }
+}
+```
+**Note about *nuxt generate*:** The `modern` property also works with the `nuxt generate` command, but in this case only the `client` option is honored and will be selected automatically when launching the `nuxt generate --modern` command without providing any values.
+
+> Please refer [Phillip Walton's excellent post](https://philipwalton.com/articles/deploying-es2015-code-in-production-today/) for more knowledge regarding modern builds.
diff --git a/en/api/configuration-modules.md b/en/api/configuration-modules.md
index 69942b2..58132cb 100644
--- a/en/api/configuration-modules.md
+++ b/en/api/configuration-modules.md
@@ -12,7 +12,7 @@ description: Modules are Nuxt.js extensions which can extend its core functional
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
modules: [
// Using package name
'@nuxtjs/axios',
diff --git a/en/api/configuration-modulesdir.md b/en/api/configuration-modulesdir.md
index cf6fe04..e1b8a09 100644
--- a/en/api/configuration-modulesdir.md
+++ b/en/api/configuration-modulesdir.md
@@ -7,12 +7,16 @@ description: Define the modules directory for your Nuxt.js application
- Type: `Array`
- Default: `['node_modules']`
- > Used to set the modules directories for path resolving, for example: webpack resolveLoading, nodeExternal and postcss. Configuration path is relative to [options.rootDir](/api/configuration-rootdir) (default: `process.cwd()`).
- Example (`nuxt.config.js`):
- ```js
-module.exports = {
+
+> Used to set the modules directories for path resolving, for example: webpack resolveLoading, nodeExternal and postcss. Configuration path is relative to [options.rootDir](/api/configuration-rootdir) (default: `process.cwd()`).
+
+Example (`nuxt.config.js`):
+
+```js
+export default {
modulesDir: ['../../node_modules']
}
```
+
Setting this field may be necessary if your project is organized as a Yarn workspace-styled mono-repository.
diff --git a/en/api/configuration-plugins.md b/en/api/configuration-plugins.md
index 2f958d2..b60ae96 100644
--- a/en/api/configuration-plugins.md
+++ b/en/api/configuration-plugins.md
@@ -17,7 +17,7 @@ If the item is an object, the properties are:
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
plugins: ['~/plugins/vue-notifications']
}
```
diff --git a/en/api/configuration-render.md b/en/api/configuration-render.md
index 520585a..9051de7 100644
--- a/en/api/configuration-render.md
+++ b/en/api/configuration-render.md
@@ -13,7 +13,7 @@ description: Nuxt.js lets you customize runtime options for rendering pages
> Use this option to customize vue SSR bundle renderer. This option is skipped for spa mode.
```js
-module.exports = {
+export default {
render: {
bundleRenderer: {
directives: {
@@ -37,7 +37,7 @@ To disable etag for pages set `etag: false`
See [etag](https://www.npmjs.com/package/etag) docs for possible options.
-### compressor
+## compressor
- Type `Object`
- Default: `{ threshold: 0 }`
@@ -47,19 +47,39 @@ will be used (with respective options).
If you want to use your own compression middleware, you can reference it
directly (f.ex. `otherComp({ myOptions: 'example' })`).
-### http2
+## fallback
+- Type `Object`
+ - Default: `{ dist: {}, static: { skipUnknown: true } }`
+
+Options for [serve-placeholder](https://github.com/nuxt/serve-placeholder) middleware.
+
+If you want to disable one of them or both, you can pass a falsy value.
+
+## http2
- Type `Object`
- - Default: `{ push: false }`
+ - Default: `{ push: false, pushAssets: null }`
Activate HTTP2 push headers.
+You can control what links to push using `pushAssets` function. Eg.:
+```js
+pushAssets: (req, res, publicPath, preloadFiles) => preloadFiles
+ .filter(f => f.asType === 'script' && f.file === 'runtime.js')
+ .map(f => `<${publicPath}${f.file}>; rel=preload; as=${f.asType}`)
+```
+
+You can add your own assets to the array as well.
+Using `req` and `res` you can decide what links to push based on the request headers, for example using the cookie with application version.
+
+The assets will be joined together with `, ` and passed as a single `Link` header.
+
## resourceHints
- Type: `boolean`
- Default: `true`
> Adds `prefetch` and `preload` links for faster initial page load time.
-You may want to only disable this option if have many pages and routes.
+You may want to only disable this option if you have many pages and routes.
## ssr
- Type: `boolean`
@@ -106,8 +126,15 @@ export default {
render: {
csp: {
hashAlgorithm: 'sha256',
- allowedSources: undefined,
- policies: undefined
+ policies: {
+ 'script-src': [
+ 'https://www.google-analytics.com',
+ 'https://name.example.com'
+ ],
+ 'report-uri': [
+ 'https://report.example.com/report-csp-violations'
+ ]
+ }
}
}
}
diff --git a/en/api/configuration-rootdir.md b/en/api/configuration-rootdir.md
index 4bbd307..86bd878 100644
--- a/en/api/configuration-rootdir.md
+++ b/en/api/configuration-rootdir.md
@@ -14,4 +14,8 @@ This property is overwritten by [nuxt commands](/guide/commands) and set to the
This property should be used when using [Nuxt.js programmatically](/api/nuxt).
-<p class="Alert Alert--blue">The downside of this option is that your `node_modules` directory should be inside the `rootDir` folder. If you want to set the path of the application without the node_modules, use the [`srcDir` option](/api/configuration-srcdir).</p>
+<div class="Alert Alert--blue">
+
+The downside of this option is that your `node_modules` directory should be inside the `rootDir` folder. If you want to set the path of the application without the node_modules, use the [`srcDir` option](/api/configuration-srcdir).
+
+</div>
diff --git a/en/api/configuration-router.md b/en/api/configuration-router.md
index 5d5aaaa..210aa15 100644
--- a/en/api/configuration-router.md
+++ b/en/api/configuration-router.md
@@ -14,16 +14,24 @@ description: The router property lets you customize Nuxt.js router.
The base URL of the app. For example, if the entire single page application is served under `/app/`, then base should use the value `'/app/'`.
+This can be useful if you need to serve Nuxt as a different context root, from within a bigger Web site. Notice that you may, or may not set up a Front Proxy Web Server.
+
+If you want to have a redirect to `router.base`, you can do so [using a Hook, see *Redirect to router.base when not on root*](/api/configuration-hooks#redirect-to-router-base-when-not-on-root).
+
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
router: {
base: '/app/'
}
}
```
-<p class="Alert Alert-blue">When `base` is set, Nuxt.js will also add in the document header `<base href="{{ router.base }}"/>`.</p>
+<div class="Alert Alert-blue">
+
+When `base` is set, Nuxt.js will also add in the document header `<base href="{{ router.base }}"/>`.
+
+</div>
> This option is given directly to the vue-router [base](https://router.vuejs.org/api/#base).
@@ -37,7 +45,7 @@ Example of adding a custom route:
`nuxt.config.js`
```js
-module.exports = {
+export default {
router: {
extendRoutes (routes, resolve) {
routes.push({
@@ -61,7 +69,7 @@ Globally configure [`<nuxt-link>`](/api/components-nuxt-link) default active cla
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
router: {
linkActiveClass: 'active-link'
}
@@ -79,7 +87,7 @@ Globally configure [`<nuxt-link>`](/api/components-nuxt-link) default exact acti
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
router: {
linkExactActiveClass: 'exact-active-link'
}
@@ -99,7 +107,7 @@ Example:
`nuxt.config.js`
```js
-module.exports = {
+export default {
router: {
// Run the middleware/user-agent.js on every page
middleware: 'user-agent'
@@ -111,7 +119,7 @@ module.exports = {
```js
export default function (context) {
// Add the userAgent property in the context (available in `asyncData` and `fetch`)
- context.userAgent = context.isServer ? context.req.headers['user-agent'] : navigator.userAgent
+ context.userAgent = process.server ? context.req.headers['user-agent'] : navigator.userAgent
}
```
@@ -126,7 +134,7 @@ Configure the router mode, this is not recommended to change it due to server-si
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
router: {
mode: 'hash'
}
@@ -182,7 +190,7 @@ Example of forcing the scroll position to the top for every routes:
`nuxt.config.js`
```js
-module.exports = {
+export default {
router: {
scrollBehavior: function (to, from, savedPosition) {
return { x: 0, y: 0 }
diff --git a/en/api/configuration-servermiddleware.md b/en/api/configuration-servermiddleware.md
index 8b4040b..74137cb 100644
--- a/en/api/configuration-servermiddleware.md
+++ b/en/api/configuration-servermiddleware.md
@@ -23,14 +23,14 @@ like handling API requests or serving assets.
## Usage
-If middleware is String Nuxt.js will try to automatically resolve and require it.
+If middleware is String Nuxt.js will try to automatically resolve and require it.
Example (`nuxt.config.js`):
```js
-const serveStatic = require('serve-static')
+import serveStatic from 'serve-static'
-module.exports = {
+export default {
serverMiddleware: [
// Will register redirect-ssl npm package
'redirect-ssl',
@@ -57,10 +57,10 @@ It is also possible writing custom middleware. For more information See [Connect
Middleware (`api/logger.js`):
```js
-module.exports = function (req, res, next) {
+export default function (req, res, next) {
// req is the Node.js http request object
console.log(req.path)
-
+
// res is the Node.js http response object
// next is a function to call to invoke the next middleware
diff --git a/en/api/configuration-srcdir.md b/en/api/configuration-srcdir.md
index 0fed226..6cb8f65 100644
--- a/en/api/configuration-srcdir.md
+++ b/en/api/configuration-srcdir.md
@@ -13,7 +13,7 @@ description: Define the source directory of your Nuxt.js application
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
srcDir: 'client/'
}
```
diff --git a/en/api/configuration-transition.md b/en/api/configuration-transition.md
index 92ddc4b..cbd2287 100644
--- a/en/api/configuration-transition.md
+++ b/en/api/configuration-transition.md
@@ -20,7 +20,7 @@ Default:
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
transition: 'page'
// or
transition: {
@@ -53,10 +53,10 @@ Default:
Example (`nuxt.config.js`):
```js
-module.exports = {
+export default {
layoutTransition: 'layout'
// or
- transition: {
+ layoutTransition: {
name: 'layout',
mode: 'out-in'
}
diff --git a/en/api/configuration-vue-config.md b/en/api/configuration-vue-config.md
index 7f9ae1c..593960e 100644
--- a/en/api/configuration-vue-config.md
+++ b/en/api/configuration-vue-config.md
@@ -18,7 +18,7 @@ description: A config object for Vue.config
export default {
vue: {
config: {
- productTip: true,
+ productionTip: true,
devtools: false
}
}
@@ -28,7 +28,7 @@ export default {
This configuration will lead to the following Vue.config:
``` js
-Vue.config.productTip // true
+Vue.config.productionTip // true
Vue.config.devtools // false
Vue.config.silent // !isDev [default value]
Vue.config.performance // isDev [default value]
diff --git a/en/api/context.md b/en/api/context.md
index 80486c4..1411f4a 100644
--- a/en/api/context.md
+++ b/en/api/context.md
@@ -3,26 +3,38 @@ title: "API: The Context"
description: The `context` provides additional objects/params from Nuxt not traditionally available to Vue components. The `context` is available in special nuxt lifecycle areas like `asyncData`, `plugins`, 'middlewares', 'modules', and 'store/nuxtServerInit`.
---
-## Context
+# The Context
+
+> The `context` provides additional objects/params from Nuxt to Vue components. The `context` is available in special nuxt lifecycle areas like `asyncData`, `fetch`, `plugins`, 'middleware', 'modules', and 'nuxtServerInit`.
+
+## Available keys
+
+<div class="Alert Alert--teal">
+
+ **Note:** This is **not** the context passed into the `build.extend` function.
+
+</div>
+
List of all the available keys in `context`:
| Key | Type | Available | Description |
|------------------------|------------------------------------------------------------------------------------|-----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `app` | Root Vue Instance | Client & Server | The root Vue instance that includes all your plugins. For example, when using `axios`, you can get access to `$axios` through `context.app.$axios`. |
-| `isClient` | `Boolean` | Client & Server | Boolean to let you know if you're actually renderer from the client-side (_deprecated._ use `process.client`). |
-| `isServer` | `Boolean` | Client & Server | Boolean to let you know if you're actually renderer from the server-side (_deprecated._ use `process.server`). |
-| `isStatic` | `Boolean` | Client & Server | Boolean to let you know if you're actually inside a generated app (via `nuxt generate`) (_deprecated._ use `process.static`). |
+| `isClient` | `Boolean` | Client & Server | **Deprecated!** Use `process.client`. Boolean to let you know if you're actually renderer from the client-side. |
+| `isServer` | `Boolean` | Client & Server | **Deprecated!** Use `process.server`. Boolean to let you know if you're actually renderer from the server-side. |
+| `isStatic` | `Boolean` | Client & Server | **Deprecated!** Use `process.static`. Boolean to let you know if you're actually inside a generated app (via `nuxt generate`). |
| `isDev` | `Boolean` | Client & Server | Boolean to let you know if you're in dev mode, can be useful for caching some data in production. |
| `isHMR` | `Boolean` | Client & Server | Boolean to let you know if the method/middleware is called from webpack hot module replacement (*only on client-side in dev mode*). |
| `route` | [Vue Router Route](https://router.vuejs.org/en/api/route-object.html) | Client & Server | Vue Router route instance. |
+| `from` | [Vue Router Route](https://router.vuejs.org/en/api/route-object.html) | Client | The route navigated from
| `store` | [Vuex Store](https://vuex.vuejs.org/en/api.html#vuexstore-instance-properties) | Client & Server | Vuex Store instance. **Available only if the [vuex store](/guide/vuex-store) is set**. |
| `env` | `Object` | Client & Server | Environment variables set in `nuxt.config.js`, see [env api](/api/configuration-env). |
-| `params` | `Object` | Client & Server | Alias of `route.params`. |
+| `params` | `Object` | Client & Server | Alias of `route.params`. |
| `query` | `Object` | Client & Server | Alias of `route.query`. |
-| `req` | [`http.Request`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) | Server | Request from the Node.js server. If Nuxt is used as a middleware, the req object might be different depending of the framework you're using.<br>**Not available via `nuxt generate`**. |
-| `res` | [`http.Response`](https://nodejs.org/api/http.html#http_class_http_serverresponse) | Server | Response from the Node.js server. If Nuxt is used as a middleware, the res object might be different depending of the framework you're using.<br>**Not available via `nuxt generate`**. |
-| `redirect` | `Function` | Client & Server | Use this method to redirect the user to another route, the status code is used on the server-side, default to `302`. `redirect([status,] path [, query])`. |
+| `req` | [`http.Request`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) | Server | Request from the Node.js server. If Nuxt is used as a middleware, the request object might be different depending on the framework you're using.<br>**Not available via `nuxt generate`**. |
+| `res` | [`http.Response`](https://nodejs.org/api/http.html#http_class_http_serverresponse) | Server | Response from the Node.js server. If Nuxt is used as a middleware, the res object might be different depending on the framework you're using.<br>**Not available via `nuxt generate`**. |
+| `redirect` | `Function` | Client & Server | Use this method to redirect the user to another route, the status code is used on the server-side, defaults to `302`. `redirect([status,] path [, query])`. |
| `error` | `Function` | Client & Server | Use this method to show the error page: `error(params)`. The `params` should have the properties `statusCode` and `message`. |
| `nuxtState` | `Object` | Client | Nuxt state, useful for plugins which uses `beforeNuxtRender` to get the nuxt state on client-side before hydration. **Available only in `universal` mode**. |
| `beforeNuxtRender(fn)` | `Function` | Server | Use this method to update `__NUXT__` variable rendered on client-side, the `fn` (can be asynchronous) is called with `{ Components, nuxtState }`, see [example](https://github.com/nuxt/nuxt.js/blob/cf6b0df45f678c5ac35535d49710c606ab34787d/test/fixtures/basic/pages/special-state.vue). |
diff --git a/en/api/index.md b/en/api/index.md
index 3af87d9..c60df05 100644
--- a/en/api/index.md
+++ b/en/api/index.md
@@ -9,7 +9,18 @@ description: You may want to fetch data and render it on the server-side. Nuxt.j
- **Type:** `Function`
-`asyncData` is called every time before loading the component (**only for page components**). It can be called from the server-side or before navigating to the corresponding route. This method receives the [`context`](/api/context) object as the first argument, you can use it to fetch some data and return the component data.
+
+<div class="Alert Alert--nuxt-green">
+
+<b>Info:</b> Please visit the [async data guide](/guide/async-data) as well!
+
+</div>
+
+
+`asyncData` is called every time before loading the **page** component and is only available for such.
+It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.
+This method receives the [`context`](/api/context) object as the first argument, you can use it to fetch some data and return the component data.
+
The result from asyncData will be **merged** with data.
@@ -24,4 +35,8 @@ export default {
}
```
-<div class="Alert Alert--orange">You do **NOT** have access of the component instance through `this` inside `asyncData` because it is called **before initiating** the component.</div>
+<div class="Alert Alert--orange">
+
+<b>Warning:</b> You **don't** have access of the component instance through `this` inside `asyncData` because it is called **before initiating** the component.
+
+</div>
diff --git a/en/api/internals-builder.md b/en/api/internals-builder.md
index 6677259..2c72b9d 100644
--- a/en/api/internals-builder.md
+++ b/en/api/internals-builder.md
@@ -5,7 +5,7 @@ description: Nuxt `Builder` Class
# Builder Class
-- Source: **[builder/builder.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/builder/builder.js)**
+- Source: **[builder/builder.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/builder/src/builder.js)**
## Hooks
@@ -21,8 +21,8 @@ this.nuxt.hook('build:done', (builder) => {
Hook | Arguments | When
---------------------|--------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------
`build:before` | (nuxt, buildOptions) | Before Nuxt build started
-`build:templates` | ({ templateFiles, templateVars, resolve }) | Generating `.nuxt` template files
+`build:templates` | ({ templatesFiles, templateVars, resolve }) | Generating `.nuxt` template files
`build:extendRoutes` | (routes, resolve) | Generating routes
`build:compile`      | ({ name, compiler }) | Before webpack compile (compiler is a webpack `Compiler` instance), if universal mode, called twice with name `'client'` and `'server'`
`build:compiled`     | ({ name, compiler, stats }) | webpack build finished
-`build:done` | (nuxt) | Nuxt build finished
\ No newline at end of file
+`build:done` | (nuxt) | Nuxt build finished
diff --git a/en/api/internals-generator.md b/en/api/internals-generator.md
index 69c3556..e341ba9 100644
--- a/en/api/internals-generator.md
+++ b/en/api/internals-generator.md
@@ -5,7 +5,7 @@ description: Nuxt Generator Class
# Generator Class
-- Source: **[builder/generator.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/builder/generator.js)**
+- Source: **[generator/generator.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/generator/src/generator.js)**
## Hooks
diff --git a/en/api/internals-module-container.md b/en/api/internals-module-container.md
index 32543b1..e5cd388 100644
--- a/en/api/internals-module-container.md
+++ b/en/api/internals-module-container.md
@@ -5,7 +5,7 @@ description: Nuxt ModuleContainer Class
# ModuleContainer Class
-- Source: **[core/module.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/core/module.js)**
+- Source: **[core/module.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/core/src/module.js)**
All [modules](/guide/modules) will be called within context of `ModuleContainer` instance.
@@ -36,6 +36,8 @@ Plugin | Arguments | When
### addVendor (vendor)
+**Deprecated as `vendor` isn't used anymore**
+
Adds to `options.build.vendor` and apply unique filter.
### addTemplate (template)
@@ -81,8 +83,8 @@ Is shortcut to `addModule(moduleOpts, true)`
We can register hooks on certain life cycle events.
-Hook | Arguments | When
---------------------------|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------
+Hook | Arguments | When
+--------------------------|----------------------------|--------------------------------------------------------------------------------------
`modules:before` | (moduleContainer, options) | Called before creating ModuleContainer class, useful to overload methods and options.
- `modules:done` | (moduleContainer) | Called when all modules has been loaded.
+ `modules:done` | (moduleContainer) | Called when all modules has been loaded.
diff --git a/en/api/internals-nuxt.md b/en/api/internals-nuxt.md
index 15a303e..4bf76b7 100644
--- a/en/api/internals-nuxt.md
+++ b/en/api/internals-nuxt.md
@@ -5,7 +5,7 @@ description: Nuxt Core Class
# Nuxt Class
-- Source: **[core/nuxt.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/core/nuxt.js)**
+- Source: **[core/nuxt.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/core/src/nuxt.js)**
This is the core container which allows all modules and classes communicate with each other. All modules has access to Nuxt instance using `this.nuxt`.
diff --git a/en/api/internals-renderer.md b/en/api/internals-renderer.md
index fda1cdc..ddc1563 100644
--- a/en/api/internals-renderer.md
+++ b/en/api/internals-renderer.md
@@ -5,7 +5,7 @@ description: Nuxt Renderer Class
# Renderer Class
-- Source: **[core/renderer.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/core/renderer.js)**
+- Source: **[vue-renderer/renderer.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/vue-renderer/src/renderer.js)**
This class is exporting a connect middleware which handles and serves all SSR and asset requests.
@@ -13,8 +13,8 @@ This class is exporting a connect middleware which handles and serves all SSR an
We can register hooks on certain life cycle events.
-Hook | Arguments | When
---------------------------|------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------
+Hook | Arguments | When
+--------------------------|--------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`render:before` | (renderer, options) | Before setting up middleware and resources for the Renderer class, useful to overload some methods or options.
`render:setupMiddleware` | (app) *connect instance* | Before Nuxt adds it's middleware stack. We can use it to register custom server side middleware.
`render:errorMiddleware` | (app) *connect instance* | Before adding Nuxt error middleware, useful to add your own middleware before using Nuxt's. See the [Sentry module](https://github.com/nuxt-community/sentry-module/blob/master/lib/sentry.js) for more info.
@@ -22,4 +22,4 @@ Hook | Arguments | When
`render:done` | (renderer) | SSR Middleware and all resources are ready (Renderer ready)
`render:routeContext` | (context.nuxt) | *Every time a route is server-rendered and before `render:route` hook*. Called before serializing Nuxt context into `window.__NUXT__`, useful to add some data that you can fetch on client-side.
`render:route` | (url, result, context) | *Every time a route is server-rendered*. Called before sending back the request to the browser.
- `render:routeDone` | (url, result, context) | *Every time a route is server-rendered*. Called aftet the response has been sent to the browser.
+ `render:routeDone` | (url, result, context) | *Every time a route is server-rendered*. Called after the response has been sent to the browser.
diff --git a/en/api/internals.md b/en/api/internals.md
index 3fd1657..88f31f2 100644
--- a/en/api/internals.md
+++ b/en/api/internals.md
@@ -18,17 +18,17 @@ These classes are the heart of Nuxt and should exist on both runtime and build t
#### Nuxt
- [`Nuxt` Class](/api/internals-nuxt)
-- Source: [core/nuxt.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/core/nuxt.js)
+- Source: [core/nuxt.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/core/src/nuxt.js)
#### Renderer
- [`Renderer` Class](/api/internals-renderer)
-- Source: [core/renderer.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/core/renderer.js)
+- Source: [vue-renderer/renderer.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/vue-renderer/src/renderer.js)
#### ModuleContainer
- [`ModuleContainer` Class](/api/internals-module-container)
-- Source: [core/module.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/core/module.js)
+- Source: [core/module.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/core/src/module.js)
### Build
@@ -37,29 +37,29 @@ These classes are only needed for build or dev mode.
#### Builder
- [`Builder` Class](/api/internals-builder)
-- Source: [builder/builder.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/builder/builder.js)
+- Source: [builder/builder.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/builder/src/builder.js)
#### Generator
- [`Generator` Class](/api/internals-generator)
-- Source: [generator/generator.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/builder/generator.js)
+- Source: [generator/generator.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/generator/src/generator.js)
### Common
#### Utils
-- Source: [common/utils.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/common/utils.js)
+- Source: [utils/src](https://github.com/nuxt/nuxt.js/blob/dev/packages/utils/src)
#### Options
-- Source: [common/options.js](https://github.com/nuxt/nuxt.js/blob/dev/lib/common/options.js)
+- Source: [config/options.js](https://github.com/nuxt/nuxt.js/blob/dev/packages/config/src/options.js)
## Packaging & Usage
-Nuxt exports all classes by default. To require them:
+Nuxt exports all classes by default. To import them:
```js
-const { Nuxt, Builder, Utils } = require('nuxt')
+import { Nuxt, Builder, Utils } from 'nuxt'
```
## Common patterns
diff --git a/en/api/menu.json b/en/api/menu.json
index 3cc40e1..fec7370 100644
--- a/en/api/menu.json
+++ b/en/api/menu.json
@@ -12,6 +12,7 @@
{ "name": "fetch", "to": "/pages-fetch" },
{ "name": "head", "to": "/pages-head" },
{ "name": "layout", "to": "/pages-layout" },
+ { "name": "loading", "to": "/pages-loading" },
{ "name": "middleware", "to": "/pages-middleware" },
{ "name": "scrollToTop", "to": "/pages-scrolltotop" },
{
@@ -44,18 +45,29 @@
"contents": [
{ "name": "analyze", "to": "#analyze" },
{ "name": "babel", "to": "#babel" },
+ { "name": "cache", "to": "#cache" },
{ "name": "cssSourceMap", "to": "#csssourcemap" },
{ "name": "devMiddleware", "to": "#devmiddleware" },
{ "name": "extend", "to": "#extend" },
{ "name": "extractCSS", "to": "#extractcss" },
{ "name": "filenames", "to": "#filenames" },
{ "name": "hotMiddleware", "to": "#hotmiddleware" },
+ { "name": "html.minify", "to": "#html-minify" },
+ { "name": "loaders", "to": "#loaders" },
+ { "name": "optimization", "to": "#optimization" },
+ { "name": "optimizeCSS", "to": "#optimizecss" },
+ { "name": "parallel", "to": "#parallel" },
{ "name": "plugins", "to": "#plugins" },
{ "name": "postcss", "to": "#postcss" },
+ { "name": "profile", "to": "#profile" },
{ "name": "publicPath", "to": "#publicpath" },
+ { "name": "splitChunks", "to": "#splitchunks" },
{ "name": "ssr", "to": "#ssr" },
+ { "name": "styleResources", "to": "#styleresources" },
{ "name": "templates", "to": "#templates" },
- { "name": "vendor", "to": "#vendor" },
+ { "name": "terser", "to": "#terser" },
+ { "name": "transpile", "to": "#transpile" },
+ { "name": "vueLoader", "to": "#vueloader" },
{ "name": "watch", "to": "#watch" }
]
},
@@ -82,24 +94,30 @@
"contents": [
{ "name": "Disable the Progress Bar", "to": "#disable-the-progress-bar" },
{ "name": "Customize the Progress Bar", "to": "#customize-the-progress-bar" },
- { "name": "Use a Custom Loading Component", "to": "#use-a-custom-loading-component" }
+ { "name": "Use a Custom Loading Component", "to": "#use-a-custom-loading-component" },
+ { "name": "Internals of the Progress Bar", "to": "#internals-of-the-progress-bar" }
]
},
{ "name": "loadingIndicator", "to": "/configuration-loading-indicator" },
{ "name": "mode", "to": "/configuration-mode" },
+ { "name": "modern", "to": "/configuration-modern" },
{ "name": "modules", "to": "/configuration-modules" },
+ { "name": "modulesDir", "to": "/configuration-modulesdir" },
{ "name": "plugins", "to": "/configuration-plugins" },
{
"name": "render",
"to": "/configuration-render",
"contents": [
- { "name": "bundleRenderer", "to": "#bundleRenderer" },
+ { "name": "bundleRenderer", "to": "#bundlerenderer" },
{ "name": "etag", "to": "#etag" },
- { "name": "gzip", "to": "#gzip" },
+ { "name": "compressor", "to": "#compressor" },
+ { "name": "fallback", "to": "#fallback" },
{ "name": "http2", "to": "#http2" },
- { "name": "resourceHints", "to": "#resourceHints" },
+ { "name": "resourceHints", "to": "#resourcehints" },
{ "name": "ssr", "to": "#ssr" },
- { "name": "static", "to": "#static" }
+ { "name": "static", "to": "#static" },
+ { "name": "dist", "to": "#dist" },
+ { "name": "csp", "to": "#csp" }
]
},
{ "name": "rootDir", "to": "/configuration-rootdir" },
@@ -113,14 +131,19 @@
{ "name": "linkExactActiveClass", "to": "#linkexactactiveclass" },
{ "name": "middleware", "to": "#middleware" },
{ "name": "mode", "to": "#mode" },
- { "name": "scrollBehavior", "to": "#scrollbehavior" }
+ { "name": "scrollBehavior", "to": "#scrollbehavior" },
+ { "name": "parseQuery / stringifyQuery", "to": "#parsequery-stringifyquery" },
+ { "name": "fallback", "to": "#fallback" }
]
},
{ "name": "server", "to": "/configuration-server" },
{ "name": "serverMiddleware", "to": "/configuration-servermiddleware" },
{ "name": "srcDir", "to": "/configuration-srcdir" },
+ { "name": "dir", "to": "/configuration-dir" },
{ "name": "transition", "to": "/configuration-transition" },
+ { "name": "vue.config", "to": "/configuration-vue-config" },
{ "name": "watch", "to": "/configuration-watch" },
+ { "name": "globalName", "to": "/configuration-global-name" },
{
"name": "watchers",
"to": "/configuration-watchers",
diff --git a/en/api/nuxt-render-and-get-window.md b/en/api/nuxt-render-and-get-window.md
index 7177828..201ae3f 100644
--- a/en/api/nuxt-render-and-get-window.md
+++ b/en/api/nuxt-render-and-get-window.md
@@ -15,7 +15,11 @@ description: Get the `window` from a given URL of a Nuxt.js Application.
> Get the window from a given url of a Nuxt.js application.
-<p class="Alert Alert--info">This method is made for [test purposes](/guide/development-tools#end-to-end-testing).</p>
+<div class="Alert Alert--orange">
+
+This method is made for [test purposes](/guide/development-tools#end-to-end-testing).
+
+</div>
To use this function, you have to install `jsdom`:
diff --git a/en/api/nuxt-render-route.md b/en/api/nuxt-render-route.md
index 52fef8f..e2fa479 100644
--- a/en/api/nuxt-render-route.md
+++ b/en/api/nuxt-render-route.md
@@ -18,7 +18,11 @@ description: Render a specific route with a given context.
This method should be used mostly for [test purposes](/guide/development-tools#end-to-end-testing) as well with [`nuxt.renderAndGetWindow`](/api/nuxt-render-and-get-window).
-<p class="Alert Alert--info">`nuxt.renderRoute` should be executed after the build process in production mode (`dev: false`).</p>
+<div class="Alert Alert--orange">
+
+`nuxt.renderRoute` should be executed after the build process in production mode (`dev: false`).
+
+</div>
Example:
@@ -39,7 +43,7 @@ new Builder(nuxt)
// `error` not null when the error layout is displayed, the error format is:
// { statusCode: 500, message: 'My error message' }
- // `redirected` is not `false` when `redirect()` has been used in `data()` or `fetch()`
+ // `redirected` is not `false` when `redirect()` has been used in `asyncData()` or `fetch()`
// { path: '/other-path', query: {}, status: 302 }
})
```
diff --git a/en/api/nuxt-render.md b/en/api/nuxt-render.md
index d76e0bb..f631aa1 100644
--- a/en/api/nuxt-render.md
+++ b/en/api/nuxt-render.md
@@ -34,10 +34,6 @@ app.use(nuxt.render)
if (config.dev) {
new Builder(nuxt).build()
.then(listen)
- .catch((error) => {
- console.error(error)
- process.exit(1)
- })
}
else {
listen()
@@ -50,4 +46,8 @@ function listen() {
}
```
-<p class="Alert">It's recommended to call `nuxt.render` at the end of your middlewares since it will handle the rendering of your web application and won't call `next()`</p>
+<div class="Alert">
+
+It's recommended to call `nuxt.render` at the end of your middlewares since it will handle the rendering of your web application and won't call `next()`
+
+</div>
diff --git a/en/api/pages-fetch.md b/en/api/pages-fetch.md
index 39c328f..e3141be 100644
--- a/en/api/pages-fetch.md
+++ b/en/api/pages-fetch.md
@@ -9,10 +9,18 @@ description: The `fetch` method is used to fill the store before rendering the p
- **Type:** `Function`
-The `fetch` method, *if set*, is called every time before loading the component (**only for page components**). It can be called from the server-side or before navigating to the corresponding route.
+The `fetch` method, *if set*, is called every time before loading the component (**only for page components**). It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.
The `fetch` method receives [the `context`](/api/context) object as the first argument, we can use it to fetch some data and fill the store. To make the `fetch` method asynchronous, **return a Promise**, Nuxt.js will wait for the promise to be resolved before rendering the component.
+
+<div class="Alert Alert--orange">
+
+**Warning**: You **don't** have access of the component instance through `this` inside `fetch` because it is called **before initiating** the component.
+
+</div>
+
+
Example of `pages/index.vue`:
```html
diff --git a/en/api/pages-head.md b/en/api/pages-head.md
index d11a3d5..e4e7410 100644
--- a/en/api/pages-head.md
+++ b/en/api/pages-head.md
@@ -29,6 +29,7 @@ export default {
return {
title: this.title,
meta: [
+ // hid is used as unique identifier. Do not use `vmid` for it as it will not work
{ hid: 'description', name: 'description', content: 'My custom description' }
]
}
@@ -37,4 +38,8 @@ export default {
</script>
```
-<p class="Alert">To avoid any duplication when used in child component, please give a unique identifier with the `hid` key, please [read more about it](https://github.com/declandewet/vue-meta#lists-of-tags).</p>
+<div class="Alert Alert--teal">
+
+<b>Info:</b> To avoid duplicated meta tags when used in child component, set up an unique identifier with the `hid` key for your meta elements ([read more](https://github.com/declandewet/vue-meta#lists-of-tags)).
+
+</div>
diff --git a/en/api/pages-loading.md b/en/api/pages-loading.md
new file mode 100644
index 0000000..63cbb01
--- /dev/null
+++ b/en/api/pages-loading.md
@@ -0,0 +1,28 @@
+---
+title: "API: The loading Property"
+description: The `loading` property gives you the option to disable the default loading progress bar on a specific page.
+---
+
+# The loading Property
+
+> The loading property gives you the option to disable the default loading progress bar on a specific page.
+
+- **Type:** `Boolean` (default: `true`)
+
+By default, Nuxt.js uses its own component to show a progress bar between the routes.
+
+You can disable or customize it globally through the [Configuration's loading option](/api/configuration-loading), but also disable it for specific pages by setting the `loading` property to `false` :
+
+```html
+<template>
+ <h1>My page</h1>
+</template>
+
+<script>
+export default {
+ loading: false
+}
+</script>
+```
+
+You can find an official example using this property [here](/examples/custom-page-loading).
diff --git a/en/api/pages-scrolltotop.md b/en/api/pages-scrolltotop.md
index 1696f87..1a82ec0 100644
--- a/en/api/pages-scrolltotop.md
+++ b/en/api/pages-scrolltotop.md
@@ -9,7 +9,7 @@ description: The `scrollToTop` property lets you tell Nuxt.js to scroll to the t
- **Type:** `Boolean` (default: `false`)
-By default, Nuxt.js scrolls to the top when you go to another page, but with children routes, Nuxt.js keeps the scroll position. If you want to tell Nuxt.js to scroll to the top when rendering your child route, set `scrollToTop: true`:
+By default, Nuxt.js scrolls to the top when you go to another page, but with children routes, Nuxt.js keeps the scroll position. If you want to tell Nuxt.js to scroll to the top when rendering your child route, set `scrollToTop` to `true`:
```html
<template>
@@ -23,4 +23,6 @@ export default {
</script>
```
+Conversely, you can manually set `scrollToTop` to `false` on parent routes as well.
+
If you want to overwrite the default scroll behavior of Nuxt.js, take a look at the [scrollBehavior option](/api/configuration-router#scrollBehavior).
diff --git a/en/api/pages-validate.md b/en/api/pages-validate.md
index 437ad2c..7c04bde 100644
--- a/en/api/pages-validate.md
+++ b/en/api/pages-validate.md
@@ -56,7 +56,7 @@ export default {
}
```
-You can also throw expected or unexpected errors during validate function executation:
+You can also throw expected or unexpected errors during validate function execution:
```js
export default {
diff --git a/en/api/pages-watchquery.md b/en/api/pages-watchquery.md
index b410adb..ab53e22 100644
--- a/en/api/pages-watchquery.md
+++ b/en/api/pages-watchquery.md
@@ -6,10 +6,12 @@ description: Watch query strings and execute component methods on change (asyncD
# The watchQuery Property
> Watch query strings and execute component methods on change (asyncData, fetch, validate, layout, ...)
-- **Type:** `Array` (default: `[]`)
+- **Type:** `Boolean` or `Array` (default: `[]`)
Use the `watchQuery` key to set up a watcher for query strings. If the defined strings change, all component methods (asyncData, fetch, validate, layout, ...) will be called. Watching is disabled by default to improve performance.
+If you want to set up a watcher for all query strings, set `watchQuery: true`.
+
```js
export default {
watchQuery: ['page']
diff --git a/en/examples/auth-external-jwt.md b/en/examples/auth-external-jwt.md
index 89f0ad0..22c3d63 100644
--- a/en/examples/auth-external-jwt.md
+++ b/en/examples/auth-external-jwt.md
@@ -9,6 +9,10 @@ code: https://github.com/ahadyekta/nuxt-auth-external-jwt
In auth-routes example both api and nuxt start together and use one Node.js server instance. However, sometimes we should work with external api with jsonWebToken. In this example it will be explained in a simple way.
+## Official `auth-module`
+
+If you want to implement complex authentication flows, for example OAuth2, we suggest using the official [`auth-module`](https://github.com/nuxt-community/auth-module)
+
## Structure
Since Nuxt.js provides both server and client rendering and the cookie of browser is different from cookie of the Node.js server, we should push token data to some storage that can be accessible in both sides.
@@ -33,17 +37,17 @@ npm install cookieparser --save
Then inside page directory make a `login.vue` file, and inside the script section, add:
```js
-import Cookie from 'js-cookie'
+const Cookie = process.client ? require('js-cookie') : undefined
export default {
middleware: 'notAuthenticated',
methods: {
- postLogin () {
- setTimeout(() => {
+ postLogin() {
+ setTimeout(() => { // we simulate the async request with timeout.
const auth = {
accessToken: 'someStringGotFromApiServiceWithAjax'
}
- this.$store.commit('update', auth) // mutating to store for client rendering
+ this.$store.commit('setAuth', auth) // mutating to store for client rendering
Cookie.set('auth', auth) // saving token in cookie for server rendering
this.$router.push('/')
}, 1000)
@@ -61,26 +65,30 @@ After that make `index.js` in `store` directory like below :
```javascript
import Vuex from 'vuex'
-var cookieparser = require('cookieparser')
+const cookieparser = process.server ? require('cookieparser') : undefined
const createStore = () => {
return new Vuex.Store({
- state: {
+ state: () => ({
auth: null
- },
+ }),
mutations: {
- update (state, data) {
- state.auth = data
+ setAuth(state, auth) {
+ state.auth = auth
}
},
actions: {
- nuxtServerInit ({ commit }, { req }) {
- let accessToken = null
+ nuxtServerInit({ commit }, { req }) {
+ let auth = null
if (req.headers.cookie) {
- var parsed = cookieparser.parse(req.headers.cookie)
- accessToken = JSON.parse(parsed.auth)
+ const parsed = cookieparser.parse(req.headers.cookie)
+ try {
+ auth = JSON.parse(parsed.auth)
+ } catch (err) {
+ // No valid cookie found
+ }
}
- commit('update', accessToken)
+ commit('setAuth', auth)
}
}
})
@@ -116,3 +124,23 @@ export default function ({ store, redirect }) {
```
> Note: use `authenticated` middleware for pages which need authentication and use `notAuthenticated` middleware inside the login/register and similar pages.
+
+## Logging out the User
+Finally to allow the user to logout of the system, we can remove the cookie:
+
+```javascript
+const Cookie = process.client ? require('js-cookie') : undefined
+
+export default {
+ methods: {
+ logout() {
+ // Code will also be required to invalidate the JWT Cookie on external API
+ Cookie.remove('auth')
+ this.$store.commit('setAuth', null)
+ }
+ }
+}
+```
+
+> Note: refer to the method using @click="logout"
+
diff --git a/en/examples/auth-routes.md b/en/examples/auth-routes.md
index 195c42b..6e789a8 100644
--- a/en/examples/auth-routes.md
+++ b/en/examples/auth-routes.md
@@ -10,6 +10,10 @@ liveedit: https://gomix.com/#!/project/nuxt-auth-routes
> Nuxt.js can be used to create authenticated routes easily.
+## Official `auth-module`
+
+If you want to implement complex authentication flows, for example OAuth2, we suggest using the official [`auth-module`](https://github.com/nuxt-community/auth-module)
+
## Using Express and Sessions
To add the sessions feature in our application, we will use `express` and `express-session`, for this, we need to use Nuxt.js programmatically.
@@ -100,9 +104,9 @@ require('whatwg-fetch')
const store = () => new Vuex.Store({
- state: {
+ state: () => ({
authUser: null
- },
+ }),
mutations: {
SET_USER: function (state, user) {
diff --git a/en/examples/i18n.md b/en/examples/i18n.md
index ab3b9c6..23a3e20 100644
--- a/en/examples/i18n.md
+++ b/en/examples/i18n.md
@@ -5,3 +5,7 @@ github: i18n
livedemo: https://i18n.nuxtjs.org
documentation: /guide/routing#middleware
---
+
+## Official `i18n-module`
+
+If you want to implement complex authentication flows, for example OAuth2, we suggest using the official [`i18n-module`](https://github.com/nuxt-community/nuxt-i18n/)
diff --git a/en/examples/named-views.md b/en/examples/named-views.md
new file mode 100644
index 0000000..e6fc087
--- /dev/null
+++ b/en/examples/named-views.md
@@ -0,0 +1,7 @@
+---
+title: Named Views
+description: Named Views example with Nuxt.js
+github: named-views
+livedemo: https://named-views.nuxtjs.org
+documentation: /guide/routing#named-views
+---
diff --git a/en/faq/appengine-deployment.md b/en/faq/appengine-deployment.md
new file mode 100644
index 0000000..db91b11
--- /dev/null
+++ b/en/faq/appengine-deployment.md
@@ -0,0 +1,59 @@
+---
+title: Google App Engine Deployment
+description: How to deploy Nuxt.js on Google App Engine?
+---
+
+# How to deploy on Google App Engine?
+
+Deploying to [Google App Engine](https://cloud.google.com/appengine/) is a fast and easy solution for hosting your universal Nuxt application on Google's Cloud Services.
+
+In this guide, we build the application locally and then simply upload the entire project folder to Google App Engine. After the upload, Google App Engine will automatically start the `start` script in our package.json and your app will be available immediately.
+
+## Getting Started
+
+Make sure you have a Google Cloud Account, a project and an empty Google App Engine app set up on [Google App Engine](https://cloud.google.com/appengine/). Furthermore, make sure to download and install the Cloud SDK (CLI) from Google as explained [here](https://cloud.google.com/sdk/) and log into your Google Cloud Account.
+
+## Configure your application
+
+All you need to add to your universal Nuxt app for deploying it to the App Engine is a file called `app.yaml`. Create a new file with that name in your root project directory and add the following content:
+
+```yaml
+runtime: nodejs10
+
+instance_class: F2
+
+handlers:
+ - url: /_nuxt
+ static_dir: .nuxt/dist/client
+ secure: always
+
+ - url: /(.*\.(gif|png|jpg|ico|txt))$
+ static_files: static/\1
+ upload: static/.*\.(gif|png|jpg|ico|txt)$
+ secure: always
+
+ - url: /.*
+ script: auto
+ secure: always
+
+env_variables:
+ HOST: '0.0.0.0'
+ NODE_ENV: 'production'
+```
+
+## Build and deploy the app
+
+Now build your app with `npm run build`.
+
+At this point, your app is ready to be uploaded to Google App Engine. Now just run the following command:
+
+```
+gcloud app deploy app.yaml --project <project-id>
+```
+
+Voilà! Your Nuxt.js application is now hosted on Google App Engine!
+
+## Further Information
+
+- The `instance_class` attribute in your app.yaml file sets the class of your app instance. Instance F2 is not completely free, but has the minimum memory needed to run a Nuxt application.
+- Make sure to put the project-id and not the project-name in the deploy command. These are two different things - but easy to mix up.
diff --git a/en/faq/deployment-aws-s3-cloudfront.md b/en/faq/deployment-aws-s3-cloudfront.md
index 35702b2..d4db15c 100644
--- a/en/faq/deployment-aws-s3-cloudfront.md
+++ b/en/faq/deployment-aws-s3-cloudfront.md
@@ -9,13 +9,32 @@ AWS is Amazon Web Services.
S3 is their static storage which can be configured for Static Site Hosting.
Cloudfront is their CDN (content delivery network)
-Hosting a Nuxt "Universal App" on AWS w/ S3 + Cloudfront is powerful and cheap.
+Hosting a **static generated** Nuxt app on AWS w/ S3 + Cloudfront is powerful and cheap.
> AWS is a death by 1000 paper cuts. If we missed a step, please submit a PR to update this document.
## Overview
-We will use the [Gulp](https://gulpjs.com/) build system for this. `Gulp` is a mature build system with handy utilities we can use.
+We'll host super cheap with some AWS services. Briefly:
+
+ - S3
+ - cloud data "bucket" for our website files
+ - can be configured to host static websites
+ - CloudFront
+ - a CDN (content delivery network)
+ - offers free HTTPS certs
+ - Makes your site load faster
+
+We'll push the site like this:
+
+```
+Nuxt Generate -> Local folder -> AWS S3 Bucket -> AWS Cloudfront CDN -> Browser
+ [ nuxt generate ] [ gulp deploy ]
+ [ deploy.sh ]
+```
+
+First, we'll generate the site with `nuxt generate`.
+Then, we'll use [Gulp](https://gulpjs.com/) to publish the files to a S3 bucket and invalidate a CloudFront CDN.
- [gulp](https://www.npmjs.com/package/gulp)
- [gulp-awspublish](https://www.npmjs.com/package/gulp-awspublish)
@@ -28,30 +47,38 @@ Our deploy script needs these environment variables set:
- AWS_ACCESS_KEY_ID="key"
- AWS_SECRET_ACCESS_KEY="secret"
+We'll have these files:
+
+```
+deploy.sh - run `nuxt generate` and `gulp deploy`
+gulpfile.js - `gulp deploy` code to push files to S3 and invalidate CloudFront
+```
+
## Setting it up
1. Make a S3 bucket and configure it for static site hosting
- 2. Create a cloudfront distribution
+ 2. Create a CloudFront distribution
3. Configure security access
4. Setup build script in your project
-### 1. Setup your AWS S3 bucket and 2. Setup your Cloudfront Distribution
+### 1. AWS: Setup your S3 bucket
+### 2. AWS: Setup your CloudFront Distribution
-For steps 1. and 2, follow this [tutorial to setup your S3 and Cloudfront](https://reidweb.com/2017/02/06/cloudfront-cdn-tutorial/)
+For steps 1. and 2, follow this [tutorial to setup your S3 and CloudFront](https://reidweb.com/2017/02/06/cloudfront-cdn-tutorial/)
You should now have this data:
- AWS_BUCKET_NAME="example.com"
- AWS_CLOUDFRONT="UPPERCASE"
-### 3. Configure security access
+### 3. AWS: Configure security access
For step 3, we need to create a user that can:
- Update the bucket contents
- - Invalidate the cloudfront distribution (propagates changes to users faster)
+ - Invalidate the CloudFront distribution (propagates changes to users faster)
[Create a programmatic user with this policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html):
-> NOTE: replace 2x `example.com` with your S3 bucket name below. This policy allows pushing to the specified bucket, and invalidating any cloudfront distribution.
+> NOTE: replace 2x `example.com` with your S3 bucket name below. This policy allows pushing to the specified bucket, and invalidating any CloudFront distribution.
``` json
{
@@ -96,28 +123,27 @@ You should now have this data:
- AWS_ACCESS_KEY_ID="key"
- AWS_SECRET_ACCESS_KEY="secret"
-### 4. Setup your project's build script
-
-4.1) Add Gulp to your project and to your command line
-``` bash
-npm install --save-dev gulp gulp-awspublish gulp-cloudfront-invalidate-aws-publish concurrent-transform
-npm install -g gulp
-```
+### 4. Laptop: Setup your project's build script
-4.2) Create a `deploy.sh` script. See optional [nvm (node version manager)](https://github.com/creationix/nvm).
+4.1) Create a `deploy.sh` script. See optional [nvm (node version manager)](https://github.com/creationix/nvm).
``` bash
#!/bin/bash
+export AWS_ACCESS_KEY_ID="key"
+export AWS_SECRET_ACCESS_KEY="secret"
+export AWS_BUCKET_NAME="example.com"
+export AWS_CLOUDFRONT="UPPERCASE"
+
# Load nvm (node version manager), install node (version in .nvmrc), and npm install packages
[ -s "$HOME/.nvm/nvm.sh" ] && source "$HOME/.nvm/nvm.sh" && nvm use
# Npm install if not already.
[ ! -d "node_modules" ] && npm install
npm run generate
-AWS_ACCESS_KEY_ID="key" AWS_SECRET_ACCESS_KEY="secret" AWS_BUCKET_NAME="example.com" AWS_CLOUDFRONT="UPPERCASE" gulp deploy
+gulp deploy
```
-4.3) Make `deploy.sh` runnable and don't check into git
+4.2) Make `deploy.sh` runnable and DON'T CHECK INTO GIT (deploy.sh has secrets in it)
``` bash
chmod +x deploy.sh
echo "
@@ -130,6 +156,12 @@ deploy.sh
" >> .gitignore
```
+4.3) Add Gulp to your project and to your command line
+``` bash
+npm install --save-dev gulp gulp-awspublish gulp-cloudfront-invalidate-aws-publish concurrent-transform
+npm install -g gulp
+```
+
4.4) Create a `gulpfile.js` with the build script
``` javascript
@@ -149,7 +181,7 @@ var config = {
// Optional
deleteOldVersions: false, // NOT FOR PRODUCTION
- distribution: process.env.AWS_CLOUDFRONT, // Cloudfront distribution ID
+ distribution: process.env.AWS_CLOUDFRONT, // CloudFront distribution ID
region: process.env.AWS_DEFAULT_REGION,
headers: { /*'Cache-Control': 'max-age=315360000, no-transform, public',*/ },
@@ -158,7 +190,7 @@ var config = {
indexRootPath: true,
cacheFileName: '.awspublish',
concurrentUploads: 10,
- wait: true, // wait for Cloudfront invalidation to complete (about 30-60 seconds)
+ wait: true, // wait for CloudFront invalidation to complete (about 30-60 seconds)
}
gulp.task('deploy', function() {
@@ -173,10 +205,10 @@ gulp.task('deploy', function() {
// Invalidate CDN
if (config.distribution) {
- console.log('Configured with Cloudfront distribution');
+ console.log('Configured with CloudFront distribution');
g = g.pipe(cloudfront(config));
} else {
- console.log('No Cloudfront distribution configured - skipping CDN invalidation');
+ console.log('No CloudFront distribution configured - skipping CDN invalidation');
}
// Delete removed files
@@ -196,8 +228,8 @@ Run it:
```
You should get an output similar to this:
-```
-$ ./deploy.sh Mod master
+``` bash
+$ ./deploy.sh
Found '/home/michael/scm/example.com/www/.nvmrc' with version <8>
Now using node v8.11.2 (npm v5.6.0)
@@ -259,7 +291,7 @@ server-bundle.json 306 kB [emitted]
nuxt:generate Generate done +0ms
[21:25:27] Using gulpfile ~/scm/example.com/www/gulpfile.js
[21:25:27] Starting 'deploy'...
-Configured with Cloudfront distribution
+Configured with CloudFront distribution
[21:25:27] [cache] README.md
[21:25:27] [cache] android-chrome-192x192.png
[21:25:27] [cache] android-chrome-512x512.png
@@ -292,17 +324,8 @@ Configured with Cloudfront distribution
[21:25:38] [update] how/index.html
[21:25:43] [create] videos/flag.webm
[21:25:43] [update] index.html
-[21:25:43] Cloudfront invalidation created: I16NXXXXX4JDOA
+[21:25:43] CloudFront invalidation created: I16NXXXXX4JDOA
[21:26:09] Finished 'deploy' after 42 s
```
-`deploy.sh` first runs `nuxt generate`, then runs `gulp deploy` with our environment variables set.
-
-Note that the `Cloudfront invalidation created: XXXX` is the only output from the cloudfront invalidation npm package. If you don't see that, it's not working.
-
-
-
-
-
-
-
+Note that the `ClouFront invalidation created: XXXX` is the only output from the CloudFront invalidation npm package. If you don't see that, it's not working.
diff --git a/en/faq/duplicated-meta-tags.md b/en/faq/duplicated-meta-tags.md
index 2d11ead..d2a7f01 100644
--- a/en/faq/duplicated-meta-tags.md
+++ b/en/faq/duplicated-meta-tags.md
@@ -7,7 +7,11 @@ description: Duplicated Meta tags with Nuxt.js?
This is a "feature" of [vue-meta](https://github.com/declandewet/vue-meta), please take a look at the [documentation of head elements](/guide/views#html-head).
-> To avoid any duplication when used in child component, please provide a unique identifier with the `hid` key, please [read more](https://github.com/declandewet/vue-meta#lists-of-tags) about it.
+<div class="Alert">
+
+To avoid any duplication when used in child component, please give a unique identifier with the <code>hid</code> key. [Learn more](https://github.com/declandewet/vue-meta#lists-of-tags).
+
+</div>
For the meta description, you need to add the unique identifier `hid` so vue-meta will know that it has to overwrite the default tag.
diff --git a/en/faq/extend-webpack.md b/en/faq/extend-webpack.md
index 99032e5..2ff08d5 100644
--- a/en/faq/extend-webpack.md
+++ b/en/faq/extend-webpack.md
@@ -8,7 +8,7 @@ description: How to extend webpack config into my Nuxt.js application ?
You can extend the webpack configuration via the `extend` option in your `nuxt.config.js`:
```js
-module.exports = {
+export default {
build: {
extend (config, { isDev, isClient }) {
// ...
diff --git a/en/faq/external-resources.md b/en/faq/external-resources.md
index a50db2f..8ba44d2 100644
--- a/en/faq/external-resources.md
+++ b/en/faq/external-resources.md
@@ -10,7 +10,7 @@ description: How to use external resources with Nuxt.js?
Include your resources in the `nuxt.config.js` file:
```js
-module.exports = {
+export default {
head: {
script: [
{ src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' }
@@ -41,7 +41,7 @@ export default {
link: [
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto' }
]
- }
+ }
}
}
</script>
diff --git a/en/faq/github-pages.md b/en/faq/github-pages.md
index 156b172..fefb21d 100644
--- a/en/faq/github-pages.md
+++ b/en/faq/github-pages.md
@@ -15,7 +15,11 @@ npm run generate
It will create a `dist` folder with everything inside ready to be deployed on GitHub Pages hosting. Branch `gh-pages` for project repository OR branch `master` for user or organization site
-<p class="Alert Alert--nuxt-green"><b>Info:</b> If you use a custom domain for your GitHub Pages and put `CNAME` file, it is recommended that CNAME file is put in the `static` directory. [More documentation](/guide/assets#static) about it.</p>
+<div class="Alert Alert--nuxt-green">
+
+<b>Info:</b> If you use a custom domain for your GitHub Pages and put `CNAME` file, it is recommended that CNAME file is put in the `static` directory. [More documentation](/guide/assets#static) about it.
+
+</div>
## Deploying to GitHub Pages for repository
@@ -26,7 +30,7 @@ If you deployed `dist` folder without adding [router base](https://nuxtjs.org/ap
To fix the issue we need to add [router base](https://nuxtjs.org/api/configuration-router/#base) configuration in `nuxt.config.js`:
```js
-module.exports = {
+export default {
router: {
base: '/<repository-name>/'
}
@@ -46,7 +50,7 @@ const routerBase = process.env.DEPLOY_ENV === 'GH_PAGES' ? {
}
} : {}
-module.exports = {
+export default {
...routerBase
}
```
diff --git a/en/faq/google-analytics.md b/en/faq/google-analytics.md
index 173beb5..50ba540 100644
--- a/en/faq/google-analytics.md
+++ b/en/faq/google-analytics.md
@@ -48,7 +48,7 @@ Then, we tell Nuxt.js to import it in our main application:
`nuxt.config.js`
```js
-module.exports = {
+export default {
plugins: [
{ src: '~plugins/ga.js', ssr: false }
]
@@ -57,4 +57,8 @@ module.exports = {
Voilà, Google Analytics is integrated into your Nuxt.js application and will track every page view!
-<p class="Alert Alert--nuxt-green"><b>Info:</b> you can use this method for any other tracking service.</p>
+<div class="Alert Alert--nuxt-green">
+
+<b>Info:</b> you can use this method for any other tracking service.
+
+</div>
diff --git a/en/faq/heroku-deployment.md b/en/faq/heroku-deployment.md
index fac0d0b..7381efe 100644
--- a/en/faq/heroku-deployment.md
+++ b/en/faq/heroku-deployment.md
@@ -35,10 +35,24 @@ Then, we tell Heroku to launch `npm run build` via the `heroku-postbuild` script
}
```
+Heroku uses a [Procfile](https://devcenter.heroku.com/articles/procfile) (name the file `Procfile` with no file extension) that specifies the commands that are executed by the apps dynos. To start the Procfile will be very simple, and needs to contain the following line:
+
+```
+web: npm run start
+```
+
+This will instruct run the `npm run start` command and tell heroku to direct external HTTP traffic to it.
+
Finally, we can push the app on Heroku with:
```bash
git push heroku master
```
+To deploy a non-master brach to Heroku use:
+```bash
+git push heroku develop:master
+```
+where `develop` is the name of your branch.
+
Voilà! Your Nuxt.js application is now hosted on Heroku!
diff --git a/en/faq/host-port.md b/en/faq/host-port.md
index cc9e423..ebec7e6 100644
--- a/en/faq/host-port.md
+++ b/en/faq/host-port.md
@@ -5,8 +5,9 @@ description: How to edit host and port with Nuxt.js?
# How to edit host and port?
-You can configure the connection variables in different ways, listed **from highest to lowest priority**:
+You can configure the connection variables in different ways. They are listed **from highest to lowest priority**.
+> **Note:** If `port` is assigned the string value of `'0'` (not `0`, which is falsy), a random port will be assigned to your Nuxt application.
## As direct arguments
@@ -20,13 +21,12 @@ Or
}
```
+## Configure in `nuxt.config.js`:
-## Configure in `nuxt.config.json`:
-
-Inside your `nuxt.config.json`:
+Inside your `nuxt.config.js`:
```js
-module.exports = {
+export default {
server: {
port: 8000, // default: 3000
host: '0.0.0.0', // default: localhost
@@ -83,4 +83,4 @@ Inside your `package.json`:
"scripts": {
"dev": "nuxt"
}
-```
\ No newline at end of file
+```
diff --git a/en/faq/http-proxy.md b/en/faq/http-proxy.md
new file mode 100644
index 0000000..a49e4df
--- /dev/null
+++ b/en/faq/http-proxy.md
@@ -0,0 +1,29 @@
+---
+title: Cross origin resource sharing
+description: How to share cross origin resource?
+---
+
+# How to share cross-origin resource?
+
+[The solution of cross origin resource sharing in Nuxt.js ](https://github.com/nuxt-community/proxy-module#readme)
+
+```
+npm i @nuxtjs/proxy -D
+```
+
+In nuxt.config.js
+
+```
+ modules: [
+ '@nuxtjs/axios',
+ '@nuxtjs/proxy'
+ ],
+proxy: {
+ '/api': {
+ target: 'http://example.com',
+ pathRewrite: {
+ '^/api' : '/'
+ }
+ }
+}
+```
diff --git a/en/faq/ios-phone-numbers.md b/en/faq/ios-phone-numbers.md
new file mode 100644
index 0000000..30b4537
--- /dev/null
+++ b/en/faq/ios-phone-numbers.md
@@ -0,0 +1,21 @@
+---
+title: iOS and phone numbers
+description: Safari on iOS changes phone numbers to links which can cause a render mismatch
+---
+
+# iOS and phone numbers
+
+If you include telephone numbers in your Nuxt page, make sure to directly wrap them into a link:
+
+```html
+<!-- Example phone number: +7 (982) 536-50-77 -->
+
+<template>
+ <a href="tel: +7 (982) 536-50-77">+7 (982) 536-50-77</a>
+</template>
+
+```
+
+Otherwise, some mobile Safari versions will automatically transform these numbers into links. Sounds good and
+helpful at first glance but this will trigger a `NodeMismatch` warning as the SSR content doesn't match the website
+content anymore. This can make your app unusable on these Safari versions.
diff --git a/en/faq/jsx.md b/en/faq/jsx.md
index 2af77ff..60f1a87 100644
--- a/en/faq/jsx.md
+++ b/en/faq/jsx.md
@@ -5,7 +5,7 @@ description: How to use JSX with Nuxt.js?
# How to use JSX?
-Nuxt.js uses the official [babel-preset-vue-app](https://github.com/vuejs/babel-preset-vue-app) for babel default configuration, so you can use JSX in your components.
+Nuxt.js uses [@nuxt/babel-preset-app](https://github.com/nuxt/nuxt.js/tree/dev/packages/babel-preset-app), which is based on the official [@vue/babel-preset-app](https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/babel-preset-app) for babel default configuration, so you can use JSX in your components.
You can now use JSX in the `render` method of your components:
@@ -22,6 +22,10 @@ export default {
</script>
```
-<p class="Alert Alert--info">Aliasing `createElement` to `h` is a common convention you’ll see in the Vue ecosystem but is actually optional for JSX since it [automatically injects](https://github.com/vuejs/babel-plugin-transform-vue-jsx#h-auto-injection) `const h = this.$createElement` in any method and getter (not functions or arrow functions) declared in ES2015 syntax that has JSX so you can drop the (h) parameter.</p>
+<div class="Alert Alert--orange">
+
+Aliasing `createElement` to `h` is a common convention you’ll see in the Vue ecosystem but is actually optional for JSX since it [automatically injects](https://github.com/vuejs/babel-plugin-transform-vue-jsx#h-auto-injection) `const h = this.$createElement` in any method and getter (not functions or arrow functions) declared in ES2015 syntax that has JSX so you can drop the (h) parameter.
+
+</div>
You can learn more about how to use it in the [JSX section](https://vuejs.org/v2/guide/render-function.html#JSX) of the Vue.js documentation.
diff --git a/en/faq/menu.json b/en/faq/menu.json
index aeeabe3..701c971 100644
--- a/en/faq/menu.json
+++ b/en/faq/menu.json
@@ -10,7 +10,8 @@
{ "name": "How to add webpack plugins?", "to": "/webpack-plugins" },
{ "name": "How to edit HOST and PORT?", "to": "/host-port" },
{ "name": "How to use cached components?", "to": "/cached-components" },
- { "name": "How to use Google Analytics?", "to": "/google-analytics" }
+ { "name": "How to use Google Analytics?", "to": "/google-analytics" },
+ { "name": "How to share cross origin resource?", "to": "/http-proxy"}
]
},
{
@@ -19,7 +20,8 @@
{ "name": "window/document undefined?", "to": "/window-document-undefined" },
{ "name": "Why a CSS Flash appears?", "to": "/css-flash" },
{ "name": "Async data in components?", "to": "/async-data-components" },
- { "name": "Duplicated Meta Tags?", "to": "/duplicated-meta-tags" }
+ { "name": "Duplicated Meta Tags?", "to": "/duplicated-meta-tags" },
+ { "name": "iOS and phone numbers", "to": "/ios-phone-numbers" }
]
},
{
@@ -28,6 +30,7 @@
{ "name": "Deploy on AWS w/ S3 and Cloudfront", "to": "/deployment-aws-s3-cloudfront" },
{ "name": "Deploy on Dokku", "to": "/dokku-deployment" },
{ "name": "Deploy on GitHub", "to": "/github-pages" },
+ { "name": "Deploy on Google App Engine", "to": "/appengine-deployment" },
{ "name": "Deploy on Heroku", "to": "/heroku-deployment" },
{ "name": "Deploy on Netlify", "to": "/netlify-deployment" },
{ "name": "Deploy on Now", "to": "/now-deployment" },
diff --git a/en/faq/netlify-deployment.md b/en/faq/netlify-deployment.md
index b38e8b9..3032393 100644
--- a/en/faq/netlify-deployment.md
+++ b/en/faq/netlify-deployment.md
@@ -9,11 +9,11 @@ Deploying to [Netlify](https://www.netlify.com) is a low friction option for get
The core of the process leverages the `nuxt generate` command during deployment to build a static version of your Nuxt.js app into a `dist` directory. The contents of this directory are then deployed to a production URL.
-### Getting Started
+## Getting Started
Press the _"New site from Git"_ button on the Netlify dashboard. Authenticate with your repository host, select a repository to deploy, and continue. You should land on step 3: _"Build options, and deploy!"_
-### Configure:
+## Configure:
1. __Branch to deploy:__ `master`, or which-ever branch you prefer
1. __Build command:__ `npm run generate`
@@ -23,4 +23,4 @@ Press the _"New site from Git"_ button on the Netlify dashboard. Authenticate wi
Click _"Deploy site"_ to immediately trigger a deploy. Your Netlify site will be assigned a random URL and deployed using the `nuxt generate` command.
-Voilà! Your Nuxt.js application is now hosted on Netlify!
\ No newline at end of file
+Voilà! Your Nuxt.js application is now hosted on Netlify!
diff --git a/en/faq/nginx-proxy.md b/en/faq/nginx-proxy.md
index 160e48b..9aa2a03 100644
--- a/en/faq/nginx-proxy.md
+++ b/en/faq/nginx-proxy.md
@@ -35,9 +35,93 @@ server {
}
```
+# Using nginx with generated pages and a caching proxy as fallback
+
+If you have a high volume website with regularly changing content, you might want to benefit from Nuxt generate capabilities and [nginx caching](https://www.nginx.com/blog/nginx-caching-guide).
+
+Below is an example configuration. Keep in mind that:
+- root folder should be the same as set by [configuration generate.dir](/api/configuration-generate#dir)
+- expire headers set by Nuxt are stripped (due to the cache)
+- both Nuxt as nginx can set additional headers, it's advised to choose one (if in doubt, choose nginx)
+- if your site is mostly static, increase the `proxy_cache_path inactive` and `proxy_cache_valid` numbers
+
+If you don't generate your routes but still wish to benefit from nginx cache:
+- remove the `root` entry
+- change `location @proxy {` to `location / {`
+- remove the other 2 `location` entries
+
+
+```nginx
+proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=nuxt-cache:25m max_size=1g inactive=60m use_temp_path=off;
+
+map $sent_http_content_type $expires {
+ "text/html" 1h; # set this to your needs
+ "text/html; charset=utf-8" 1h; # set this to your needs
+ default 7d; # set this to your needs
+}
+
+server {
+ listen 80; # the port nginx is listening on
+ server_name your-domain; # setup your domain here
+
+ gzip on;
+ gzip_types text/plain application/xml text/css application/javascript;
+ gzip_min_length 1000;
+
+ charset utf-8;
+
+ root /var/www/NUXT_PROJECT_PATH/dist
+
+ location ~* \.(?:ico|gif|jpe?g|png|woff2?|eot|otf|ttf|svg|js|css)$ {
+ expires $expires;
+ add_header Pragma public;
+ add_header Cache-Control "public";
+
+ try_files $uri $uri/ @proxy;
+ }
+
+ location / {
+ expires $expires;
+ add_header Content-Security-Policy "default-src 'self' 'unsafe-inline';";
+ add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
+ add_header X-Frame-Options "SAMEORIGIN";
+
+ try_files $uri $uri/index.html @proxy; # for generate.subFolders: true
+ # try_files $uri $uri.html @proxy; # for generate.subFolders: false
+ }
+
+ location @proxy {
+ expires $expires;
+ add_header Content-Security-Policy "default-src 'self' 'unsafe-inline';";
+ add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
+ add_header X-Frame-Options "SAMEORIGIN";
+ add_header X-Cache-Status $upstream_cache_status;
+
+ proxy_redirect off;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_ignore_headers Cache-Control;
+ proxy_http_version 1.1;
+ proxy_read_timeout 1m;
+ proxy_connect_timeout 1m;
+ proxy_pass http://127.0.0.1:3000; # set the adress of the Node.js instance here
+ proxy_cache nuxt-cache;
+ proxy_cache_bypass $arg_nocache; # probably better to change this
+ proxy_cache_valid 200 302 60m; # set this to your needs
+ proxy_cache_valid 404 1m; # set this to your needs
+ proxy_cache_lock on;
+ proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
+ proxy_cache_key $uri$is_args$args;
+ proxy_cache_purge PURGE from 127.0.0.1;
+ }
+}
+```
+
# nginx configuration for Laravel Forge
-Change `YOUR_WEBSITE_FOLDER` to your web site folder and `YOUR_WEBSITE_DOMAIN` to your website URL. Laravel Forge will have filled out these values for you but be sure to double check.
+Change `YOUR_WEBSITE_FOLDER` to your website folder and `YOUR_WEBSITE_DOMAIN` to your website URL. Laravel Forge will have filled out these values for you but be sure to double check.
```nginx
# FORGE CONFIG (DOT NOT REMOVE!)
diff --git a/en/faq/now-deployment.md b/en/faq/now-deployment.md
index 0568055..ec93bc7 100644
--- a/en/faq/now-deployment.md
+++ b/en/faq/now-deployment.md
@@ -5,6 +5,40 @@ description: How to deploy Nuxt.js app with Now?
# How to deploy with Now?
+## Now V2
+
+**Note:** You cannot deploy a server-side-rendered Nuxt app with Now V2 right now. Please use Now V1 for such apps.
+
+To deploy with [ZEIT Now](https://zeit.co/now) you need to customize `package.json` add create a `now.json` config.
+
+* Add `now-build` script command to `package.json`:
+ * For SPA (without SSR):
+ ```js
+ "scripts": {
+ ...
+ "now-build": "nuxt build --spa"
+ }
+ ```
+ * For Static Generated (Pre Rendering):
+ ```js
+ "scripts": {
+ ...
+ "now-build": "nuxt generate"
+ }
+ ```
+* Create `now.json` and define `builds`
+ ```json
+ {
+ "version": 2,
+ "builds": [
+ { "src": "package.json", "use": "@now/static-build" }
+ ]
+ }
+ ```
+* Run `now` and enjoy!
+
+## Now V1 (legacy)
+
To deploy with [now.sh](https://zeit.co/now) a `package.json` like follows is recommended:
```json
diff --git a/en/faq/postcss-plugins.md b/en/faq/postcss-plugins.md
index 5ea17d1..788903d 100644
--- a/en/faq/postcss-plugins.md
+++ b/en/faq/postcss-plugins.md
@@ -8,13 +8,25 @@ description: How to add PostCSS plugins?
In your `nuxt.config.js` file:
```js
-module.exports = {
+export default {
build: {
- postcss: [
- require('postcss-nested')(),
- require('postcss-responsive-type')(),
- require('postcss-hexrgba')(),
- ]
+ postcss: {
+ // Add plugin names as key and arguments as value
+ // Install them before as dependencies with npm or yarn
+ plugins: {
+ // Disable a plugin by passing false as value
+ 'postcss-url': false,
+ 'postcss-nested': {},
+ 'postcss-responsive-type': {},
+ 'postcss-hexrgba': {}
+ },
+ preset: {
+ // Change the postcss-preset-env settings
+ autoprefixer: {
+ grid: true
+ }
+ }
+ }
}
}
```
diff --git a/en/faq/pre-processors.md b/en/faq/pre-processors.md
index 81ff0bd..19ecebb 100644
--- a/en/faq/pre-processors.md
+++ b/en/faq/pre-processors.md
@@ -15,7 +15,7 @@ Example of our `pages/index.vue` using [Pug](https://github.com/pugjs/pug), [Cof
</template>
<script lang="coffee">
-module.exports = data: ->
+export default data: ->
{ name: 'World' }
</script>
diff --git a/en/faq/surge-deployment.md b/en/faq/surge-deployment.md
index ffb3e97..873e261 100644
--- a/en/faq/surge-deployment.md
+++ b/en/faq/surge-deployment.md
@@ -31,4 +31,8 @@ Done :)
If you have a project with [dynamic routes](/guide/routing#dynamic-routes), take a look at the [`generate` configuration](/api/configuration-generate) to tell Nuxt.js how to generate these dynamic routes.
-<div class="Alert">When generating your web application with `nuxt generate`, [the context](/api) given to [`data`](/guide/async-data#the-data-method) and [`fetch`](/guide/vuex-store#the-fetch-method) will not have `req` and `res`.</div>
+<div class="Alert">
+
+When generating your web application with `nuxt generate`, [the context](/api) given to [asyncData](/guide/async-data) and [`fetch`](/guide/vuex-store#the-fetch-method) will not have `req` and `res`.
+
+</div>
diff --git a/en/faq/webpack-plugins.md b/en/faq/webpack-plugins.md
index f946a14..fa00bc0 100644
--- a/en/faq/webpack-plugins.md
+++ b/en/faq/webpack-plugins.md
@@ -8,9 +8,9 @@ description: How to add webpack plugins into my Nuxt.js application?
In your `nuxt.config.js` file:
```js
-const webpack = require('webpack')
+import webpack from 'webpack'
-module.exports = {
+export default {
build: {
plugins: [
new webpack.ProvidePlugin({
diff --git a/en/faq/window-document-undefined.md b/en/faq/window-document-undefined.md
index 3704616..67cc3e5 100644
--- a/en/faq/window-document-undefined.md
+++ b/en/faq/window-document-undefined.md
@@ -5,20 +5,12 @@ description: window or document undefined with Nuxt.js?
# window or document undefined?
-This is due to the server-side rendering. If you need to specify that you want to import a resource only on the client-side, you need to use the `process.browser` variable.
+This is due to the server-side rendering. If you need to specify that you want to import a resource only on the client-side, you need to use the `process.client` variable.
For example, in your `.vue` file:
```js
-if (process.browser) {
+if (process.client) {
require('external_library')
}
```
-
-If you are using this library within multiple files, we recommend that you add it into your [vendor bundle](/api/configuration-build#build-vendor) via `nuxt.config.js`:
-
-```js
- build: {
- vendor: ['external_library']
- }
-```
diff --git a/en/guide/assets.md b/en/guide/assets.md
index a94e1df..4a7b920 100644
--- a/en/guide/assets.md
+++ b/en/guide/assets.md
@@ -3,11 +3,12 @@ title: Assets
description: By default, Nuxt uses vue-loader, file-loader and url-loader webpack loaders for strong assets serving. You can also use Static directory for static assets.
---
-> By default, Nuxt uses vue-loader, file-loader and url-loader webpack loaders for strong assets serving. You can also use Static directory for static assets.
+> By default, Nuxt uses vue-loader, file-loader and url-loader webpack loaders for strong assets serving. You can also use the `static` directory for static assets.
-## webpacked
+## Webpack
-By default, [vue-loader](http://vue-loader.vuejs.org/) automatically processes your style and template files with css-loader and the Vue template compiler. In this compilation process, all asset URLs such as `<img src="...">`, `background: url(...)` and CSS `@import` are resolved as module dependencies.
+[vue-loader](http://vue-loader.vuejs.org/) automatically processes your style and template files with `css-loader` and the Vue template compiler out of the box.
+In this compilation process, all asset URLs such as `<img src="...">`, `background: url(...)` and CSS `@import` are resolved as module dependencies.
For example, we have this file tree:
@@ -18,11 +19,17 @@ For example, we have this file tree:
----| index.vue
```
-In your CSS, if you use `url('~/assets/image.png')`, it will be translated into `require('~/assets/image.png')`.
+If you use `url('~assets/image.png')` in your CSS, it will be *translated* into `require('~/assets/image.png')`.
-> Note that `~assets` (without a slash) won't work because `~` is a special indicator in `css-loader` and will be resolved to [modules](https://github.com/css-modules/css-modules).
+<div class="Alert Alert--orange">
-Or if in your `pages/index.vue` you use:
+**Warning:** Starting from Nuxt 2.0 the `~/` alias won't be resolved correctly in your CSS files.
+You must use `~assets` (without a slash) or the `@` alias in `url` CSS references, i.e. `background: url("~assets/banner.svg")`
+
+</div>
+
+
+Or if you reference that image in your `pages/index.vue`:
```html
<template>
@@ -38,17 +45,18 @@ createElement('img', { attrs: { src: require('~/assets/image.png') }})
Because `.png` is not a JavaScript file, Nuxt.js configures webpack to use [file-loader](https://github.com/webpack/file-loader) and [url-loader](https://github.com/webpack/url-loader) to handle them for you.
-The benefits of using file-loader and url-loader are:
+The benefits of these loaders are:
-- file-loader lets you designate where to copy and place the asset file, and how to name it using version hashes for better caching.
-- url-loader allows you to conditionally inline a file as base-64 data URL if they are smaller than a given threshold. This can reduce a number of HTTP requests for trivial files. If the file is larger than the threshold, it automatically falls back to file-loader.
+- `file-loader` lets you designate where to copy and place the asset file, and how to name it using version hashes for better caching. In production, you will benefit from long-term caching by default!
+- `url-loader` allows you to conditionally inline a file as base-64 data URL if they are smaller than a given threshold. This can reduce a number of HTTP requests for trivial files. If the file is larger than the threshold, it automatically falls back to file-loader.
-Actually, Nuxt.js default assets loaders configuration is:
+For those two loaders, the default configuration is:
```js
+// https://github.com/nuxt/nuxt.js/blob/dev/packages/builder/src/webpack/base.js#L204-L229
[
{
- test: /\.(png|jpe?g|gif|svg)$/,
+ test: /\.(png|jpe?g|gif|svg|webp)$/,
loader: 'url-loader',
query: {
limit: 1000, // 1kB
@@ -66,7 +74,9 @@ Actually, Nuxt.js default assets loaders configuration is:
]
```
-Which means that every file below 1 KB will be inlined as base-64 data URL. Otherwise, the image/font will be copied in its corresponding folder (under the `.nuxt` directory) with a name containing a version hashes for better caching.
+Which means that every file below 1 KB will be inlined as base-64 data URL.
+Otherwise, the image/font will be copied in its corresponding folder (under the `.nuxt` directory)
+with a name containing a version hash for better caching.
When launching our application with `nuxt`, our template in `pages/index.vue`:
@@ -76,23 +86,24 @@ When launching our application with `nuxt`, our template in `pages/index.vue`:
</template>
```
-Will be generated into:
+Will be transformed into:
```html
<img src="/_nuxt/img/image.0c61159.png">
```
-If you want to update these loaders or disable them, please use [build.extend](/api/configuration-build#extend).
+If you want to change the loader configurations, please use [build.extend](/api/configuration-build#extend).
+
## Static
-If you don't want to use webpacked Assets from the `assets` directory, you can create and use the `static` directory in your project root directory.
+If you don't want to use Webpack assets from the `assets` directory, you can create and use the `static` directory (in your project root folder).
-These files will be automatically served by Nuxt and accessible in your project root URL.
+All included files will be automatically served by Nuxt and are accessible through your project root URL. (`static/favicon.ico` will be available at `localhost:3000/favicon.ico`)
-This option is helpful for files like `robots.txt`, `sitemap.xml` or `CNAME` (for like GitHub Pages).
+This option is helpful for files like `robots.txt`, `sitemap.xml` or `CNAME` (which is important for GitHub Pages deployment).
-From your code you can then reference those files with `/` URLs:
+In your code, you can then reference these files relative to the root (`/`):
```html
<!-- Static image from static directory -->
diff --git a/en/guide/async-data.md b/en/guide/async-data.md
index 5e0260f..66e2c9a 100644
--- a/en/guide/async-data.md
+++ b/en/guide/async-data.md
@@ -3,22 +3,44 @@ title: Async Data
description: You may want to fetch data and render it on the server-side. Nuxt.js adds an `asyncData` method to let you handle async operations before setting the component data.
---
-> You may want to fetch data and render it on the server-side.
-Nuxt.js adds an `asyncData` method to let you handle async operations before setting the component data.
+> You may want to fetch data and render it on the server-side. Nuxt.js adds an `asyncData` method to let you handle async operations before initializing the component
-## The asyncData Method
+<div>
+ <a href="https://vueschool.io/courses/async-data-with-nuxtjs?friend=nuxt" target="_blank" class="Promote">
+ <img src="/async-data-with-nuxtjs.png" alt="AsyncData by vueschool"/>
+ <div class="Promote__Content">
+ <h4 class="Promote__Content__Title">Async Data with Nuxt.js</h4>
+ <p class="Promote__Content__Description">Learn how to manage asynchronous data with Nuxt.js.</p>
+ <p class="Promote__Content__Signature">Video courses made by VueSchool to support Nuxt.js developpement.</p>
+ </div>
+ </a>
+</div>
-Sometimes you just want to fetch data and pre-render it on the server without using a store. `asyncData` is called every time before loading the component (**only for pages components**). It can be called server-side or before navigating to the corresponding route. This method receives [the context](/api/context) as the first argument, you can use it to fetch some data and Nuxt.js will merge it with the component data.
+## The asyncData method
-<div class="Alert Alert--orange">You do **NOT** have access of the component instance through `this` inside `asyncData` because it is called **before initiating** the component.</div>
+Sometimes you just want to fetch data and pre-render it on the server without using a store.
+`asyncData` is called every time before loading the **page** component.
+It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.
+This method receives [the context](/api/context) as the first argument, you can use it to fetch some data and Nuxt.js will merge it with the component data.
+
+Nuxt.js will automatically merge the returned object with the component data.
+
+<div class="Alert Alert--orange">
+
+You do **NOT** have access of the component instance through `this` inside `asyncData` because it is called **before initiating** the component.
+
+</div>
Nuxt.js offers you different ways to use `asyncData`. Choose the one you're the most familiar with:
1. Returning a `Promise`. Nuxt.js will wait for the promise to be resolved before rendering the component.
2. Using the [async/await proposal](https://github.com/lukehoban/ecmascript-asyncawait) ([learn more about it](https://zeit.co/blog/async-and-await))
-3. Define a callback as second argument. It has to be called like this: `callback(err, data)`
-<div class="Alert Alert--grey">We are using [axios](https://github.com/mzabriskie/axios) to make isomorphic HTTP requests, we <strong>strongly recommend</strong> to use our [axios module](https://axios.nuxtjs.org/) for your Nuxt projects.</div>
+<div class="Alert Alert--grey">
+
+We are using [axios](https://github.com/mzabriskie/axios) to make isomorphic HTTP requests, we <strong>strongly recommend</strong> to use our [axios module](https://axios.nuxtjs.org/) for your Nuxt projects.
+
+</div>
### Returning a Promise
@@ -44,18 +66,6 @@ export default {
}
```
-### Using a callback
-
-```js
-export default {
- asyncData ({ params }, callback) {
- axios.get(`https://my-api/posts/${params.id}`)
- .then((res) => {
- callback(null, { title: res.data.title })
- })
- }
-}
-```
### Displaying the data
@@ -72,17 +82,50 @@ You can display the data inside your template like you're used to doing:
To see the list of available keys in `context`, take a look at the [API Essential `context`](/api/context).
+### Use `req`/`res` objects
+
+When `asyncData` is called on server side, you have access to the `req` and `res` objects of the user request.
+
+```js
+export default {
+ async asyncData ({ req, res }) {
+ // Please check if you are on the server side before
+ // using req and res
+ if (process.server) {
+ return { host: req.headers.host }
+ }
+
+ return {}
+ }
+}
+```
+
### Accessing dynamic route data
-You can use the context object injected into the `asyncData` property to access dynamic route data. For example, dynamic route params can be accessed using the name of the file or folder that configured it. So, if you define a file named `_slug.vue`, you can acccess it via `context.params.slug`.
+You can use the `context` parameter to access dynamic route data as well!
+For example, dynamic route params can be retrieved using the name of the file or folder that configured it.
+If you've defined a file named `_slug.vue` in your `pages` folder, you can access the value via `context.params.slug`:
+
+```js
+export default {
+ async asyncData ({ params }) {
+ const slug = params.slug // When calling /abc the slug will be "abc"
+ return { slug }
+ }
+}
+```
+
### Listening to query changes
-The `asyncData` method **is not called** on query string changes by default. If you want to change this behavior, for example when building a pagination component, you can setup parameters that should be listened to through the `watchQuery` property of your page component. Learn more on the [API `watchQuery` page](/api/pages-watchquery).
+The `asyncData` method **is not called** on query string changes by default.
+If you want to change this behavior, for example when building a pagination component,
+you can set up parameters that should be listened to with the `watchQuery` property of your page component.
+Learn more on the [API `watchQuery` page](/api/pages-watchquery) page.
## Handling Errors
-Nuxt.js adds the `error(params)` method in the `context`, you can call it to display the error page. `params.statusCode` will be also used to render the proper status code from the server-side.
+Nuxt.js adds the `error(params)` method in the `context`, which you can call to display the error page. `params.statusCode` will be also used to render the proper status code from the server-side.
Example with a `Promise`:
@@ -100,20 +143,5 @@ export default {
}
```
-If you're using the `callback` argument, you can call it directly with the error and Nuxt.js will call the `error` method for you:
-
-```js
-export default {
- asyncData ({ params }, callback) {
- axios.get(`https://my-api/posts/${params.id}`)
- .then((res) => {
- callback(null, { title: res.data.title })
- })
- .catch((e) => {
- callback({ statusCode: 404, message: 'Post not found' })
- })
- }
-}
-```
-To customize the error page, take a look at the [Guide Views layouts](/guide/views#layouts).
+To customize the error page, take a look at the [views guide](/guide/views#layouts) .
diff --git a/en/guide/commands.md b/en/guide/commands.md
index 1e533ff..0742589 100644
--- a/en/guide/commands.md
+++ b/en/guide/commands.md
@@ -19,7 +19,8 @@ description: Nuxt.js comes with a set of useful commands, both for development a
You can use `--help` with any command to get detailed usage. Common arguments are:
- **`--config-file` or `-c`:** specify the path to `nuxt.config.js` file.
-- **`--spa` or `-s`:** Runs command in SPA mode by disabling server side rendering.
+- **`--spa` or `-s`:** Runs command in SPA mode and disables server side rendering.
+- **`--unix-socket` or `-n`:** specify the path to a UNIX socket.
#### Using in package.json
@@ -36,7 +37,11 @@ You should put these commands in the `package.json`:
Then, you can launch your commands via `npm run <command>` (example: `npm run dev`).
-<p class="Alert Alert--nuxt-green"><b>Pro tip:</b> to pass arguments to npm commands, you need an extra <code>--</code> script name (example: <code>npm run dev -- --spa</code>).</p>
+<div class="Alert Alert--nuxt-green">
+
+<b>Pro tip:</b> to pass arguments to npm commands, you need an extra <code>--</code> script name (example: <code>npm run dev -- --spa</code>).
+
+</div>
## Development Environment
@@ -50,7 +55,7 @@ npm run dev
## Production Deployment
-Nuxt.js lets your choose between three modes to deploy your application: Server Rendered, SPA or Static Generated.
+Nuxt.js lets you choose between three modes to deploy your application: SSR, SPA or Static Generated.
### Server Rendered Deployment (Universal)
@@ -61,7 +66,9 @@ nuxt build
nuxt start
```
-You can also set `server.https` in `nuxt.config.js` with the same set of options passed to [`https.createServer`](https://nodejs.org/api/https.html), should you choose to serve Nuxt in HTTPS mode. Unix sockets are also available if you set the `server.socket` option in `nuxt.config.js` (or `-n` in the [CLI](https://nuxtjs.org/guide/commands#list-of-commands)). When using [Unix sockets](https://en.wikipedia.org/wiki/Berkeley_sockets), make sure not to set the `host` and `port` parameters otherwise the `socket` parameter is ignored.
+You can also set `server.https` in your `nuxt.config.js` with the same set of options passed to [`https.createServer`](https://nodejs.org/api/https.html), should you choose to serve Nuxt.js in HTTPS mode.
+Unix sockets are also available if you set the `server.socket` option in `nuxt.config.js` (or `-n` in the [CLI](https://nuxtjs.org/guide/commands#list-of-commands)).
+When using [Unix sockets](https://en.wikipedia.org/wiki/Berkeley_sockets), make sure not to set the `host` and `port` parameters otherwise the `socket` parameter is ignored.
The `package.json` like follows is recommended:
@@ -81,7 +88,7 @@ The `package.json` like follows is recommended:
Note: we recommend putting `.nuxt` in `.npmignore` or `.gitignore`.
-### Static Generated Deployment (Pre Rendered)
+### Static Generated Deployment (Pre-rendered)
Nuxt.js gives you the ability to host your web application on any static hosting.
@@ -95,11 +102,15 @@ It will create a `dist` folder with everything inside ready to be deployed on a
If you have a project with [dynamic routes](/guide/routing#dynamic-routes), take a look at the [generate configuration](/api/configuration-generate) to tell Nuxt.js how to generate these dynamic routes.
-<div class="Alert">When generating your web application with `nuxt generate`, [the context](/api/context) given to [data()](/guide/async-data#the-data-method) and [fetch()](/guide/vuex-store#the-fetch-method) will not have `req` and `res`.</div>
+<div class="Alert">
+
+When generating your web application with `nuxt generate`, [the context](/api/context) given to [asyncData](/guide/async-data) and [fetch](/guide/vuex-store#the-fetch-method) will not have `req` and `res`.
+
+</div>
### Single Page Application Deployment (SPA)
-`nuxt generate` still needs SSR engine during build/generate time while having the advantage of having all our pages pre rendered, and have a high SEO and page load score. The content is generated at *build time*. For example, we can't use it for applications where content depends on user authentication or a real time API (at least for the first load).
+`nuxt generate` still needs its SSR engine during build/generate time while having the advantage of having all our pages pre rendered, and have a high SEO and page load score. The content is generated at *build time*. For example, we can't use it for applications where content depends on user authentication or a real time API (at least for the first load).
The SPA idea is simple! When SPA mode is enabled using `mode: 'spa'` or `--spa` flag, and we run build, generation automatically starts after the build. This generation contains common meta and resource links, but not page content.
@@ -111,6 +122,8 @@ So, for an SPA deployment, you must do the following:
Another possible deployment method is to use Nuxt as a middleware in frameworks while in `spa` mode. This helps reduce server load and uses Nuxt in projects where SSR is not possible.
-<div class="Alert">See [How to deploy on Heroku?](/faq/heroku-deployment) for examples of deployment to popular hosts.</div>
+<div class="Alert">
+
+Read our [FAQ](/faq) and find nifty examples for deployments to popular hosts.
-<div class="Alert">See [How to deploy on GitHub Pages?](/faq/github-pages) for more details on how to deploy to GitHub Pages.</div>
+</div>
diff --git a/en/guide/configuration.md b/en/guide/configuration.md
index 62cb79f..4f0f4f2 100644
--- a/en/guide/configuration.md
+++ b/en/guide/configuration.md
@@ -3,35 +3,35 @@ title: Configuration
description: By default, Nuxt.js is configured to cover most use cases. This default configuration can be overwritten by using the `nuxt.config.js` file.
---
-> By default, Nuxt.js is configured to cover most use cases. This default configuration can be overwritten by modifying the `nuxt.config.js` file.
+> By default, Nuxt.js is configured to cover most use cases. This default configuration can be overwritten with the `nuxt.config.js` file.
### build
-This option lets you add modules inside the `vendor.bundle.js` file to reduce the size of the application bundle. This is especially helpful when using external modules.
+This option lets you configure various settings for the `build` step, including `loaders`, `filenames`, the `webpack` config and `transpilation`.
[Documentation about `build` integration](/api/configuration-build)
### css
-This option lets you define the CSS files/modules/libraries you want to set as globals (included in every page).
+This option lets you define the CSS files, modules, and libraries you want to include globally (on every page).
[Documentation about `css` integration](/api/configuration-css)
### dev
-This option lets you define the `development` or `production` mode of Nuxt.js
+This option lets you define the `development` or `production` mode of Nuxt.js (important when you use Nuxt.js programatically)
[Documentation about `dev` integration](/api/configuration-dev)
### env
-This option lets you define environment variables available to both the client and the server.
+This option lets you define environment variables that are available to both client and server.
[Documentation about `env` integration](/api/configuration-env)
### generate
-This option lets you define parameters values for every dynamic route in your application that will be transformed into HTML files by Nuxt.js.
+This option lets you set up parameter values for every dynamic route in your application that will be transformed into HTML files by Nuxt.js.
[Documentation about generate integration](/api/configuration-generate)
@@ -43,53 +43,59 @@ This option lets you define all default meta tags for your application.
### loading
-This option lets you customize the loading component Nuxt.js loads by default.
+This option lets you customize the loading component that Nuxt.js uses by default.
[Documentation about `loading` integration](/api/configuration-loading)
### modules
-This option lets you add Nuxt modules to your project.
+With this option you can add Nuxt.js modules to your project.
[Documentation about `modules` integration](/api/configuration-modules)
### modulesDir
This option lets you define the node_modules folder of your Nuxt.js Application.
-
+
[Documentation about `modulesDir` integration](/api/configuration-modulesdir)
### plugins
-This option lets you define JavaScript plugins to be run before instantiating the root Vue.js Application.
+This option lets you define JavaScript plugins that should be run before instantiating the root Vue.js application.
[Documentation about `plugins` integration](/api/configuration-plugins)
### rootDir
-This option lets you define the workspace of your Nuxt.js Application.
+This option lets you define the workspace of your Nuxt.js application.
[Documentation about `rootDir` integration](/api/configuration-rootdir)
-### server
+### router
-This option lets you configure the connection variables for the server instance of your Nuxt.js Application.
+With the `router` option you overwrite the default Nuxt.js configuration of Vue Router.
-[Documentation about `server` integration](/api/configuration-server)
+[Documentation about `router` integration](/api/configuration-router)
-### router
+### server
-This option lets you overwrite the default Nuxt.js configuration of Vue Router.
+This option lets you configure the connection variables for the server instance of your Nuxt.js application.
-[Documentation about `router` integration](/api/configuration-router)
+[Documentation about `server` integration](/api/configuration-server)
### srcDir
-This option lets you define the source directory of your Nuxt.js Application.
+This option lets you define the source directory of your Nuxt.js application.
[Documentation about `srcDir` integration](/api/configuration-srcdir)
+### dir
+
+This option lets you define the custom directories of your Nuxt.js application.
+
+[Documentation about `dir` integration](/api/configuration-dir)
+
### transition
This option lets you define the default properties of the page transitions.
diff --git a/en/guide/contribution-guide.md b/en/guide/contribution-guide.md
index 18d001a..ba4f803 100644
--- a/en/guide/contribution-guide.md
+++ b/en/guide/contribution-guide.md
@@ -7,15 +7,110 @@ description: Any contribution to Nuxt.js is more than welcome!
## Reporting Issues
-A great way to contribute to the project is to send a detailed report when you encounter an issue. Fot this, we use [CMTY](https://cmty.app/nuxt/issues/new).
+A great way to contribute to the project is to send a detailed report when you encounter an issue.
+To make things easier for contributors and maintainers, we use [CMTY](https://cmty.nuxtjs.org/).
+
+Please make sure to include a reproduction repository or [CodeSandBox](https://template.nuxtjs.org/)
+so that bugs can be reproduced without great efforts. The better a bug can be reproduced, the faster we can start fixing it!
## Pull Requests
We'd love to see your pull requests, even if it's just to fix a typo!
-Any significant improvement should be associated to an existing [feature request](https://cmty.app/nuxt/issues/feature-request?repo=nuxt.js) or [bug report](https://cmty.app/nuxt/issues/bug-report?repo=nuxt.js).
+However, any significant improvement should be associated to an existing
+[feature request](https://feature.nuxtjs.org/)
+or [bug report](https://bug.nuxtjs.org/).
+
+### Getting started
+
+1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device.
+2. Run `npm install` or `yarn install` to install the dependencies.
+
+> _Note that both **npm** and **yarn** have been seen to miss installing dependencies. To remedy that, you can either delete the `node_modules` folder in your example app and install again or do a local install of the missing dependencies._
+
+> If you are adding a dependency, please use `yarn add`. The `yarn.lock` file is the source of truth for all Nuxt dependencies.
+
+### Setup
+ Before running any tests, make sure all dependencies are met and build all packages:
+ ```sh
+yarn
+yarn build
+```
+
+### Test structure
+
+A great PR, whether it includes a bug fix or a new feature, will often include tests.
+To write great tests, let us explain our test structure:
+
+#### Fixtures
+
+The fixtures (found under `tests/fixtures`) contain several Nuxt applications. To keep build time as short as possible,
+we don't build an own Nuxt application per test. Instead, the fixtures are built (`yarn test:fixtures`) before running
+the actual unit tests.
+
+Please make sure to **alter** or **add a new fixture** when submitting a PR to reflect the changes properly (if applicable).
+
+Also, don't forget to **rebuild** a fixture after changing it by running the corresponding test
+with `jest test/fixtures/my-fixture/my-fixture.test.js`!
+
+#### Unit tests
+
+The unit tests can be found in `tests/unit` and will be executed after building the fixtures. A fresh Nuxt server will be used
+per test so that no shared state (except the initial state from the build step) is present.
+
+After adding your unit tests, you can run them directly:
+
+```sh
+jest test/unit/test.js
+```
+
+Or you can run the whole unit test suite:
+
+```sh
+yarn test:unit
+```
+
+Again, please be aware that you might have to rebuild your fixtures before!
+
+### Testing your changes
+
+While working on your PR you will likely want to check if your fixture is set up correctly or debug your current changes.
+
+To do so you can use the Nuxt script itself to launch for example your fixture or an example app:
+
+```sh
+yarn nuxt examples/your-app
+yarn nuxt test/fixtures/your-fixture-app
+```
+
+> `npm link` could also (and does, to some extent) work for this, but it has been known to exhibit some issues. That is why we recommend calling `yarn nuxt` directly to run examples.
+
+### Examples
+
+If you are working on a larger feature, please set up an example app in `examples/`.
+This will help greatly in understanding changes and also help Nuxt users to understand the feature you've built in-depth.
+
+### Linting
+
+As you might have noticed already, we are using ESLint to enforce a code standard. Please run `yarn lint` before committing
+your changes to verify that the code style is correct. If not, you can use `yarn lint --fix` or `npm run lint -- --fix` (no typo!) to fix most of the
+style changes. If there are still errors left, you must correct them manually.
+
+### Documentation
+
+If you are adding a new feature, do a refactoring or change the behavior of Nuxt in any other manner, you'll likely
+want to document the changes. Please do so with a PR to the [docs](https://github.com/nuxt/docs/pulls) repository.
+You don't have to write documentation up immediately (but please do so as soon as your pull request is mature enough).
+
+### Final checklist
+
+When submitting your PR, there is a simple template that you have to fill out.
+Please tick all appropriate "answers" in the checklists.
+
+### Troubleshooting
+
+#### Debugging tests on macOS
-### Convention
+Searching for `getPort()` will reveal it's used to start new Nuxt processes during tests. It's been seen to stop working on macOS at times and may require you to manually set a port for testing.
-- For a fix, the branch name should be `fix-XXX` where XXX is the issue number or the name of what your fix does
-- For a feature, the branch name should be `feat-XXX` where XXX is the issue number associated to this feature request
+Another common issue is Nuxt processes that may hang in memory when running fixture tests. A ghost process will often prevent subsequent tests from working. Run `ps aux | grep -i node` to inspect any hanging test processes if you suspect this is happening.
diff --git a/en/guide/development-tools.md b/en/guide/development-tools.md
index 2771c63..24cda80 100644
--- a/en/guide/development-tools.md
+++ b/en/guide/development-tools.md
@@ -132,7 +132,7 @@ npm install --save-dev babel-eslint eslint eslint-config-prettier eslint-loader
Then, you can configure ESLint via a `.eslintrc.js` file in your root project directory:
```js
-module.exports = {
+export default {
root: true,
env: {
browser: true,
@@ -187,7 +187,7 @@ ESLint will lint all of your JavaScript and Vue files while ignoring your ignore
It is also recommended to enable ESLint hot reloading mode via webpack. This way ESLint will run on save during `npm run dev`. Just add the following to your `nuxt.config.js`:
-```
+```js
...
/*
** Build configuration
@@ -210,4 +210,8 @@ It is also recommended to enable ESLint hot reloading mode via webpack. This way
}
```
-<p class="Alert Alert--info">One best practice is to add also `"precommit": "npm run lint"` in your package.json to lint your code automatically before commiting your code.</p>
+<div class="Alert Alert--orange">
+
+One best practice is to add also `"precommit": "npm run lint"` in your package.json to lint your code automatically before commiting your code.
+
+</div>
diff --git a/en/guide/directory-structure.md b/en/guide/directory-structure.md
index 9b9c778..f1e1128 100644
--- a/en/guide/directory-structure.md
+++ b/en/guide/directory-structure.md
@@ -9,22 +9,22 @@ description: The default Nuxt.js application structure is intended to provide a
### The Assets Directory
-The `assets` directory contains your un-compiled assets such as Less, Sass or JavaScript.
+The `assets` directory contains your un-compiled assets such as Stylus or Sass files, images, or fonts.
[More documentation about Assets integration](/guide/assets)
### The Components Directory
-The `components` directory contains your Vue.js Components. Nuxt.js doesn't supercharge the data method on these components.
+The `components` directory contains your Vue.js Components. You can't use either `asyncData` or `fetch` in these components.
### The Layouts Directory
-The `layouts` directory contains your Application Layouts.
-
-_This directory cannot be renamed._
+The `layouts` directory includes your application layouts. Layouts are used to change the look and feel of your page (for example by including a sidebar).
[More documentation about Layouts integration](/guide/views#layouts)
+_This directory cannot be renamed without extra configuration._
+
### The Middleware Directory
The `middleware` directory contains your Application Middleware. Middleware lets you define custom functions that can be run before rendering either a page or a group of pages (layouts).
@@ -35,31 +35,31 @@ The `middleware` directory contains your Application Middleware. Middleware lets
The `pages` directory contains your Application Views and Routes. The framework reads all the `.vue` files inside this directory and creates the application router.
-_This directory cannot be renamed._
+_This directory cannot be renamed without extra configuration._
[More documentation about Pages integration](/guide/views)
### The Plugins Directory
-The `plugins` directory contains your Javascript plugins that you want to run before instantiating the root Vue.js Application.
+The `plugins` directory contains your Javascript plugins that you want to run before instantiating the root Vue.js Application. This is the place to register components globally and to inject functions or constants.
[More documentation about Plugins integration](/guide/plugins)
### The Static Directory
-The `static` directory contains your static files. Each file inside this directory is mapped to `/`.
+The `static` directory is directly mapped to the server root (`/static/robots.txt` is accessible under `http://localhost:3000/robots.txt`) and contains files that likely won't be changed (i.e. the favicon)
**Example:** `/static/robots.txt` is mapped as `/robots.txt`
-_This directory cannot be renamed._
+_This directory cannot be renamed without extra configuration._
[More documentation about Static integration](/guide/assets#static)
### The Store Directory
-The `store` directory contains your [Vuex Store](http://vuex.vuejs.org/en/) files. The Vuex Store option is implemented in the Nuxt.js framework. Creating an `index.js` file in this directory enables the option in the framework automatically.
+The `store` directory contains your [Vuex Store](http://vuex.vuejs.org/en/) files. The Vuex Store comes with Nuxt.js out of the box but is disabled by default. Creating an `index.js` file in this directory enables the store.
-_This directory cannot be renamed._
+_This directory cannot be renamed without extra configuration._
[More documentation about Store integration](/guide/vuex-store)
@@ -67,7 +67,7 @@ _This directory cannot be renamed._
The `nuxt.config.js` file contains your Nuxt.js custom configuration.
-_This file can not be renamed._
+_This file can not be renamed without extra configuration._
[More documentation about `nuxt.config.js` integration](/guide/configuration)
@@ -86,4 +86,8 @@ _This file can not be renamed._
By default, `srcDir` is the same as `rootDir`.
-<p class="Alert Alert--nuxt-green"><b>Info:</b> Inside your `vue` templates, if you need to link to your `assets` or `static` directory, use `~/assets/your_image.png` and `~/static/your_image.png`.</p>
+<div class="Alert Alert--nuxt-green">
+
+<b>Info:</b> Inside your `vue` templates, if you need to link to your `assets` or `static` directory, use `~/assets/your_image.png` and `~/static/your_image.png`.
+
+</div>
diff --git a/en/guide/index.md b/en/guide/index.md
index 3cf00fe..cb281f9 100644
--- a/en/guide/index.md
+++ b/en/guide/index.md
@@ -16,7 +16,7 @@ Nuxt.js presets all the configuration needed to make your development of a Vue.j
In addition, we also provide another deployment option called: *nuxt generate*. It will build a **Static Generated** Vue.js Application.
We believe that option could be the next big step in the development of Web Applications with microservices.
-Futhermore, you can also use Nuxt.js to create single page applications (`spa` mode) quickly, useful to keep Nuxt features while working on backoffice applications.
+Furthermore, you can also use Nuxt.js to create single page applications (`spa` mode) quickly, useful to keep Nuxt features while working on backoffice applications.
As a framework, Nuxt.js comes with a lot of features to help you in your development between the client side and the server side such as Asynchronous Data, Middleware, Layouts, etc.
@@ -53,9 +53,9 @@ Under the hood we use [webpack](https://github.com/webpack/webpack) with [vue-lo
## Schema
-This schema shows what is called by Nuxt.js when the server is called or when the user navigate through the app via `<nuxt-link>`:
+This schema shows what is called by Nuxt.js when the server is called or when the user navigates through the app via `<nuxt-link>`:
-![nuxt-schema](/nuxt-schema.png)
+![nuxt-schema](/nuxt-schema.svg)
## Server Rendered (Universal SSR)
@@ -77,6 +77,17 @@ The big innovation of Nuxt.js comes with the `nuxt generate` command.
When building your application, it will generate the HTML for every one of your routes and store it in a file.
+<div>
+ <a href="https://vueschool.io/courses/static-site-generation-with-nuxtjs?friend=nuxt" target="_blank" class="Promote">
+ <img src="/static-site-generation-with-nuxtjs.png" alt="Static Site Generation with Nuxt.js by vueschool"/>
+ <div class="Promote__Content">
+ <h4 class="Promote__Content__Title">Static Site Generation with Nuxt.js</h4>
+ <p class="Promote__Content__Description">Learn how to generate static websites (pre rendering) to improve both performance and SEO while eliminating hosting costs.</p>
+ <p class="Promote__Content__Signature">Video courses made by VueSchool to support Nuxt.js developpement.</p>
+ </div>
+ </a>
+</div>
+
For example, the following file structure:
```bash
@@ -107,6 +118,10 @@ We don't want to manually generate the application every time we update the [doc
We now have an automated **Static Generated Web Application** :)
-We can go further by thinking of an e-commerce web application made with `nuxt generate` and hosted on a CDN. Everytime a product is out of stock or back in stock, we regenerate the web app. But if the user navigates through the web app in the meantime, it will be up to date thanks to the API calls made to the e-commerce API. No need to have multiple instances of a server + a cache anymore!
+We can go further by thinking of an e-commerce web application made with `nuxt generate` and hosted on a CDN. Every time a product is out of stock or back in stock, we regenerate the web app. But if the user navigates through the web app in the meantime, it will be up to date thanks to the API calls made to the e-commerce API. No need to have multiple instances of a server + a cache any more!
+
+<div class="Alert">
+
+See [How to deploy on Netlify?](/faq/netlify-deployment) for more details on how to deploy to Netlify.
-<div class="Alert">See [How to deploy on Netlify?](/faq/netlify-deployment) for more details on how to deploy to Netlify.</div>
+</div>
diff --git a/en/guide/installation.md b/en/guide/installation.md
index 54ec1e4..f355f5f 100644
--- a/en/guide/installation.md
+++ b/en/guide/installation.md
@@ -5,9 +5,20 @@ description: Nuxt.js is really easy to get started with. A simple project only n
> Nuxt.js is really easy to get started with. A simple project only needs the `nuxt` dependency.
+<div>
+ <a href="https://vueschool.io/courses/nuxtjs-fundamentals/?friend=nuxt" target="_blank" class="Promote">
+ <img src="/nuxt-fundamentals.png" alt="Nuxt Fundamentals by vueschool"/>
+ <div class="Promote__Content">
+ <h4 class="Promote__Content__Title">Nuxt.js Fundamentals</h4>
+ <p class="Promote__Content__Description">Learn how to get started quickly with Nuxt.js in videos.</p>
+ <p class="Promote__Content__Signature">Video courses made by VueSchool to support Nuxt.js developpement.</p>
+ </div>
+ </a>
+</div>
+
## Using `create-nuxt-app`
-To get started quickly, the Nuxt.js team has created scaffolding tool [create-nuxt-app](https://github.com/nuxt-community/create-nuxt-app).
+To get started quickly, the Nuxt.js team has created scaffolding tool [create-nuxt-app](https://github.com/nuxt/create-nuxt-app).
Make sure you have [npx](https://www.npmjs.com/package/npx) installed (`npx` is shipped by default since NPM `5.2.0`)
@@ -38,10 +49,16 @@ It will ask you some questions:
- [Bulma](https://github.com/jgthms/bulma)
- [Tailwind](https://github.com/tailwindcss/tailwindcss)
- [Element UI](https://github.com/ElemeFE/element)
+ - [Ant Design Vue](https://github.com/vueComponent/ant-design-vue)
- [Buefy](https://buefy.github.io)
-3. The Nuxt mode you want (`Universal` or `SPA`)
-4. Add [axios module](https://github.com/nuxt-community/axios-module) to make HTTP request easily into your application.
-5. Add [EsLint](https://eslint.org/) to Lint your code on save.
+3. Choose your favorite testing framework:
+ - None (feel free to add one later)
+ - [Jest](https://github.com/facebook/jest)
+ - [AVA](https://github.com/avajs/ava)
+4. The [Nuxt mode you want (`Universal` or `SPA`)](https://nuxtjs.org/guide/release-notes#better-spa-experience)
+5. Add [axios module](https://github.com/nuxt-community/axios-module) to make HTTP request easily into your application.
+6. Add [EsLint](https://eslint.org/) to Lint your code on save.
+7. Add [Prettier](https://prettier.io/) to prettify your code on save.
When answered, it will install all the dependencies so the next step is to launch the project with:
@@ -51,7 +68,11 @@ $ npm run dev
The application is now running on http://localhost:3000.
-<p class="Alert">Nuxt.js will listen for file changes inside the <code>pages</code> directory, so there is no need to restart the application when adding new pages.</p>
+<div class="Alert">
+
+Nuxt.js will listen for file changes inside the <code>pages</code> directory, so there is no need to restart the application when adding new pages.
+
+</div>
To discover more about the directory structure of the project: [Directory Structure Documentation](/guide/directory-structure).
@@ -64,7 +85,11 @@ $ mkdir <project-name>
$ cd <project-name>
```
-<p class="Alert Alert--nuxt-green"><b>Info:</b> replace <code>&lt;project-name&gt;</nom-du-projet></code> by the name of the project.</p>
+<div class="Alert Alert--nuxt-green">
+
+<b>Info:</b> replace <code>&lt;project-name&gt;</nom-du-projet></code> by the name of the project.
+
+</div>
### The package.json
@@ -115,6 +140,10 @@ $ npm run dev
The application is now running on http://localhost:3000.
-<p class="Alert">Nuxt.js will listen for file changes inside the <code>pages</code> directory, so there is no need to restart the application when adding new pages.</p>
+<div class="Alert">
+
+Nuxt.js will listen for file changes inside the <code>pages</code> directory, so there is no need to restart the application when adding new pages.
+
+</div>
To discover more about the directory structure of the project: [Directory Structure Documentation](/guide/directory-structure).
diff --git a/en/guide/menu.json b/en/guide/menu.json
index 97fb9f0..7d25a81 100644
--- a/en/guide/menu.json
+++ b/en/guide/menu.json
@@ -43,6 +43,7 @@
{ "to": "#dynamic-routes", "name": "Dynamic Routes" },
{ "to": "#nested-routes", "name": "Nested Routes" },
{ "to": "#dynamic-nested-routes", "name": "Dynamic Nested Routes" },
+ { "to": "#named-views", "name": "Named Views" },
{ "to": "#transitions", "name": "Transitions" },
{ "to": "#middleware", "name": "Middleware" }
]
@@ -93,10 +94,10 @@
"to": "/vuex-store", "name": "Vuex Store",
"contents": [
{ "to": "#activate-the-store", "name": "Activate the Store" },
- { "to": "#classic-mode", "name": "Classic mode" },
{ "to": "#modules-mode", "name": "Modules mode" },
{ "to": "#the-fetch-method", "name": "The fetch Method" },
- { "to": "#the-nuxtserverinit-action", "name": "The nuxtServerInit Action" }
+ { "to": "#the-nuxtserverinit-action", "name": "The nuxtServerInit Action" },
+ { "to": "#classic-mode", "name": "Classic mode" }
]
},
{
diff --git a/en/guide/modules.md b/en/guide/modules.md
index 9045874..0eeb61f 100644
--- a/en/guide/modules.md
+++ b/en/guide/modules.md
@@ -7,11 +7,22 @@ description: Modules are Nuxt.js extensions which can extend its core functional
## Introduction
-While developing production-grade applications with Nuxt, you soon discover that the framework's core functionality is not enough. Nuxt can be extended with configuration options and plugins, but maintaining these customizations across multiple projects is tedious, repetitive and time-consuming. On the other hand, supporting every project's needs out of the box would make Nuxt very complex and hard to use.
-
-This is why Nuxt provides a higher-order module system that makes it easy to extend the core. Modules are simply **functions** that are called sequentially when booting Nuxt. The framework waits for each module to finish before continuing. In this way, modules can customize almost any aspect of Nuxt. Thanks to Nuxt's modular design (based on webpack's [Tapable](https://github.com/webpack/tapable)), modules can easily register hooks for certain entry points like builder initialization. Modules can also override templates, configure webpack loaders, add CSS libraries, and perform any of a number of other useful tasks.
-
-Best of all, Nuxt modules can be incorporated into npm packages. This makes them easy to reuse across projects and to share with the Nuxt community, helping create an ecosystem of high-quality Nuxt add-ons.
+While developing production-grade applications with Nuxt, you'll soon discover that the framework's core
+functionality is not enough. Nuxt can be extended with configuration options and plugins,
+but maintaining these customizations across multiple projects is tedious, repetitive and time-consuming.
+On the other hand, supporting every project's needs out of the box would make Nuxt very complex and hard to use.
+
+This is one of the reasons why Nuxt provides a higher-order module system that makes it easy to extend the core.
+Modules are simply **functions** that are called sequentially when booting Nuxt.
+The framework waits for each module to finish before continuing.
+In this way, modules can customize almost any aspect of Nuxt.
+Thanks to Nuxt's modular design (based on webpack's [Tapable](https://github.com/webpack/tapable)),
+modules can easily register hooks for certain entry points like the builder initialization.
+Modules can also override templates, configure webpack loaders, add CSS libraries, and perform many other useful tasks.
+
+Best of all, Nuxt modules can be incorporated into npm packages.
+This makes them easy to reuse across projects and to share with the Nuxt community,
+helping create an ecosystem of high-quality Nuxt add-ons.
Modules are great if you:
@@ -29,11 +40,11 @@ As already mentioned modules are just simple functions. They can be packaged as
**modules/simple.js**
```js
-module.exports = function SimpleModule (moduleOptions) {
+export default function SimpleModule (moduleOptions) {
// Write your code here
}
-// REQUIRED if publishing as an npm package
+// REQUIRED if publishing the module as npm package
// module.exports.meta = require('./package.json')
```
@@ -43,7 +54,7 @@ This is the object passed using `modules` array by user we can use it to customi
**`this.options`**
-You can directly access to Nuxt options using this reference. This is `nuxt.config.js` with all default options assigned to and can be used for shared options between modules.
+You can directly access Nuxt options using this reference. This is the content of the user's `nuxt.config.js` with all default options assigned to. It can be used for shared options between modules.
**`this.nuxt`**
@@ -51,7 +62,7 @@ This is a reference to current Nuxt instance. Refer to [Nuxt class docs for avai
**`this`**
-Context of modules. Refer to [ModuleContainer](/api/internals-module-container) class docs for available methods.
+Context of modules. Please look into the [ModuleContainer](/api/internals-module-container) class docs for available methods.
**`module.exports.meta`**
@@ -60,18 +71,19 @@ This line is **required** if you are publishing module as an npm package. Nuxt i
**nuxt.config.js**
```js
-module.exports = {
+export default {
modules: [
// Simple usage
'~/modules/simple'
- // Passing options
+ // Passing options directly
['~/modules/simple', { token: '123' }]
]
}
```
-We then tell Nuxt to load some specific modules for a project with optional parameters as options. Please refer to [modules configuration](/api/configuration-modules) docs for more info!
+We then tell Nuxt to load some specific modules for a project with optional parameters as options.
+Please refer to [modules configuration](/api/configuration-modules) docs for more info!
## Async Modules
@@ -79,12 +91,16 @@ Not all modules will do everything synchronous. For example you may want to deve
### Use async/await
-<p class="Alert Alert--orange">Be aware that `async`/`await` is only supported in Node.js > 7.2. So if you are a module developer at least warn users about that if using them. For heavily async modules or better legacy support you can use either a bundler to transform it for older Node.js compatibility or a promise method.</p>
+<div class="Alert Alert--orange">
+
+Be aware that `async`/`await` is only supported in Node.js > 7.2. So if you are a module developer at least warn users about that if using them. For heavily async modules or better legacy support you can use either a bundler to transform it for older Node.js compatibility or a promise method.
+
+</div>
```js
-const fse = require('fs-extra')
+import fse from 'fs-extra'
-module.exports = async function asyncModule() {
+export default async function asyncModule() {
// You can do async works here using `async`/`await`
let pages = await fse.readJson('./pages.json')
}
@@ -93,9 +109,9 @@ module.exports = async function asyncModule() {
### Return a Promise
```js
-const axios = require('axios')
+import axios from 'axios'
-module.exports = function asyncModule() {
+export default function asyncModule() {
return axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => res.data.map(user => '/users/' + user.username))
.then(routes => {
@@ -104,33 +120,19 @@ module.exports = function asyncModule() {
}
```
-### Use callbacks
-
-```js
-const axios = require('axios')
-
-module.exports = function asyncModule(callback) {
- axios.get('https://jsonplaceholder.typicode.com/users')
- .then(res => res.data.map(user => '/users/' + user.username))
- .then(routes => {
- callback()
- })
-}
-```
-
-
## Common Snippets
### Top level options
-Sometimes it is more convenient if we can use top level options while registering modules in `nuxt.config.js`. This allows us to combine multiple option sources.
+Sometimes it is more convenient if we can use top level options while registering modules in `nuxt.config.js`.
+This allows us to combine multiple option sources.
**nuxt.config.js**
```js
-module.exports = {
+export default {
modules: [
- '@nuxtjs/axios'
+ ['@nuxtjs/axios', { anotherOption: true }]
],
// axios module is aware of this by using `this.options.axios`
@@ -144,15 +146,19 @@ module.exports = {
**module.js**
```js
-module.exports = function (moduleOptions) {
+export default function (moduleOptions) {
+ // `options` will contain option1, option2 and anotherOption
const options = Object.assign({}, this.options.axios, moduleOptions)
+
// ...
}
```
### Provide plugins
-It is common that modules provide one or more plugins when added. For example [bootstrap-vue](https://bootstrap-vue.js.org) module would require to register itself into Vue. For this we can use `this.addPlugin` helper.
+It is common that modules provide one or more plugins when added.
+For example [bootstrap-vue](https://bootstrap-vue.js.org) module would require to register itself into Vue.
+In such situations we can use the `this.addPlugin` helper.
**plugin.js**
@@ -166,9 +172,9 @@ Vue.use(BootstrapVue)
**module.js**
```js
-const path = require('path')
+import path from 'path'
-module.exports = function nuxtBootstrapVue (moduleOptions) {
+export default function nuxtBootstrapVue (moduleOptions) {
// Register `plugin.js` template
this.addPlugin(path.resolve(__dirname, 'plugin.js'))
}
@@ -192,9 +198,9 @@ ga('create', '<%= options.ua %>', 'auto')
**module.js**
```js
-const path = require('path')
+import path from 'path'
-module.exports = function nuxtBootstrapVue (moduleOptions) {
+export default function nuxtBootstrapVue (moduleOptions) {
// Register `plugin.js` template
this.addPlugin({
src: path.resolve(__dirname, 'plugin.js'),
@@ -211,12 +217,12 @@ module.exports = function nuxtBootstrapVue (moduleOptions) {
### Add a CSS library
-Consider doing a check if a CSS library exists to avoid duplicates and add **an option to disable** the CSS libray in the module. See the example shown below.
+If your module will provide a CSS library, make sure to perform a check if the user already included the library to avoid duplicates, and add **an option to disable** the CSS library in the module.
**module.js**
```js
-module.exports = function (moduleOptions) {
+export default function (moduleOptions) {
if (moduleOptions.fontAwesome !== false) {
// Add Font Awesome
this.options.css.push('font-awesome/css/font-awesome.css')
@@ -226,12 +232,14 @@ module.exports = function (moduleOptions) {
### Emit assets
+<!-- todo: up2date? -->
+
We can register webpack plugins to emit assets during build.
**module.js**
```js
-module.exports = function (moduleOptions) {
+export default function (moduleOptions) {
const info = 'Built by awesome module - 1.3 alpha on ' + Date.now()
this.options.build.plugins.push({
@@ -249,14 +257,14 @@ module.exports = function (moduleOptions) {
}
```
-### Register custom loaders
+### Register custom webpack loaders
We can do the same as `build.extend` in `nuxt.config.js` using `this.extendBuild`.
**module.js**
```js
-module.exports = function (moduleOptions) {
+export default function (moduleOptions) {
this.extendBuild((config, { isClient, isServer }) => {
// `.foo` Loader
config.module.rules.push({
@@ -266,7 +274,7 @@ module.exports = function (moduleOptions) {
// Customize existing loaders
// Refer to source code for Nuxt internals:
- // https://github.com/nuxt/nuxt.js/blob/dev/lib/builder/webpack/base.js
+ // https://github.com/nuxt/nuxt.js/tree/dev/packages/builder/src/webpack/base.js
const barLoader = config.module.rules.find(rule => rule.loader === 'bar-loader')
})
}
@@ -274,35 +282,83 @@ module.exports = function (moduleOptions) {
## Run Tasks on Specific hooks
-Your module may need to do things only on specific conditions not just during Nuxt initialization. We can use powerful [Tapable](https://github.com/webpack/tapable) plugin system to do tasks on specific events. Nuxt will await for us if hooks return a Promise or are defined as `async`.
+Your module may need to do things only on specific conditions and not just during Nuxt initialization.
+We can use the powerful [Hookable](https://github.com/nuxt/nuxt.js/blob/dev/packages/common/src/hookable.js) Nuxt.js system to do tasks on specific events.
+Nuxt will wait for your function if it return a Promise or is defined as `async`.
+
+Here are some basic examples:
```js
-module.exports = function () {
- // Add hook for modules
- this.nuxt.hook('module', moduleContainer => {
+export default function myModule() {
+
+ this.nuxt.hook('modules:done', moduleContainer => {
// This will be called when all modules finished loading
})
- // Add hook for renderer
- this.nuxt.hook('renderer', renderer => {
- // This will be called when renderer was created
+ this.nuxt.hook('render:before', renderer => {
+ // Called after the renderer was created
})
- // Add hook for build
- this.nuxt.hook('build', async builder => {
- // This will be called once when builder created
-
- // We can even register internal hooks here
- builder.hook('compile', ({compiler}) => {
- // This will be run just before webpack compiler starts
- })
+ this.nuxt.hook('build:compile', async ({name, compiler }) => {
+ // Called before the compiler (default: webpack) starts
})
- // Add hook for generate
- this.nuxt.hook('generate', async generator => {
- // This will be called when a Nuxt generate starts
+ this.nuxt.hook('generate:before', async generator => {
+ // This will be called before Nuxt generates your pages
})
}
```
-<p class="Alert">There are many many more hooks and possibilities for modules. Please refer to [Nuxt Internals](/api/internals) to learn more about Nuxt internal API.</p>
+## Module package commands
+
+**Experimental**
+
+Starting in `v2.4.0`, you can add custom nuxt commands through a Nuxt module's package. To do so, you must follow the `NuxtCommand` API when defining your command. A simple example hypothetically placed in `my-module/bin/command.js` looks like this:
+
+```js
+#!/usr/bin/env node
+
+const consola = require('consola')
+const { NuxtCommand } = require('@nuxt/cli')
+
+NuxtCommand.run({
+ name: 'command',
+ description: 'My Module Command',
+ usage: 'command <foobar>',
+ options: {
+ foobar: {
+ alias: 'fb',
+ type: 'string',
+ description: 'Simple test string'
+ }
+ },
+ run(cmd) {
+ consola.info(cmd.argv)
+ }
+})
+```
+
+A few things of note here. First, notice the call to `/usr/bin/env` to retrieve the Node executable. Also notice that ES module syntax can't be used for commands unless you manually incorporate [`esm`](https://github.com/standard-things/esm) into your code.
+
+Next, you'll notice how `NuxtCommand.run()` is used to specify the settings and behavior of the command. Options are defined in `options`, which get parsed via [`minimist`](https://github.com/substack/minimist).
+Once arguments are parsed, `run()` is automatically called with the `NuxtCommand` instance as first parameter.
+
+In the example above, `cmd.argv` is used to retrieve parsed command-line arguments. There are more methods and properties in `NuxtCommand` -- documentation on them will be provided as this feature is further tested and improved.
+
+To make your command recognizable by the Nuxt CLI, list it under the `bin` section of your package.json, using the `nuxt-module` convention, where `module` relates to your package's name. With this central binary, you can use `argv` to further parse more `subcommands` for your command if you desire.
+
+```js
+{
+ "bin": {
+ "nuxt-foobar": "./bin/command.js"
+ }
+}
+```
+
+Once your package is installed (via NPM or Yarn), you'll be able to execute `nuxt foobar ...` on the command-line.
+
+<div class="Alert">
+
+There are way more hooks and possibilities for modules. Please read the [Nuxt Internals](/api/internals) to find out more about the nuxt-internal API.
+
+</div>
diff --git a/en/guide/plugins.md b/en/guide/plugins.md
index fd5c7d8..9768bf6 100644
--- a/en/guide/plugins.md
+++ b/en/guide/plugins.md
@@ -3,21 +3,25 @@ title: Plugins
description: Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root Vue.js Application. This is especially helpful when using your own libraries or external modules.
---
-> Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root vue.js application. This is especially helpful when using your own libraries or external modules.
+> Nuxt.js allows you to define JavaScript plugins to be run before instantiating the root Vue.js Application. This is especially helpful when using your own libraries or external modules.
-<div class="Alert">It is important to know that in any Vue [instance lifecycle](https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram), only `beforeCreate` and `created` hooks are called **both from client-side and server-side**. All other hooks are called only from the client-side.</div>
+<div class="Alert">
+
+It is important to know that in any Vue [instance lifecycle](https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram), only `beforeCreate` and `created` hooks are called **both, from client-side and server-side**. All other hooks are called only from the client-side.
+
+</div>
## External Packages
-We may want to use external packages/modules in our application, one great example is [axios](https://github.com/mzabriskie/axios) for making HTTP request for both server and client.
+We may want to use external packages/modules in our application (one great example is [axios](https://github.com/mzabriskie/axios)) for making HTTP request for both server and client.
-We install it via npm:
+First, we should install it via npm:
```bash
npm install --save axios
```
-Then, we can use it directly in our pages:
+Then we can use it directly in our page components:
```html
<template>
@@ -36,23 +40,11 @@ export default {
</script>
```
-But there is **one problem here**. If we import axios in another page, it will be included again for the page bundle. We want to include `axios` only once in our application. To do this, we use the `build.vendor` key in our `nuxt.config.js`:
-
-```js
-module.exports = {
- build: {
- vendor: ['axios']
- }
-}
-```
-
-Then, we can import `axios` anywhere without having to worry about making the bundle bigger!
-
## Vue Plugins
-If we want to use [vue-notifications](https://github.com/se-panfilov/vue-notifications) to display notification in our application, we need to setup the plugin before launching the app.
+If we want to use Vue plugins, like [vue-notifications](https://github.com/se-panfilov/vue-notifications) to display notification in our application, we need to setup the plugin before launching the app.
-File `plugins/vue-notifications.js`:
+We create the file `plugins/vue-notifications.js`:
```js
import Vue from 'vue'
@@ -61,29 +53,16 @@ import VueNotifications from 'vue-notifications'
Vue.use(VueNotifications)
```
-Then, we add the file inside the `plugins` key of `nuxt.config.js`:
+Then we add the file path inside the `plugins` key of our `nuxt.config.js`:
```js
-module.exports = {
+export default {
plugins: ['~/plugins/vue-notifications']
}
```
To learn more about the `plugins` configuration key, check out the [plugins api](/api/configuration-plugins).
-Actually, `vue-notifications` will be included in the app bundle, but because it's a library, we want to include it in the vendor bundle for better caching.
-
-We can update our `nuxt.config.js` to add `vue-notifications` in the vendor bundle:
-
-```js
-module.exports = {
- build: {
- vendor: ['vue-notifications']
- },
- plugins: ['~/plugins/vue-notifications']
-}
-```
-
## Inject in $root & context
Sometimes you want to make functions or values available across the app.
@@ -92,7 +71,7 @@ It is a convention to prefix those functions with a `$`.
### Inject into Vue instances
-Injecting content into Vue instances works similar to when doing this in standard Vue apps.
+Injecting context into Vue instances works similar to when doing this in standard Vue apps.
`plugins/vue-inject.js`:
@@ -105,7 +84,7 @@ Vue.prototype.$myInjectedFunction = (string) => console.log("This is an example"
`nuxt.config.js`:
```js
-module.exports = {
+export default {
plugins: ['~/plugins/vue-inject.js']
}
```
@@ -125,7 +104,7 @@ export default {
### Inject into context
-Injecting content into Vue instances works similar to when doing this in standard Vue apps.
+Injecting context into Vue instances works similar to when doing this in standard Vue apps.
`plugins/ctx-inject.js`:
@@ -139,7 +118,7 @@ export default ({ app }, inject) => {
`nuxt.config.js`:
```js
-module.exports = {
+export default {
plugins: ['~/plugins/ctx-inject.js']
}
```
@@ -173,7 +152,7 @@ export default ({ app }, inject) => {
`nuxt.config.js`:
```js
-module.exports = {
+export default {
plugins: ['~/plugins/combined-inject.js']
}
```
@@ -185,7 +164,7 @@ Now the function can be used from `context`, via `this` in Vue instances and via
```js
export default {
mounted(){
- this.$myInjectedFunction('works in mounted')
+ this.$myInjectedFunction('works in mounted')
},
asyncData(context){
context.app.$myInjectedFunction('works with context')
@@ -221,14 +200,15 @@ export const actions = {
## Client-side only
-Some plugins might work **only for the browser**, you can use the `ssr: false` option in `plugins` to run the file only on the client-side.
+Some plugins might work **only in the browser** because they lack SSR support.
+In these situations you can use the `ssr: false` option in `plugins` to add the plugin only on the client-side.
Example:
`nuxt.config.js`:
```js
-module.exports = {
+export default {
plugins: [
{ src: '~/plugins/vue-notifications', ssr: false }
]
@@ -244,6 +224,8 @@ import VueNotifications from 'vue-notifications'
Vue.use(VueNotifications)
```
-In case you need to require some libraries only for the server, you can use the `process.server` variable set to `true` when webpack is creating the `server.bundle.js` file.
+In case you need to import some libraries in a plugin only on *server-side*, you can check if the `process.server` variable is set to `true`.
+
+Also, if you need to know if you are inside a generated app (via `nuxt generate`), you can check if `process.static` is set to `true`. This is only the case during and after the generation.
-Also, if you need to know if you are inside a generated app (via `nuxt generate`), you can check `process.static`, set to `true` during generation and after. To know the state when a page is being server-rendered by `nuxt generate` before being saved, you can use `process.static && process.server`.
+You can also combine both options to hit the spot when a page is being server-rendered by `nuxt generate` before being saved (`process.static && process.server`).
diff --git a/en/guide/routing.md b/en/guide/routing.md
index ffed26c..6d3c134 100644
--- a/en/guide/routing.md
+++ b/en/guide/routing.md
@@ -5,7 +5,11 @@ description: Nuxt.js use the file-system to generate the routes of your web appl
> Nuxt.js automatically generates the [vue-router](https://github.com/vuejs/vue-router) configuration based on your file tree of Vue files inside the `pages` directory.
-<div class="Alert Alert--grey">To navigate between pages, we recommend to use the [`<nuxt-link>`](/api/components-nuxt-link) component.</div>
+<div class="Alert Alert--grey">
+
+To navigate between pages, we recommend to use the [`<nuxt-link>`](/api/components-nuxt-link) component.
+
+</div>
For example:
@@ -53,7 +57,7 @@ router: {
## Dynamic Routes
-To define a dynamic route with a param, you need to define a .vue file OR a directory **prefixed by an underscore**.
+To define a dynamic route with a parameter, you need to define a .vue file OR a directory **prefixed by an underscore**.
This file tree:
@@ -96,9 +100,13 @@ router: {
}
```
-As you can see the route named `users-id` has the path `:id?` which makes it optional, if you want to make it required, create an `index.vue` file in the `users/_id` directory.
+As you can see the route named `users-id` has the path `:id?` which makes it optional, if you want to make it required, create an `index.vue` file in the `users/_id` directory instead.
+
+<div class="Alert Alert--orange">
-<p class="Alert Alert--info"><b>Warning:</b> dynamic routes are ignored by the `generate` command: [API Configuration generate](/api/configuration-generate#routes)</p>
+**Warning:** dynamic routes are ignored by the `generate` command: [API Configuration generate](/api/configuration-generate#routes)
+
+</div>
### Validate Route Params
@@ -115,7 +123,7 @@ export default {
}
```
-If the validate method does not return `true` or a `Promise` that resolve to `true` or throws an Error, Nuxt.js will automatically load the 404 error page or 500 error page in case of an error.
+If the validate method does not return `true` or a `Promise` that resolve to `true`, or throws an Error, Nuxt.js will automatically load the 404 error page or 500 error page in case of an error.
More information about the validate method: [API Pages validate](/api/pages-validate)
@@ -125,7 +133,11 @@ Nuxt.js lets you create nested route by using the children routes of vue-router.
To define the parent component of a nested route, you need to create a Vue file with the **same name as the directory** which contain your children views.
-<p class="Alert Alert--info"><b>Warning:</b> don't forget to write `<nuxt-child/>` inside the parent component (<code>.vue</code> file).</p>
+<div class="Alert Alert--orange">
+
+<b>Warning:</b> don't forget to include `<nuxt-child/>` inside the parent component (<code>.vue</code> file).
+
+</div>
This file tree:
@@ -221,6 +233,62 @@ router: {
}
```
+### Unknown Dynamic Nested Routes
+
+If you do not know the depth of your URL structure, you can use `_.vue` to dynamically match nested paths.
+This will handle requests that do not match a _more specific_ request.
+
+This file tree:
+
+```bash
+pages/
+--| people/
+-----| _id.vue
+-----| index.vue
+--| _.vue
+--| index.vue
+```
+
+Will handle requests like this:
+
+Path | File
+--- | ---
+`/` | `index.vue`
+`/people` | `people/index.vue`
+`/people/123` | `people/_id.vue`
+`/about` | `_.vue`
+`/about/careers` | `_.vue`
+`/about/careers/chicago` | `_.vue`
+
+__Note:__ Handling 404 pages is now up to the logic of the `_.vue` page. [More on 404 redirecting can be found here](/guide/async-data#handling-errors).
+
+### Named Views
+
+To render named views you can use `<nuxt name="top"/>` or `<nuxt-child name="top"/>` components in your layout/page. To specify named view of page we need to extend router config in `nuxt.config.js` file:
+
+``` js
+export default {
+ router: {
+ extendRoutes(routes, resolve) {
+ let index = routes.findIndex(route => route.name === 'main')
+ routes[index] = {
+ ...routes[index],
+ components: {
+ default: routes[index].component,
+ top: resolve(__dirname, 'components/mainTop.vue')
+ },
+ chunkNames: {
+ top: 'components/mainTop'
+ }
+ }
+ }
+ }
+}
+```
+It require to extend interested route with 2 properties `components` and `chunkNames`. Named view in this config example has name `top`.
+
+To see an example, take a look at the [named-views example](/examples/named-views).
+
### SPA fallback
You can enable SPA fallbacks for dynamic routes too. Nuxt.js will output an extra file that is the same as the `index.html` that would be used in `mode: 'spa'`. Most static hosting services can be configured to use the SPA template if no file matches. It won't include the `head` info or any HTML, but it will still resolve and load the data from the API.
@@ -228,9 +296,9 @@ You can enable SPA fallbacks for dynamic routes too. Nuxt.js will output an extr
We enable this in our `nuxt.config.js` file:
``` js
-module.exports = {
+export default {
generate: {
- fallback: true, // if you want to use '404.html'
+ fallback: true, // if you want to use '404.html' instead of the default '200.html'
fallback: 'my-fallback/file.html' // if your hosting needs a custom location
}
}
@@ -246,7 +314,7 @@ GitHub Pages and Netlify recognize the `404.html` file automatically, so setting
#### Implementation for Firebase Hosting
-To use on Firebase Hosting, configure `generate.fallback` to `true` and use the following config ([more info](https://firebase.google.com/docs/hosting/url-redirects-rewrites#section-rewrites)):
+To use the fallback on Firebase Hosting, configure `generate.fallback` to `true` and use the following config ([more info](https://firebase.google.com/docs/hosting/url-redirects-rewrites#section-rewrites)):
``` json
{
@@ -273,7 +341,11 @@ Nuxt.js uses the [`<transition>`](http://vuejs.org/v2/guide/transitions.html#Tra
### Global Settings
-<p class="Alert Alert--nuxt-green"><b>Info :</b> Nuxt.js default transition name is `"page"`.</p>
+<div class="Alert Alert--nuxt-green">
+
+<b>Info:</b> Nuxt.js default transition name is `"page"`.
+
+</div>
To add a fade transition to every page of your application, we need a CSS file that is shared across all our routes, so we start by creating a file in the `assets` folder.
@@ -288,12 +360,12 @@ Our global css in `assets/main.css`:
}
```
-We add its path in our `nuxt.config.js` file:
+Then we add its path to the `css` array in our `nuxt.config.js` file:
```js
-module.exports = {
+export default {
css: [
- 'assets/main.css'
+ '~/assets/main.css'
]
}
```
@@ -302,7 +374,7 @@ More information about the transition key: [API Configuration transition](/api/p
### Page Settings
-You can also define a custom transition for only one page with the `transition` property.
+You can also define a custom transition for a specific page with the `transition` property.
We add a new class in our global css in `assets/main.css`:
@@ -315,7 +387,7 @@ We add a new class in our global css in `assets/main.css`:
}
```
-then, we use the transition property to define the class name to use for this page transition:
+Then we use the transition property to define the class name to use for this page transition:
```js
export default {
@@ -335,13 +407,14 @@ A middleware receives [the context](/api/context) as first argument:
```js
export default function (context) {
- context.userAgent = context.isServer ? context.req.headers['user-agent'] : navigator.userAgent
+ context.userAgent = process.server ? context.req.headers['user-agent'] : navigator.userAgent
}
```
+In universal mode, middlewares will be called server-side once (on the first request to the Nuxt app or when page refreshes) and client-side when navigating to further routes. In SPA mode, middlewares will be called client-side on the first request and when navigating to further routes.
The middleware will be executed in series in this order:
-1. `nuxt.config.js`
+1. `nuxt.config.js` (in the order within the file)
2. Matched layouts
3. Matched pages
@@ -359,18 +432,29 @@ export default function ({ route }) {
}
```
-Then, in your `nuxt.config.js`, layout or page, use the `middleware` key:
+Then, in your `nuxt.config.js`, use the `router.middleware` key:
`nuxt.config.js`
```js
-module.exports = {
+export default {
router: {
middleware: 'stats'
}
}
```
-The `stats` middleware will be called for every route changes.
+Now the `stats` middleware will be called for every route change.
+
+You can add your middleware to a specific layout or page as well:
+
+
+`pages/index.vue` or `layouts/default.vue`
+
+```js
+export default {
+ middleware: 'stats'
+}
+```
To see a real-life example using the middleware, please see [example-auth0](https://github.com/nuxt/example-auth0) on GitHub.
diff --git a/en/guide/views.md b/en/guide/views.md
index ec20ae8..e98ce62 100644
--- a/en/guide/views.md
+++ b/en/guide/views.md
@@ -3,17 +3,17 @@ title: Views
description: The Views section describes all you need to configure data and views for a specific route in your Nuxt.js Application (Document, Layouts, Pages and HTML Head).
---
-> The Views section describes all you need to configure data and views for a specific route in your Nuxt.js Application (Document, Layouts, Pages and HTML Head).
+> The Views section describes all you need to configure data and views for a specific route in your Nuxt.js Application (App Template, Layouts, Pages and HTML Head).
-![nuxt-views-schema](/nuxt-views-schema.png)
+![nuxt-views-schema](/nuxt-views-schema.svg)
-## Document
+## App Template
-> You can customise the main document with Nuxt.js.
+> You can customize the HTML app template used by Nuxt.js to include scripts or conditional CSS classes.
-To extend the HTML template, create `app.html` at the root of your project.
+To change the template, create an `app.html` file in the root folder of your project.
-The default template is:
+The default template used by Nuxt.js is:
```html
<!DOCTYPE html>
@@ -27,7 +27,7 @@ The default template is:
</html>
```
-One example is to add conditional CSS classes for IE:
+One use case of using a custom app template is to add conditional CSS classes for IE:
```html
<!DOCTYPE html>
@@ -42,17 +42,25 @@ One example is to add conditional CSS classes for IE:
</html>
```
+<!-- TODO: Load polyfills here? -->
+
## Layouts
-Nuxt.js lets you extend the main layout or create custom layouts by adding them in the `layouts` directory.
+Layouts are a great help when you want to change the look and feel of your Nuxt.js app.
+Whether you want to include a sidebar or having distinct layouts for mobile and desktop
### Default Layout
You can extend the main layout by adding a `layouts/default.vue` file.
+It will be used for all pages that don't have a layout specified.
+
+<div class="Alert Alert--nuxt-green">
-*Make sure to add the `<nuxt/>` component when creating a layout to display the page component.*
+<b>Info:</b> Make sure to add the `<nuxt/>` component when creating a layout to actually include the page component.
-The default layout source code is:
+</div>
+
+The default layout that comes out of the box is just three lines long and simply renders the page component:
```html
<template>
@@ -60,67 +68,80 @@ The default layout source code is:
</template>
```
-### Error Page
-
-You can customize the error page by adding a `layouts/error.vue` file.
-
-This layout is special, since you should _not_ include `<nuxt/>` inside its template. You must see this layout as a component displayed when an error occurs (`404`, `500`, etc.).
+### Custom Layout
-The default error page source code is [available on GitHub](https://github.com/nuxt/nuxt.js/blob/master/lib/app/components/nuxt-error.vue).
+Every file (*top-level*) in the `layouts` directory will create a custom layout accessible with the `layout` property in the page components.
-Example of a custom error page in `layouts/error.vue`:
+Let's say we want to create a blog layout and save it to `layouts/blog.vue`:
```html
<template>
- <div class="container">
- <h1 v-if="error.statusCode === 404">Page not found</h1>
- <h1 v-else>An error occurred</h1>
- <nuxt-link to="/">Home page</nuxt-link>
+ <div>
+ <div>My blog navigation bar here</div>
+ <nuxt/>
</div>
</template>
+```
+
+Then we have to tell the pages (i.e. `pages/posts.vue`) to use your custom layout:
+```html
+<template>
+<!-- Your template -->
+</template>
<script>
export default {
- props: ['error'],
- layout: 'blog' // you can set a custom layout for the error page
+ layout: 'blog'
+ // page component definitions
}
</script>
```
-### Custom Layout
+More information about the `layout` property: [API Pages `layout`](/api/pages-layout)
+
+Check out the [demonstration video](https://www.youtube.com/watch?v=YOKnSTp7d38) to see custom layouts in action.
+
+<!-- TODO: Scoped styles best practice -->
+
+### Error Page
+
+The error page is a *page component* which is always displayed when an error occurs (that does not happen while server-side rendering).
+
+<div class="Alert Alert--orange">
+
+<b>Warning:</b> Though this file is placed in the <code>layouts</code> folder, it should be treated as a <b>page</b>.
-Every file (*first level*) in the `layouts` directory will create a custom layout accessible with the `layout` property in the page component.
+</div>
-*Make sure to add the `<nuxt/>` component when creating a layout to display the page component.*
+As mentioned above, this layout is special, since you **should not** include `<nuxt/>` inside its template.
+You must see this layout as a component displayed when an error occurs (`404`, `500`, etc.).
+Similar to other page components, you can set a custom layout for the error page as well in the usual way.
-Example of `layouts/blog.vue`:
+The default error page source code is [available on GitHub](https://github.com/nuxt/nuxt.js/blob/dev/packages/vue-app/template/components/nuxt-error.vue).
+
+You can customize the error page by adding a `layouts/error.vue` file:
```html
<template>
- <div>
- <div>My blog navigation bar here</div>
- <nuxt/>
+ <div class="container">
+ <h1 v-if="error.statusCode === 404">Page not found</h1>
+ <h1 v-else>An error occurred</h1>
+ <nuxt-link to="/">Home page</nuxt-link>
</div>
</template>
-```
-
-And then in `pages/posts.vue`, you can tell Nuxt.js to use your custom layout:
-```html
<script>
export default {
- layout: 'blog'
+ props: ['error'],
+ layout: 'blog' // you can set a custom layout for the error page
}
</script>
```
-More information about the `layout` property: [API Pages `layout`](/api/pages-layout)
-
-Check the [demonstration video](https://www.youtube.com/watch?v=YOKnSTp7d38) to see it in action.
## Pages
-Every Page component is a Vue component, but Nuxt.js adds special keys to make the development of your universal application as easy as possible.
+Every Page component is a Vue component but Nuxt.js adds special attributes and functions to make the development of your universal application as easy as possible.
```html
<template>
@@ -131,6 +152,8 @@ Every Page component is a Vue component, but Nuxt.js adds special keys to make t
export default {
asyncData (context) {
// called every time before loading the component
+ // as the name said, it can be async
+ // Also, the returned object will be merged with your data object
return { name: 'World' }
},
fetch () {
@@ -151,34 +174,32 @@ export default {
</style>
```
-| Attribute | Description |
-|-----------|-------------|
-| `asyncData` | The most important key. It can be asynchronous and receives the context as argument. Please read the [async data documentation](/guide/async-data) to learn how it works. |
-| `fetch` | Used to fill the store before rendering the page. It's like the `data` method, except it doesn't set the component data. See the [API Pages `fetch` documentation](/api/pages-fetch). |
-| `head` | Set specific `<meta>` tags for the current page. See [API Pages `head` documentation](/api/pages-head). |
-| `layout` | Specify a layout defined in the `layouts` directory. See [API Pages `layout` documentation](/api/pages-layout). |
-| `loading` | If set to `false`, prevents a page from automatically calling `this.$nuxt.$loading.finish()` as you enter it and `this.$nuxt.$loading.start()` as you leave it, allowing you to **manually** control the behavior, see [example](https://nuxtjs.org/examples/custom-page-loading). Only applies if `loading` is also set in `nuxt.config.js`. See [API Configuration `loading` documentation](/api/configuration-loading).
-| `transition` | Set a specific transition for the page. See [API Pages `transition`](/api/pages-transition). |
-| `scrollToTop` | Boolean (default: `false`). Specify if you want the page to scroll to the top before rendering the page. It's used for [nested routes](/guide/routing#nested-routes). |
-| `validate` | Validator function for [dynamic routes](/guide/routing#dynamic-routes). |
-| `middleware` | Set middleware for this page. The middleware will be called before rendering the page. See routes [middleware](/guide/routing#middleware). |
+| Attribute | Description | Documentation |
+|-----------|-------------| ------------- |
+| `asyncData` | The most important key. It can be asynchronous and receives the context as argument. | [Guide: Async data](/guide/async-data) |
+| `fetch` | Used to fill the store before rendering the page. It's like the `asyncData` method, except it doesn't set the component data. | [API Pages `fetch`](/api/pages-fetch) |
+| `head` | Set specific `<meta>` tags for the current page. | [API Pages `head`](/api/pages-head) |
+| `layout` | Specify a layout defined in the `layouts` directory. | [API Pages `layout`](/api/pages-layout) |
+| `loading` | If set to `false`, prevents a page from automatically calling `this.$nuxt.$loading.finish()` as you enter it and `this.$nuxt.$loading.start()` as you leave it, allowing you to **manually** control the behavior, as [this example](/examples/custom-page-loading) shows. Only applies if `loading` is also set in `nuxt.config.js`. | [API Configuration `loading`](/api/configuration-loading) |
+| `transition` | Defines a specific transition for the page. | [API Pages `transition`](/api/pages-transition) |
+| `scrollToTop` | Boolean (default: `false`). Specify if you want the page to scroll to the top before rendering the page. It's used for [nested routes](/guide/routing#nested-routes). | [API Pages `scrollToTop`](/api/pages-scrolltotop#the-scrolltotop-property) |
+| `validate` | Validator function for [dynamic routes](/guide/routing#dynamic-routes). | [API Pages `validate`](/api/pages-validate#the-validate-method) |
+| `middleware` | Defines middleware for this page. The middleware will be called before rendering the page. | [Guide: middleware](/guide/routing#middleware) |
More information about the pages properties usage: [API Pages](/api)
## HTML Head
-Nuxt.js uses [vue-meta](https://github.com/declandewet/vue-meta) to update the `headers` and `html attributes` of your application.
+Nuxt.js uses [vue-meta](https://github.com/declandewet/vue-meta) to update the `document head` and `meta attributes` of your application.
-Nuxt.js configures `vue-meta` with these options:
+The `vue-meta` Nuxt.js uses can be found [on GitHub](https://github.com/nuxt/nuxt.js/blob/dev/packages/vue-app/template/index.js#L29-L35)
+
+<div class="Alert Alert--teal">
+
+<b>Info:</b> Nuxt.js uses <code>hid</code> instead of the default <code>vmid</code> key to identify meta elements
+
+</div>
-```js
-{
- keyName: 'head', // the component option name that vue-meta looks for meta info on.
- attribute: 'data-n-head', // the attribute name vue-meta adds to the tags it observes
- ssrAttribute: 'data-n-head-ssr', // the attribute name that lets vue-meta know that meta info has already been server-rendered
- tagIDKeyName: 'hid' // the property name that vue-meta uses to determine whether to overwrite or append a tag
-}
-```
### Default Meta Tags
@@ -200,10 +221,8 @@ head: {
To learn more about the options available for `head`, take a look at [vue-meta documentation](https://github.com/declandewet/vue-meta#recognized-metainfo-properties).
-More information about the `head` method: [API Configuration `head`](/api/configuration-head).
+More information about the `head` method are available on the [API Configuration `head`](/api/configuration-head) page.
### Custom Meta Tags for a Page
-More information about the head method: [API Pages `head`](/api/pages-head).
-
-<p class="Alert">To avoid any duplication when used in child component, please give a unique identifier with the `hid` key. [Learn more](https://github.com/declandewet/vue-meta#lists-of-tags).</p>
+More information about the head method can be found on the [API Pages `head`](/api/pages-head) page.
diff --git a/en/guide/vuex-store.md b/en/guide/vuex-store.md
index 93658f8..b0d7d74 100644
--- a/en/guide/vuex-store.md
+++ b/en/guide/vuex-store.md
@@ -1,61 +1,29 @@
---
title: Vuex Store
-description: Using a store to manage the state is important for every big application, that's why Nuxt.js implements Vuex in its core.
+description: Using a store to manage the state is important for every big application. That's why Nuxt.js implements Vuex in its core.
---
-> Using a store to manage the state is important to every big application, that's why Nuxt.js implements [Vuex](https://vuex.vuejs.org/en/) in its core.
+> Using a store to manage the state is important for every big application. That's why Nuxt.js implements [Vuex](https://vuex.vuejs.org/en/) in its core.
## Activate the Store
Nuxt.js will look for the `store` directory, if it exists, it will:
1. Import Vuex,
-2. Add `vuex` module in the vendors bundle,
-3. Add the `store` option to the root Vue instance.
+2. Add the `store` option to the root Vue instance.
-Nuxt.js lets you have **2 modes of store**, choose the one you prefer:
+Nuxt.js lets you decide between **2 store modes**. You can choose the one you prefer:
-- **Classic:** `store/index.js` returns a store instance.
- **Modules:** every `.js` file inside the `store` directory is transformed as a [namespaced module](http://vuex.vuejs.org/en/modules.html) (`index` being the root module).
+- **Classic (__deprecated__):** `store/index.js` returns a method to create a store instance.
-## Classic mode
-
-To activate the store with the classic mode, we create the `store/index.js` file which should export a method which returns a Vuex instance:
-
-```js
-import Vuex from 'vuex'
-
-const createStore = () => {
- return new Vuex.Store({
- state: {
- counter: 0
- },
- mutations: {
- increment (state) {
- state.counter++
- }
- }
- })
-}
-
-export default createStore
-```
-
-> We don't need to install `vuex` since it's shipped with Nuxt.js.
-
-We can now use `this.$store` inside our components:
-
-```html
-<template>
- <button @click="$store.commit('increment')">{{ $store.state.counter }}</button>
-</template>
-```
+Regardless of the mode, your `state` value should **always be a `function`** to avoid unwanted *shared* state on the server side.
## Modules mode
> Nuxt.js lets you have a `store` directory with every file corresponding to a module.
-If you want this option, export the state as a function, and the mutations and actions as objects in `store/index.js` instead of a store instance:
+To get started, simply export the state as a function, and the mutations and actions as objects in `store/index.js`:
```js
export const state = () => ({
@@ -92,11 +60,13 @@ export const mutations = {
}
```
-The store will be as such:
+The store will be created as such:
```js
new Vuex.Store({
- state: { counter: 0 },
+ state: () => ({
+ counter: 0
+ }),
mutations: {
increment (state) {
state.counter++
@@ -104,9 +74,10 @@ new Vuex.Store({
},
modules: {
todos: {
- state: {
+ namespaced: true,
+ state: () => ({
list: []
- },
+ }),
mutations: {
add (state, { text }) {
state.list.push({
@@ -144,7 +115,9 @@ import { mapMutations } from 'vuex'
export default {
computed: {
- todos () { return this.$store.state.todos.list }
+ todos () {
+ return this.$store.state.todos.list
+ }
},
methods: {
addTodo (e) {
@@ -167,12 +140,12 @@ export default {
> The module method also works for top-level definitions without implementing a sub-directory in the `store` directory
-Example for state; you create a file `store/state.js` and add the following
+Example for state: you create a file `store/state.js` and add the following
```js
-export default {
+export default () => ({
counter: 0
-}
+})
```
And the corresponding mutations can be in the file `store/mutations.js`
@@ -185,15 +158,15 @@ export default {
}
```
-<div class="Alert">You can also have modules by exporting a store instance, you will have to add them manually on your store.</div>
-
### Module files
You can optionally break down a module file into separate files: `state.js`, `actions.js`, `mutations.js` and `getters.js`. If you maintain an `index.js` file with state, getters and mutations while having a single separate file for actions, that will also still be properly recognized.
+> Note: Whilst using split-file modules, you must remember that using arrow functions, ```this``` is only lexically available. Lexical scoping simply means that the ```this``` always references the owner of the arrow function. If the arrow function is not contained then ```this``` would be undefined. The solution is to use a "normal" function which produces its own scope and thus has ```this``` available.
+
### Plugins
-You can add additional plugin to the store (in Modules Mode) putting it into the `store/index.js` file:
+You can add additional plugins to the store (in the modules mode) by putting them into the `store/index.js` file:
```js
import myPlugin from 'myPlugin'
@@ -215,7 +188,7 @@ More information about the plugins: [Vuex documentation](https://vuex.vuejs.org/
## The fetch Method
-> The `fetch` method is used to fill the store before rendering the page, it's like the `data` method except it doesn't set the component data.
+> The `fetch` method is used to fill the store before rendering the page, it's like the `asyncData` method except it doesn't set the component data.
More information about the fetch method: [API Pages fetch](/api/pages-fetch).
@@ -239,7 +212,7 @@ actions: {
The [context](/api/context) is given to `nuxtServerInit` as the 2nd argument, it is the same as `asyncData` or `fetch` method.
-> Note: Asynchronous `nuxtServerInit` actions must return a Promise to allow the `nuxt` server to wait on them.
+> Note: Asynchronous `nuxtServerInit` actions must return a Promise or leverage async/await to allow the `nuxt` server to wait on them.
```js
actions: {
@@ -251,23 +224,24 @@ actions: {
## Vuex Strict Mode
-Strict mode is enabled by default on dev mode and turned off in production mode. To disable strict mode in dev, follow the below example.
-
-### Module Mode
+Strict mode is enabled by default on dev mode and turned off in production mode. To disable strict mode in dev, follow the below example in `store/index.js`:
`export const strict = false`
-### Classic Mode
+## Classic mode
-```
+> This feature is deprecated and will be removed in Nuxt 3.
+
+To activate the store with the classic mode, we create the `store/index.js` file which should export a method that returns a Vuex instance:
+
+```js
import Vuex from 'vuex'
const createStore = () => {
return new Vuex.Store({
- strict: false,
- state: {
+ state: () => ({
counter: 0
- },
+ }),
mutations: {
increment (state) {
state.counter++
@@ -278,3 +252,13 @@ const createStore = () => {
export default createStore
```
+
+> We don't need to install `vuex` since it's shipped with Nuxt.js.
+
+We can now use `this.$store` inside our components:
+
+```html
+<template>
+ <button @click="$store.commit('increment')">{{ $store.state.counter }}</button>
+</template>
+```
diff --git a/en/lang.json b/en/lang.json
index 32025f1..20ca6a1 100644
--- a/en/lang.json
+++ b/en/lang.json
@@ -1,6 +1,6 @@
{
"iso": "en",
- "docVersion": "2.0.0",
+ "docVersion": "2.3.X",
"links": {
"api": "API",
"blog": "Blog",
@@ -16,6 +16,8 @@
"homepage": "Home page",
"live_demo": "Live Demo",
"live_edit": "Live Edit",
+ "tidelift_short": "GET PROFESSIONAL SUPPORT",
+ "tidelift": "GET PROFESSIONAL SUPPORT FOR NUXT",
"twitter": "Twitter",
"vuejs": "Vue.js",
"vue_jobs": "Vue Jobs"
@@ -35,7 +37,15 @@
"meta": {
"title": "Nuxt.js - Universal Vue.js Applications",
"description": "Nuxt.js is a minimal framework for creating Vue.js applications with server side rendering, code-splitting, hot-reloading, static generation and more!"
- }
+ },
+ "codesandbox_title": "Play with Nuxt.js online",
+ "codesandbox_open": "Open on CodeSandBox.io",
+ "codesandbox_examples": "See more examples"
+ },
+ "sponsors": {
+ "title": "Sponsors",
+ "become": "Support us and",
+ "become_partner": "become a partner"
},
"footer": {
"authors": "Made by Chopin Brothers"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment