Nuxt/docs/content/3.docs/2.directory-structure/15.nuxt.config.md

509 lines
12 KiB
Markdown
Raw Normal View History

---
icon: IconFile
title: nuxt.config.js
head.title: Nuxt configuration file
---
# Nuxt configuration file
Nuxt can be configured easily with one single file, called `nuxt.config`, it supports both `.js` and `.ts` extension.
```ts
export default {
// My Nuxt config
}
```
Learn more about all the different [config properties](/docs/config)
<!-- GENERATED_CONFIG_DOCS -->
## alias
- **Type**: `object`
- **Version**: 2, 3
- **Default**
```json
{
"~~": "/project",
"@@": "/project",
"~": "/project",
"@": "/project",
"assets": "/project/assets",
"public": "/project"
}
```
> You can improve your DX by defining additional aliases to access custom directories within your JavaScript and CSS.
::alert{type="info"}
**Note**: Within a webpack context (image sources, CSS - but not JavaScript) you _must_ access
your alias by prefixing it with `~`.
::
::alert{type="info"}
**Note**: If you are using TypeScript and want to use the alias you define within
your TypeScript files, you will need to add the aliases to your `paths` object within `tsconfig.json` .
::
**Example**:
```js
import { resolve } from 'pathe'
export default {
alias: {
'images': resolve(__dirname, './assets/images'),
'style': resolve(__dirname, './assets/style'),
'data': resolve(__dirname, './assets/other/data')
}
}
```
<!-- ```html
<template>
<img src="~images/main-bg.jpg">
</template>
<script>
import data from 'data/test.json'
</script>
<style>
// Uncomment the below
//@import '~style/variables.scss';
//@import '~style/utils.scss';
//@import '~style/base.scss';
body {
background-image: url('~images/main-bg.jpg');
}
</style>
``` -->
## buildDir
- **Type**: `string`
- **Version**: 2, 3
- **Default**
```json
"/project/.nuxt"
```
> Define the directory where your built Nuxt files will be placed.
Many tools assume that `.nuxt` is a hidden directory (because it starts with a `.`). If that is a problem, you can use this option to prevent that.
**Example**:
```js
export default {
buildDir: 'nuxt-build'
}
```
## buildModules
- **Type**: `array`
- **Version**: 2, 3
- **Default**
```json
[]
```
> Modules that are only required during development and build time.
Modules are Nuxt extensions which can extend its core functionality and add endless integrations
Each module is either a string (which can refer to a package, or be a path to a file), a tuple with the module as first string and the options as a second object, or an inline module function.
Nuxt tries to resolve each item in the modules array using node require path (in `node_modules`) and then will be resolved from project `srcDir` if `~` alias is used.
::alert{type="info"}
**Note**: Modules are executed sequentially so the order is important.
::
**Example**:
```js
modules: [
// Using package name
'@nuxtjs/axios',
// Relative to your project srcDir
'~/modules/awesome.js',
// Providing options
['@nuxtjs/google-analytics', { ua: 'X1234567' }],
// Inline definition
function () {}
]
```
::alert{type="info"}
**Note**: Using `buildModules` helps to make production startup faster and also significantly
decreases the size of `node_modules` in production deployments. Please refer to each
module's documentation to see if it is recommended to use `modules` or `buildModules`.
::
## dev
- **Type**: `boolean`
- **Version**: 2, 3
- **Default**
```json
true
```
> Whether Nuxt is running in development mode.
Normally you should not need to set this.
## dir
> Customize default directory structure used by nuxt.
It is better to stick with defaults unless needed.
### `layouts`
- **Type**: `string`
- **Version**: 2, 3
- **Default**
```json
"layouts"
```
> The layouts directory, each file of which will be auto-registered as a Nuxt layout.
### `pages`
- **Type**: `string`
- **Version**: 2, 3
- **Default**
```json
"pages"
```
> The directory which will be processed to auto-generate your application page routes.
### `public`
- **Type**: `string`
- **Version**: 3
- **Default**
```json
"public"
```
> The directory containing your static files, which will be directly accessible via the Nuxt server and copied across into your `dist` folder when your app is generated.
## extensions
- **Type**: `array`
- **Version**: 2, 3
- **Default**
```json
[
".js",
".mjs",
".ts",
".tsx",
".vue"
]
```
> The extensions that should be resolved by the Nuxt resolver.
## globalName
- **Type**: `string`
- **Version**: 2, 3
- **Default**
```json
"nuxt"
```
> Allows customizing the global ID used in the main HTML template as well as the main Vue instance name and other options.
## hooks
- **Type**: `any`
- **Version**: 2, 3
- **Default**
```json
null
```
> Hooks are listeners to Nuxt events that are typically used in modules, but are also available in `nuxt.config`.
Internally, hooks follow a naming pattern using colons (e.g., build:done).
For ease of configuration, you can also structure them as an hierarchical object in `nuxt.config` (as below).
**Example**:
```js
import fs from 'fs'
import path from 'path'
export default {
hooks: {
build: {
done(builder) {
const extraFilePath = path.join(
builder.nuxt.options.buildDir,
'extra-file'
)
fs.writeFileSync(extraFilePath, 'Something extra')
}
}
}
}
```
## modules
- **Type**: `array`
- **Version**: 2, 3
- **Default**
```json
[]
```
> Modules are Nuxt extensions which can extend its core functionality and add endless integrations
Each module is either a string (which can refer to a package, or be a path to a file), a tuple with the module as first string and the options as a second object, or an inline module function.
Nuxt tries to resolve each item in the modules array using node require path (in `node_modules`) and then will be resolved from project `srcDir` if `~` alias is used.
::alert{type="info"}
**Note**: Modules are executed sequentially so the order is important.
::
**Example**:
```js
modules: [
// Using package name
'@nuxtjs/axios',
// Relative to your project srcDir
'~/modules/awesome.js',
// Providing options
['@nuxtjs/google-analytics', { ua: 'X1234567' }],
// Inline definition
function () {}
]
```
## privateRuntimeConfig
- **Type**: `any`
- **Version**: 2, 3
- **Default**
```json
{}
```
> Runtime config allows passing dynamic config and environment variables to the Nuxt app context.
It is added to the Nuxt payload so there is no need to rebuild to update your configuration in development or if your application is served by the Nuxt server. (For static sites you will still need to regenerate your site to see changes.)
The value of this object is accessible from server only using `$config`.
It will override `publicRuntimeConfig` on the server-side.
It should hold _private_ environment variables (that should not be exposed on the frontend). This could include a reference to your API secret tokens.
**Example**:
```js
export default {
privateRuntimeConfig: {
apiSecret: process.env.API_SECRET
}
}
```
## publicRuntimeConfig
> Runtime config allows passing dynamic config and environment variables to the Nuxt app context.
It is added to the Nuxt payload so there is no need to rebuild to update your configuration in development or if your application is served by the Nuxt server. (For static sites you will still need to regenerate your site to see changes.)
The value of this object is accessible from both client and server using `$config`. It should hold env variables that are _public_ as they will be accessible on the frontend. This could include a reference to your public URL.
**Example**:
```js
export default {
publicRuntimeConfig: {
baseURL: process.env.BASE_URL || 'https://nuxtjs.org'
}
}
```
### `app`
- **Type**: `object`
- **Version**: 2, 3
- **Default**
```json
{
"basePath": "/",
"assetsPath": "/_nuxt/",
"cdnURL": null
}
```
## rootDir
- **Type**: `string`
- **Version**: 2, 3
- **Default**
```json
"/project"
```
> Define the workspace directory of your application.
This property can be overwritten (for example, running `nuxt ./my-app/` will set the `rootDir` to the absolute path of `./my-app/` from the current/working directory.
It is normally not needed to configure this option.
## serverMiddleware
- **Type**: `array`
- **Version**: 2, 3
- **Default**
```json
[]
```
> Server middleware are connect/express/h3-shaped functions that handle server-side requests. They run on the server and before the Vue renderer.
By adding entries to `serverMiddleware` you can register additional routes or modify `req`/`res` objects without the need for an external server.
You can pass a string, which can be the name of a node dependency or a path to a file. You can also pass an object with `path` and `handler` keys. (`handler` can be a path or a function.)
**Example**:
```js
serverMiddleware: [
// Will register redirect-ssl npm package
'redirect-ssl',
// Will register file from project server-middleware directory to handle /server-middleware/* requires
{ path: '/server-middleware', handler: '~/server-middleware/index.js' },
// We can create custom instances too
{ path: '/static2', handler: serveStatic(__dirname + '/static2') }
]
```
::alert{type="info"}
**Note**: If you don't want middleware to run on all routes you should use the object
form with a specific path.
::
<!-- If you pass a string handler, Nuxt will expect that file to export a default function
that handles `(req, res, next) => void`. -->
**Example**:
```js
export default function (req, res, next) {
// req is the Node.js http request object
console.log(req.url)
// res is the Node.js http response object
// next is a function to call to invoke the next middleware
// Don't forget to call next at the end if your middleware is not an endpoint!
next()
}
```
<!-- Alternatively, it can export a connect/express/h3-type app instance. -->
**Example**:
```js
const bodyParser = require('body-parser')
const app = require('express')()
app.use(bodyParser.json())
app.all('/getJSON', (req, res) => {
res.json({ data: 'data' })
})
module.exports = app
```
<!-- Alternatively, instead of passing an array of `serverMiddleware`, you can pass an object
whose keys are the paths and whose values are the handlers (string or function). -->
**Example**:
```js
export default {
serverMiddleware: {
'/a': '~/server-middleware/a.js',
'/b': '~/server-middleware/b.js',
'/c': '~/server-middleware/c.js'
}
}
```
## srcDir
- **Type**: `string`
- **Version**: 2, 3
- **Default**
```json
"/project"
```
> Define the source directory of your Nuxt application.
If a relative path is specified it will be relative to the `rootDir`.
**Example**:
```js
export default {
srcDir: 'client/'
}
```
This would work with the following folder structure:
```bash
-| app/
---| node_modules/
---| nuxt.config.js
---| package.json
---| client/
------| assets/
------| components/
------| layouts/
------| middleware/
------| pages/
------| plugins/
------| static/
------| store/
```
## ssr
- **Type**: `boolean`
- **Version**: 2, 3
- **Default**
```json
true
```
> Whether to enable rendering of HTML - either dynamically (in server mode) or at generate time. If set to `false` and combined with `static` target, generated pages will simply display a loading screen with no content.
## watchers
> The watchers property lets you overwrite watchers configuration in your `nuxt.config`.
### `chokidar`
> Options to pass directly to `chokidar`.
**See**: [chokidar](https://github.com/paulmillr/chokidar#api)
#### `ignoreInitial`
- **Type**: `boolean`
- **Version**: 2, 3
- **Default**
```json
true
```
### `rewatchOnRawEvents`
- **Type**: `any`
- **Version**: 2, 3
- **Default**
```json
{}
```
> An array of event types, which, when received, will cause the watcher to restart.
### `webpack`
> `watchOptions` to pass directly to webpack.
**See**: [webpack@4 watch options](https://v4.webpack.js.org/configuration/watch/#watchoptions).
#### `aggregateTimeout`
- **Type**: `number`
- **Version**: 2, 3
- **Default**
```json
1000
```