### Example Usage of nuxt.renderAndGetWindow
Source: https://v2.nuxt.com/docs/internals-glossary/nuxt-render-and-get-window
This example demonstrates how to load a Nuxt application, listen on a port, render a specific URL to get the window object, and then close the Nuxt instance. It's useful for testing the rendered output of your Nuxt application.
```javascript
const { loadNuxt } = require('nuxt')
async function init() {
// Assuming you've already built your project
const nuxt = await loadNuxt({ for: 'start' })
await nuxt.listen(3000)
const window = await nuxt.renderAndGetWindow('http://localhost:3000')
// Display the head `
`
console.log(window.document.title)
nuxt.close()
}
init()
```
--------------------------------
### Complex Store Folder Structure Example
Source: https://v2.nuxt.com/docs/directory-structure/store
An example file and folder structure for a complex Nuxt 2 Vuex store setup, demonstrating nested modules and file-based configurations.
```treeview
store/
--| index.js
--| ui.js
--| shop/
----| cart/
------| actions.js
------| getters.js
------| mutations.js
------| state.js
----
----| products/
------| mutations.js
------| state.js
------| itemsGroup1/
--------| state.js
```
--------------------------------
### Redirect to router.base Hook Setup
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-hooks
This example shows how to configure `router.base` and set up a custom hook to handle redirection when the application is not served from the root path during local development.
```javascript
import hooks from './hooks'
export default {
router: {
base: '/portal'
}
hooks: hooks(this)
}
```
--------------------------------
### Install v-tooltip
Source: https://v2.nuxt.com/docs/directory-structure/plugins
Install the v-tooltip library for adding tooltips to your application. Use either Yarn or NPM for installation.
```bash
yarn add v-tooltip
```
```bash
npm install v-tooltip
```
--------------------------------
### Ant Design Vue Plugin Setup
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-plugins
Example of setting up the Ant Design Vue plugin, including CSS import.
```javascript
import Vue from 'vue'
import Antd from 'ant-design-vue'
import 'ant-design-vue/dist/antd.css' // Per Ant Design's docs
Vue.use(Antd)
```
--------------------------------
### Install prism-themes with NPM
Source: https://v2.nuxt.com/docs/directory-structure/content
Install the prism-themes package using NPM for syntax highlighting.
```bash
npm install prism-themes
```
--------------------------------
### Start Production Server (NPM)
Source: https://v2.nuxt.com/docs/get-started/commands
Starts the production server after the application has been built. Suitable for Node.js hosting environments.
```bash
npm run start
```
--------------------------------
### Generate and Start Nuxt 2 Static Site
Source: https://v2.nuxt.com/docs/features/live-preview
Commands to generate the static site and start the local server for testing the live preview feature.
```bash
yarn generate
yarn start
```
```bash
npx nuxt generate
npx nuxt start
```
--------------------------------
### Install prism-themes with Yarn
Source: https://v2.nuxt.com/docs/directory-structure/content
Install the prism-themes package using Yarn for syntax highlighting.
```bash
yarn add prism-themes
```
--------------------------------
### Start Production Server (Yarn)
Source: https://v2.nuxt.com/docs/get-started/commands
Starts the production server after the application has been built. Suitable for Node.js hosting environments.
```bash
yarn start
```
--------------------------------
### Install jsdom for nuxt.renderAndGetWindow
Source: https://v2.nuxt.com/docs/internals-glossary/nuxt-render-and-get-window
Before using `nuxt.renderAndGetWindow`, you need to install the `jsdom` package as a development dependency.
```bash
npm install --save-dev jsdom
```
--------------------------------
### Configure Modern Build and Start Scripts
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-modern
Add these scripts to your `package.json` to easily build and start your Nuxt application with modern bundles enabled.
```json
{
"scripts": {
"build:modern": "nuxt build --modern=server",
"start:modern": "nuxt start --modern=server"
}
}
```
--------------------------------
### Install @nuxtjs/axios
Source: https://v2.nuxt.com/docs/directory-structure/plugins
Install the Axios module for making HTTP requests. This is typically done using Yarn or NPM.
```bash
yarn add @nuxtjs/axios
```
```bash
npm install @nuxtjs/axios
```
--------------------------------
### Vuex Store Initialization Example
Source: https://v2.nuxt.com/docs/directory-structure/store
Illustrates how Nuxt internally constructs the Vuex.Store instance with root state and namespaced modules based on the store directory structure.
```javascript
new Vuex.Store({
state: () => ({
counter: 0
}),
mutations: {
increment(state) {
state.counter++
}
},
modules: {
todos: {
namespaced: true,
state: () => ({
list: []
}),
mutations: {
add(state, { text }) {
state.list.push({
text,
done: false
})
},
remove(state, { todo }) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle(state, { todo }) {
todo.done = !todo.done
}
}
}
}
})
```
--------------------------------
### Nuxt 2 Script Configuration for Development and Production
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-dev
Define npm scripts for starting the development server, building the application, and starting in production mode.
```json
{
"scripts": {
"dev": "node server.js",
"build": "nuxt build",
"start": "NODE_ENV=production node server.js"
}
}
```
--------------------------------
### Launch Nuxt Development Server (NPM)
Source: https://v2.nuxt.com/docs/get-started/commands
Use this command to start the Nuxt development server with hot module replacement enabled.
```bash
npm run dev
```
--------------------------------
### Run Nuxt Project with NPM
Source: https://v2.nuxt.com/docs/get-started/installation
After creating a Nuxt project, navigate to the project directory and use this command to start the development server with NPM.
```bash
cd
npm run dev
```
--------------------------------
### Install Build Module with Yarn
Source: https://v2.nuxt.com/docs/directory-structure/modules
Use this command to install a module as a development dependency when using Yarn.
```bash
yarn add --dev @nuxtjs/eslint-module
```
--------------------------------
### Component Directory Structure
Source: https://v2.nuxt.com/docs/features/component-discovery
Example of a typical Nuxt components directory structure.
```vue
| components/
--| TheHeader.vue
--| TheFooter.vue
```
--------------------------------
### Run Nuxt Project with PNPM
Source: https://v2.nuxt.com/docs/get-started/installation
After creating a Nuxt project, navigate to the project directory and use this command to start the development server with PNPM.
```bash
cd
pnpm dev
```
--------------------------------
### Launch Nuxt Development Server (Yarn)
Source: https://v2.nuxt.com/docs/get-started/commands
Use this command to start the Nuxt development server with hot module replacement enabled.
```bash
yarn dev
```
--------------------------------
### Install Build Module with NPM
Source: https://v2.nuxt.com/docs/directory-structure/modules
Use this command to install a module as a development dependency when using NPM.
```bash
npm install --save-dev @nuxtjs/eslint-module
```
--------------------------------
### Adding a Prefix to Static Asset Paths
Source: https://v2.nuxt.com/docs/directory-structure/static
This example shows how to manually add a prefix to static asset paths, which is useful if you customize `router.base`.
```html
```
--------------------------------
### Run Nuxt Project with Yarn
Source: https://v2.nuxt.com/docs/get-started/installation
After creating a Nuxt project, navigate to the project directory and use this command to start the development server with Yarn.
```bash
cd
yarn dev
```
--------------------------------
### Install Sass and Sass-loader
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-css
Install the necessary packages for using Sass in your Nuxt 2 project.
```bash
yarn add --dev sass sass-loader@10
```
```bash
npm install --save-dev sass sass-loader@10
```
--------------------------------
### Start Nuxt.js Project with NPM
Source: https://v2.nuxt.com/docs/get-started/installation
Use this command to run your Nuxt.js application in development mode with NPM. The application will be available at http://localhost:3000.
```bash
npm run dev
```
--------------------------------
### Fetch Hook Usage Example
Source: https://v2.nuxt.com/docs/features/data-fetching
Demonstrates how to use the fetch hook to retrieve data and assign it to component properties. It also shows configuration options like fetchOnServer, fetchKey, and fetchDelay.
```javascript
export default {
data: () => ({
posts: []
}),
async fetch() {
this.posts = await this.$http.$get('https://api.nuxtjs.dev/posts')
},
fetchOnServer: false,
// multiple components can return the same `fetchKey` and Nuxt will track them both separately
fetchKey: 'site-sidebar',
// alternatively, for more control, a function can be passed with access to the component instance
// It will be called in `created` and must not depend on fetched data
fetchKey(getCounter) {
// getCounter is a method that can be called to get the next number in a sequence
// as part of generating a unique fetchKey.
return this.someOtherData + getCounter('sidebar')
}
}
```
--------------------------------
### Nested Component Directory Structure
Source: https://v2.nuxt.com/docs/features/component-discovery
Example of a nested directory structure for components.
```vue
| components/
--| base/
----| foo/
------| Button.vue
```
--------------------------------
### Install Sass and Sass-Loader (Yarn)
Source: https://v2.nuxt.com/docs/directory-structure/assets
Install the `sass` and `sass-loader` packages using Yarn for Sass compilation in Nuxt 2.
```bash
yarn add --dev sass sass-loader@10
```
--------------------------------
### Example Directory Structure for Child Routes
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-router
Illustrates a typical directory structure in Nuxt.js for managing parent and child routes, including dynamic slugs.
```text
-| pages/
---| index.vue
---| posts.vue
---| posts/
-----| _slug.vue
-----| index.vue
```
--------------------------------
### Redirect Examples in Nuxt 2
Source: https://v2.nuxt.com/docs/internals-glossary/context
Shows how to use the redirect function within the Nuxt context to navigate users to different routes or external URLs.
```javascript
redirect(302, '/login')
redirect({ name: 'slug', params: { slug: mySlug } })
redirect('https://vuejs.org')
```
--------------------------------
### Install Nuxt with NPM
Source: https://v2.nuxt.com/docs/get-started/installation
Add Nuxt as a project dependency using NPM. This command also creates node_modules and a lock file.
```bash
npm install nuxt
```
--------------------------------
### Install Nuxt with PNPM
Source: https://v2.nuxt.com/docs/get-started/installation
Add Nuxt as a project dependency using PNPM. This command also creates node_modules and a lock file.
```bash
pnpm add nuxt --shamefully-hoist
```
--------------------------------
### Programmatic Nuxt Server Setup
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-dev
Instantiate Nuxt programmatically in a server.js file. The server builds in development mode if the 'dev' property is true.
```javascript
const { Nuxt, Builder } = require('nuxt')
const app = require('express')()
const port = process.env.PORT || 3000
// We instantiate Nuxt with the options
const config = require('./nuxt.config.js')
const nuxt = new Nuxt(config)
app.use(nuxt.render)
// Build only in dev mode
if (config.dev) {
new Builder(nuxt).build()
}
// Listen the server
app.listen(port, '0.0.0.0').then(() => {
console.log(`Server is listening on port: ${port}`)
})
```
--------------------------------
### Install Nuxt with Yarn
Source: https://v2.nuxt.com/docs/get-started/installation
Add Nuxt as a project dependency using Yarn. This command also creates node_modules and a lock file.
```bash
yarn add nuxt
```
--------------------------------
### Specify Component Extensions
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-components
Configure the file extensions to scan for components. This example limits scanning to `.vue` files, useful for multi-file component structures.
```javascript
// nuxt.config.js
export default {
components: [{ path: '~/components', extensions: ['vue'] }]
}
```
--------------------------------
### Nuxt Render with Express Example
Source: https://v2.nuxt.com/docs/internals-glossary/nuxt-render
Integrates Nuxt.js as middleware within an Express.js application. This example demonstrates loading Nuxt in development or production mode and using `nuxt.render` to handle all incoming requests.
```javascript
const { loadNuxt, build } = require('nuxt')
const app = require('express')()
const isDev = process.env.NODE_ENV !== 'production'
const port = process.env.PORT || 3000
async function start() {
// We get Nuxt instance
const nuxt = await loadNuxt(isDev ? 'dev' : 'start')
// Render every route with Nuxt
app.use(nuxt.render)
// Build only in dev mode with hot-reloading
if (isDev) {
build(nuxt)
}
// Listen the server
app.listen(port, '0.0.0.0')
console.log('Server listening on `localhost:' + port + '`.')
}
start()
```
--------------------------------
### Asynchronous nuxtServerInit Action
Source: https://v2.nuxt.com/docs/directory-structure/store
Implement asynchronous `nuxtServerInit` actions using `async/await` to ensure the Nuxt server waits for completion before proceeding. This example dispatches another action.
```javascript
actions: {
async nuxtServerInit({ dispatch }) {
await dispatch('core/load')
}
}
```
--------------------------------
### Using Custom Path Component
Source: https://v2.nuxt.com/docs/features/component-discovery
Example of using a component from a custom path in a page template.
```vue
```
--------------------------------
### Customizing Nuxt 2 Directories
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-dir
Example of how to specify custom directory names for various application components in Nuxt 2's nuxt.config.js.
```javascript
export default {
dir: {
assets: 'custom-assets',
app: 'custom-app',
layouts: 'custom-layouts',
middleware: 'custom-middleware',
pages: 'custom-pages',
static: 'custom-static',
store: 'custom-store'
}
}
```
--------------------------------
### Render Hook Setup
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-hooks
This hook module configures middleware for the render process, specifically setting up a route redirect to handle the `router.base` configuration.
```javascript
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))
}
}
}
```
--------------------------------
### Example .nuxtignore File
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-ignore
Use a .nuxtignore file to specify glob patterns for files that Nuxt should ignore in the root directory during the build phase. This file follows the .gitignore specification.
```ignore
# ignore layout foo.vue
layouts/foo.vue
# ignore layout files whose name ends with -ignore.vue
layouts/*-ignore.vue
# ignore page bar.vue
pages/bar.vue
# ignore page inside ignore folder
pages/ignore/*.vue
# ignore store baz.js
store/baz.js
# ignore store files match *.test.*
store/ignore/*.test.*
# ignore middleware files under foo folder except foo/bar.js
middleware/foo/*.js
!middleware/foo/bar.js
```
--------------------------------
### Start Nuxt.js Project with Yarn
Source: https://v2.nuxt.com/docs/get-started/installation
Use this command to run your Nuxt.js application in development mode with Yarn. The application will be available at http://localhost:3000.
```bash
yarn dev
```
--------------------------------
### Conditionally Transpile Dependencies
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-build
Transpile specific dependencies with Babel based on build conditions. This example transpiles the 'ky' package only when Nuxt is not in modern mode.
```javascript
{
build: {
transpile: [({ isLegacy }) => isLegacy && 'ky']
}
}
```
--------------------------------
### Render a Route with Nuxt.js
Source: https://v2.nuxt.com/docs/internals-glossary/nuxt-render-route
Demonstrates how to use `nuxt.renderRoute` to render a specific route ('/') after loading a Nuxt instance in start mode. Ensure `nuxt build` has been executed prior to running this script. The returned object contains `html`, `error`, and `redirected` properties.
```javascript
const { loadNuxt, build } = require('nuxt')
async function start() {
// Get nuxt instance for start (production mode)
// Make sure to have run `nuxt build` before running this script
const nuxt = await loadNuxt({ for: 'start' })
const { html, error, redirected } = await nuxt.renderRoute('/')
// `html` will always be a string
// `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 `asyncData()` or `fetch()`
// { path: '/other-path', query: {}, status: 302 }
}
start()
```
--------------------------------
### Custom Module Implementation
Source: https://v2.nuxt.com/docs/directory-structure/modules
An example of a custom Nuxt module written in JavaScript. It logs module options and Nuxt options, and registers a hook for when Nuxt is ready.
```javascript
export default function ExampleModule(moduleOptions) {
console.log(moduleOptions.token) // '123'
console.log(this.options.exampleMsg) // 'hello'
this.nuxt.hook('ready', async nuxt => {
console.log('Nuxt is ready')
})
}
// REQUIRED if publishing the module as npm package
module.exports.meta = require('./package.json')
```
--------------------------------
### Create Project Directory and Navigate
Source: https://v2.nuxt.com/docs/get-started/installation
Manually set up a Nuxt project by creating a new directory and navigating into it using the terminal.
```bash
mkdir
cd
```
--------------------------------
### Nuxt Project Scripts in package.json
Source: https://v2.nuxt.com/docs/get-started/installation
Define essential Nuxt commands (dev, build, generate, start) within the 'scripts' section of your package.json file.
```json
{
"name": "my-app",
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"generate": "nuxt generate",
"start": "nuxt start"
}
}
```
--------------------------------
### Customizing PostCSS Plugins
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-build
This example shows how to customize the default PostCSS configuration by disabling certain plugins and adding new ones. It demonstrates disabling `postcss-url` and adding `postcss-nested`, `postcss-responsive-type`, and `postcss-hexrgba`. The `preset.autoprefixer.grid` option is also configured.
```javascript
export default {
build: {
postcss: {
postcssOptions: {
plugins: {
// Disable `postcss-url`
'postcss-url': false,
// Add some plugins
'postcss-nested': {},
'postcss-responsive-type': {},
'postcss-hexrgba': {}
},
preset: {
autoprefixer: {
grid: true
}
}
}
}
}
}
```
--------------------------------
### Create Core Directories and Config File
Source: https://v2.nuxt.com/docs/get-started/directory-structure
Use these commands to set up essential directories and the Nuxt configuration file for a new project.
```bash
mkdir components assets static
touch nuxt.config.js
```
--------------------------------
### Custom Loading Component Example
Source: https://v2.nuxt.com/docs/features/loading
This Vue component can be used as a custom loading indicator in Nuxt. It exposes `start` and `finish` methods to control its visibility during route changes.
```vue
Loading...
```
--------------------------------
### Hooking into a Custom Module Event
Source: https://v2.nuxt.com/docs/internals-glossary/internals
Demonstrates how to listen for and respond to a custom module hook ('foo' in this example) within the Nuxt instance. This enables event-driven interactions between modules.
```javascript
nuxt.hook('foo', foo => {
// ...
})
```
--------------------------------
### Nuxt Loading Component Methods
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-loading
Example of how to programmatically control the Nuxt loading bar within a Vue component. This is typically used to manually start and finish the loading indicator.
```javascript
export default {
mounted() {
this.$nextTick(() => {
this.$nuxt.$loading.start()
setTimeout(() => this.$nuxt.$loading.finish(), 500)
})
}
}
```
--------------------------------
### Initialize Nuxt Programmatically
Source: https://v2.nuxt.com/docs/internals-glossary/nuxt
Use this snippet to load a Nuxt instance programmatically for use in your own server. It supports loading in development mode with live reloading or in start mode for production.
```javascript
const { loadNuxt, build } = require('nuxt')
// Check if we need to run Nuxt in development mode
const isDev = process.env.NODE_ENV !== 'production'
// Get a ready to use Nuxt instance
const nuxt = await loadNuxt(isDev ? 'dev' : 'start')
// Enable live build & reloading on dev
if (isDev) {
build(nuxt)
}
// We can use `nuxt.render(req, res)` or `nuxt.renderRoute(route, context)`
```
--------------------------------
### Nuxt Mountains Component Example
Source: https://v2.nuxt.com/docs/features/data-fetching
Demonstrates fetching data for a list of mountains and displaying loading, error, or content states. Includes a button to manually refresh the data.
```vue
Fetching mountains...
An error occurred :(
Nuxt Mountains
{{ mountain.title }}
```
--------------------------------
### Configure Environment Variables in nuxt.config.js
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-env
Define environment variables that will be available on the client side. This example sets a `baseUrl` using a server-side environment variable or a default value.
```javascript
export default {
env: {
baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
}
```
--------------------------------
### Create Project Directory and Package JSON
Source: https://v2.nuxt.com/docs
Manually create a project directory and initialize a package.json file for a Nuxt project.
```bash
mkdir
cd
```
```bash
touch package.json
```
--------------------------------
### Detecting Rendering Environment with process Helpers
Source: https://v2.nuxt.com/docs/concepts/context-helpers
Utilize the global process object's boolean helpers (client, server, static) within asyncData to determine the rendering context. This example shows how to identify if the page is rendered on the client or server.
```vue
I am rendered on the {{ renderedOn }} side
```
--------------------------------
### Create Pages Directory and Index Page
Source: https://v2.nuxt.com/docs
Set up the 'pages' directory and create an 'index.vue' file for the home page route.
```bash
mkdir pages
```
```bash
touch pages/index.vue
```
--------------------------------
### Install Pug and Sass Loaders (NPM)
Source: https://v2.nuxt.com/docs/features/configuration
Install the necessary webpack loaders for Pug and Sass when using them in your Nuxt 2 project via NPM.
```bash
npm install --save-dev pug pug-plain-loader
npm install --save-dev sass sass-loader@10
```
--------------------------------
### Install Pug and Sass Loaders (Yarn)
Source: https://v2.nuxt.com/docs/features/configuration
Install the necessary webpack loaders for Pug and Sass when using them in your Nuxt 2 project via Yarn.
```bash
yarn add --dev pug pug-plain-loader
yarn add --dev sass sass-loader@10
```
--------------------------------
### Accessing Preview Mode URL
Source: https://v2.nuxt.com/docs/features/live-preview
Append `?preview=true` to any page URL to activate live preview mode when serving the generated static site locally.
```bash
?preview=true
```
--------------------------------
### Register Nuxt Listen Hook
Source: https://v2.nuxt.com/docs/directory-structure/modules
Registers a hook to execute custom code when the Nuxt internal server starts listening.
```javascript
nuxt.hook('listen', async (server, { host, port }) => {
// Your custom code here
})
```
--------------------------------
### Vue Template Image Reference
Source: https://v2.nuxt.com/docs/directory-structure/assets
An example of referencing an image asset within a Vue template using the '~' alias.
```html
```
--------------------------------
### Create package.json file
Source: https://v2.nuxt.com/docs/get-started/installation
Create an empty package.json file in your project directory. This file manages project metadata and scripts.
```bash
touch package.json
```
--------------------------------
### Basic Module Usage in nuxt.config.js
Source: https://v2.nuxt.com/docs/directory-structure/modules
Shows how to register a custom module using its relative path and how to pass options to it.
```javascript
export default {
exampleMsg: 'hello',
modules: [
// Simple usage
'~/modules/example',
// Passing options directly
['~/modules/example', { token: '123' }]
]
}
```
--------------------------------
### Add User Agent to Context
Source: https://v2.nuxt.com/docs/directory-structure/middleware
Example of a middleware that adds the user agent to the Nuxt context. This middleware runs on both server and client.
```javascript
export default function (context) {
// Add the userAgent property to the context
context.userAgent = process.server
? context.req.headers['user-agent']
: navigator.userAgent
}
```
--------------------------------
### Create Nuxt App with NPM
Source: https://v2.nuxt.com/docs/get-started/installation
Use this command to quickly scaffold a new Nuxt.js project with NPM. It will prompt you for configuration options.
```bash
npm init nuxt-app
```
--------------------------------
### Configure Vue.config in nuxt.config.js
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-vue-config
Use the vue.config property in your nuxt.config.js file to set Vue.config options. This example configures productionTip and devtools.
```javascript
export default {
vue: {
config: {
productionTip: true,
devtools: false
}
}
}
```
--------------------------------
### Configure ignoreOptions in nuxt.config.js
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-ignore
Customize the behavior of the file ignoring mechanism by configuring ignoreOptions in your nuxt.config.js. This example sets ignorecase to false.
```javascript
export default {
ignoreOptions: {
ignorecase: false
}
}
```
--------------------------------
### Reorder Nuxt 2 Plugins
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-extend-plugins
Use extendPlugins to change the order of plugins. This example moves a specific plugin to the beginning of the array.
```javascript
export default {
extendPlugins(plugins) {
const pluginIndex = plugins.findIndex(
plugin => (typeof plugin === 'string' ? plugin : plugin.src) === '~/plugins/shouldBeFirst.js'
)
const shouldBeFirstPlugin = plugins[pluginIndex]
plugins.splice(pluginIndex, 1)
plugins.unshift(shouldBeFirstPlugin)
return plugins
}
}
```
--------------------------------
### Generate Static Site (NPM)
Source: https://v2.nuxt.com/docs/get-started/commands
Generates all routes as static HTML files for deployment on static hosting services.
```bash
npm run generate
```
--------------------------------
### Basic generate Configuration
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-generate
Configure the generation of your universal web application to a static web application.
```javascript
export default {
generate: {
...
}
}
```
--------------------------------
### Initialize Store with Server Data
Source: https://v2.nuxt.com/docs/directory-structure/store
Use the `nuxtServerInit` action in `store/index.js` to pass server-side data, like user sessions, to the client-side store during universal mode.
```javascript
actions: {
nuxtServerInit ({ commit }, { req }) {
if (req.session.user) {
commit('user', req.session.user)
}
}
}
```
--------------------------------
### Create Nuxt App with NPX
Source: https://v2.nuxt.com/docs/get-started/installation
Use this command to quickly scaffold a new Nuxt.js project with NPX. It will prompt you for configuration options.
```bash
npx create-nuxt-app
```
--------------------------------
### Define Page Transition Type
Source: https://v2.nuxt.com/docs/components-glossary/transition
You can define the page transition type as a String, Object, or Function. This example shows the basic structure for all three.
```javascript
export default {
// Can be a String
transition: ''
// Or an Object
transition: {}
// or a Function
transition (to, from) {}
}
```
--------------------------------
### Configure Nuxt 2 to Use Preview Plugin
Source: https://v2.nuxt.com/docs/features/live-preview
Register the `preview.client.js` plugin in your `nuxt.config.js` file to enable the live preview functionality.
```javascript
export default {
plugins: ['~/plugins/preview.client.js']
}
```
--------------------------------
### Configuring Nuxt 2 Modules
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-modules
Demonstrates various ways to include modules in the `nuxt.config.js` file, including package names, relative paths, modules with options, and inline function definitions.
```javascript
export default {
modules: [
// Using package name
'@nuxtjs/axios',
// Relative to your project srcDir
'~/modules/awesome.js',
// Providing options
['@nuxtjs/google-analytics', { ua: 'X1234567' }],
// Inline definition
function () {}
]
}
```
--------------------------------
### Configure Resource Preload and Prefetch
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-render
Configure default behavior for shouldPrefetch and shouldPreload to control tag generation for external resources.
```javascript
export default {
render: {
bundleRenderer: {
shouldPrefetch: () => false,
shouldPreload: (fileWithoutQuery, asType) => ["script", "style"].includes(asType),
},
},
}
```
--------------------------------
### Module Options with Top-Level Configuration
Source: https://v2.nuxt.com/docs/directory-structure/modules
Illustrates how to provide module-specific options in `nuxt.config.js` and how a module can access these options alongside top-level Nuxt configurations.
```javascript
export default {
modules: [['@nuxtjs/axios', { anotherOption: true }]],
// axios module is aware of this by using `this.options.axios`
axios: {
option1,
option2
}
}
```
--------------------------------
### Configure Prism theme in nuxt.config.js
Source: https://v2.nuxt.com/docs/directory-structure/content
Configure the Prism theme for syntax highlighting within the Nuxt Content module. This example sets the theme to prism-material-oceanic.
```javascript
content: {
markdown: {
prism: {
theme: 'prism-themes/themes/prism-material-oceanic.css'
}
}
}
```
--------------------------------
### Registering a Tapable Plugin Globally
Source: https://v2.nuxt.com/docs/internals-glossary/internals-module-container
Register a hook on the 'ready' lifecycle event using the global Nuxt instance. This hook executes after all modules have been initialized.
```javascript
nuxt.moduleContainer.plugin('ready', async moduleContainer => {
// Do this after all modules where ready
})
```
--------------------------------
### Custom Scroll Behavior
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-router
Define custom scroll behavior between routes by providing a function. This example forces the scroll position to the top for all route changes.
```javascript
export default function (to, from, savedPosition) {
return { x: 0, y: 0 }
}
```
--------------------------------
### Handling Unknown Dynamic Nested Routes with _.vue
Source: https://v2.nuxt.com/docs/features/file-system-routing
This file tree structure demonstrates how to use `_.vue` to dynamically match nested paths, useful for handling routes with unknown depth and custom 404 logic.
```javascript
pages/
--| people/
-----| _id.vue
-----| index.vue
--| _.vue
--| index.vue
```
--------------------------------
### Create Nuxt App with PNPM
Source: https://v2.nuxt.com/docs/get-started/installation
Use this command to quickly scaffold a new Nuxt.js project with PNPM. It will prompt you for configuration options.
```bash
pnpm create nuxt-app
```
--------------------------------
### Enable Following Symlinks in Build
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-build
Set `build.followSymlinks` to `true` to allow the build process to scan files within symbolic links. This is useful for including symlinked directories, such as those in the `pages` folder.
```javascript
export default {
build: {
followSymlinks: true
}
}
```
--------------------------------
### Configure PostCSS Plugins in nuxt.config.js
Source: https://v2.nuxt.com/docs/features/configuration
Add or disable PostCSS plugins and configure presets within the nuxt.config.js file. Ensure plugins are installed as project dependencies.
```javascript
export default {
build: {
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
}
}
}
}
}
```
--------------------------------
### Namespaced Vuex Module: Todos
Source: https://v2.nuxt.com/docs/directory-structure/store
Example of a namespaced Vuex module for managing a list of todos. Includes mutations for adding, removing, and toggling todo items.
```javascript
export const state = () => ({
list: []
})
export const mutations = {
add(state, text) {
state.list.push({
text,
done: false
})
},
remove(state, { todo }) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle(state, todo) {
todo.done = !todo.done
}
}
```
--------------------------------
### Registering a Tapable Plugin Within a Module
Source: https://v2.nuxt.com/docs/internals-glossary/internals-module-container
Register a hook on the 'ready' lifecycle event from within a module's context. This allows modules to react to the initialization of other modules.
```javascript
this.plugin('ready', async moduleContainer => {
// Do this after all modules where ready
})
```
--------------------------------
### nuxt.renderAndGetWindow(url, options)
Source: https://v2.nuxt.com/docs/internals-glossary/nuxt-render-and-get-window
Retrieves the window object from a specified Nuxt application URL. This function is primarily intended for testing scenarios. It requires the `jsdom` package to be installed.
```APIDOC
## nuxt.renderAndGetWindow(url, options)
### Description
Gets the `window` object from a given URL of a Nuxt Application. This method is made for test purposes.
### Method
`Function`
### Parameters
#### Arguments
1. **url** (`String`) - Required - The URL to render.
2. **options** (`Object`) - Optional - Configuration options.
- **virtualConsole** (`Boolean`) - Optional - Defaults to `true`.
### Returns
- `Promise` - A Promise that resolves with the `window` object.
### Example
```javascript
const { loadNuxt } = require('nuxt')
async function init() {
// Assuming you've already built your project
const nuxt = await loadNuxt({ for: 'start' })
await nuxt.listen(3000)
const window = await nuxt.renderAndGetWindow('http://localhost:3000')
// Display the head ``
console.log(window.document.title)
nuxt.close()
}
init()
```
```
--------------------------------
### Including a Plugin by String Path
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-plugins
Include a plugin by providing its path as a string in the plugins array.
```javascript
export default {
plugins: ['@/plugins/ant-design-vue']
}
```
--------------------------------
### Create Nuxt App with Yarn
Source: https://v2.nuxt.com/docs/get-started/installation
Use this command to quickly scaffold a new Nuxt.js project with Yarn. It will prompt you for configuration options.
```bash
yarn create nuxt-app
```
--------------------------------
### Nuxt Configuration with Build Modules
Source: https://v2.nuxt.com/docs/directory-structure/modules
Configure Nuxt to use `buildModules` for development and build-time only modules. This improves production startup speed and reduces the production `node_modules` size.
```javascript
export default {
buildModules: ['@nuxtjs/eslint-module']
}
```
--------------------------------
### Extend Routes with Named Views
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-router
Add routes that utilize named views, ensuring to specify corresponding `chunkNames` for the named components. This example adds a modal view.
```javascript
export default {
router: {
extendRoutes(routes, resolve) {
routes.push({
path: '/users/:id',
components: {
default: resolve(__dirname, 'pages/users'), // or routes[index].component
modal: resolve(__dirname, 'components/modal.vue')
},
chunkNames: {
modal: 'components/modal'
}
})
}
}
}
```
--------------------------------
### Change Route Name Splitter
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-router
Modify the separator used for generating route names from file paths. For example, changing from '-' to '/' for pages like `pages/posts/_id.vue`.
```javascript
export default {
router: {
routeNameSplitter: '/'
}
}
```
--------------------------------
### Asynchronous Router Middleware for Stats
Source: https://v2.nuxt.com/docs/directory-structure/middleware
An example of an asynchronous middleware that sends POST request with route information. This middleware is configured in `nuxt.config.js` to run on every route change.
```javascript
import http from 'http'
export default function ({ route }) {
return http.post('http://my-stats-api.com', {
url: route.fullPath
})
}
```
```javascript
export default {
router: {
middleware: 'stats'
}
}
```
--------------------------------
### Configuring Custom Folder Structure for Plugin File
Source: https://v2.nuxt.com/docs/internals-glossary/internals-module-container
Demonstrates how to specify a custom folder structure for a generated plugin file within the .nuxt directory by using path.join in the fileName option.
```javascript
{
fileName: path.join('folder', 'foo.client.js'), // will result in `.nuxt/folder/foo.client.js`
}
```
--------------------------------
### Object Transition Configuration
Source: https://v2.nuxt.com/docs/components-glossary/transition
Configure transition properties like name and mode using an object. This allows for more detailed control over transitions.
```javascript
export default {
transition: {
name: 'test',
mode: 'out-in'
}
}
```
```html
```
--------------------------------
### Using Server Timing API in Middleware
Source: https://v2.nuxt.com/docs/configuration-glossary/configuration-server
Utilize the `res.timing` API within server middleware to measure specific operations. The `start` and `end` methods record timing information.
```javascript
export default function (req, res, next) {
res.timing.start('midd', 'Middleware timing description')
// server side operation..
// ...
res.timing.end('midd')
next()
}
```
--------------------------------
### Use Axios in Page Components
Source: https://v2.nuxt.com/docs/directory-structure/plugins
Fetch data using the $axios instance within Nuxt page components. This example demonstrates fetching a post by ID using asyncData.
```vue