Skip to content

Nuxt3 配置 和 渲染流程

渲染流程

配置文件

  • app.config.ts

  • nuxt.config.ts

Nuxt 配置(nuxt.config.ts)

Nuxt 已经配置了合理的默认值,以提高你的生产效率。

nuxt.config.ts 文件位于 Nuxt 项目的根目录,可以覆盖或扩展应用程序的行为。

一个最简配置文件导出了 defineNuxtConfig 函数,函数中包含了一个配置对象。defineNuxtConfig 助手函数在全局范围内无需导入即可使用。

js
export default defineNuxtConfig({
  // 我的Nuxt配置
});

通常在文档中会提到此文件,例如添加自定义脚本、注册模块或更改渲染模式。

INFO

你不必使用 TypeScript 来构建 Nuxt 应用程序。

然而,强烈推荐使用.ts 扩展名作为 nuxt.config 文件的扩展名。

这样你可以在 IDE 中受益于提示,避免在编辑配置时出现拼写错误和其他错误。

- 环境覆盖

你可以在nuxt.config中配置完全类型化的环境覆盖

js
export default defineNuxtConfig({
  // 生产环境
  $production: {
    routeRules: {
      "/**": { isr: true },
    },
  },
  // 开发环境
  $development: {
    //
  },
});

- 环境变量和私有令牌

runtimeConfig API 将像环境变量这样的值暴露给应用程序的其余部分。默认情况下,这些键只在服务器端可用。

但是

runtimeConfig.public 中的键也可以在客户端使用。

这些值应该在 nuxt.config 中定义,并可以使用环境变量进行覆盖。

js
export default defineNuxtConfig({
  runtimeConfig: {
    // 只在服务器端可用的私有键
    apiSecret: "123",
    // public中的键也可以在客户端使用
    public: {
      apiBase: "/api",
    },
  },
});

这些变量通过useRuntimeConfig()组合函数暴露给应用程序的其余部分。

html
<script setup lang="ts">
  const runtimeConfig = useRuntimeConfig();
</script>

应用程序配置(app.config.js)

app.config.ts 文件位于源目录中(默认为项目的根目录),用于公开在构建时确定的公共变量。

runtimeConfig 选项不同,这些变量不能使用环境变量进行覆盖。

一个最简配置文件导出了 defineAppConfig 函数,函数中包含了一个配置对象。defineAppConfig 助手函数在全局范围内无需导入即可使用。

js
// app.config.ts
export default defineAppConfig({
  title: "Hello Nuxt",
  theme: {
    dark: true,
    colors: {
      primary: "#ff0000",
    },
  },
});

这些变量通过 useAppConfig 组合函数暴露给应用程序的其余部分。

html
<script setup lang="ts">
  const appConfig = useAppConfig();
  console.log(appConfig.title);
  console.log(appConfig.theme.colors);
</script>

Nuxt 配置与应用程序区分

  • nuxt.config.ts 需要在构建后使用环境变量指定的私有或公共令牌。

  • app.config.ts 在构建时确定的公共令牌,网站配置(如主题变体、标题)以及不敏感的项目配置等。

功能nuxt.config.tsapp.config.ts
客户端已注入已打包
环境变量✅ 是❌ 否
响应式✅ 是✅ 是
类型支持✅ 部分支持✅ 是
每个请求的配置❌ 否✅ 是
热模块替换❌ 否✅ 是
非原始 JS 类型❌ 否✅ 是

外部配置文件

Nuxt 使用 nuxt.config.ts 文件作为配置的唯一来源,并跳过读取外部配置文件。

在构建项目的过程中,你可能需要配置这些文件。

下表列出了常见的配置以及如何在 Nuxt 中配置它们(如果适用)。

名称配置文件如何配置
Nitronitro.config.tsnuxt.config中使用nitro
PostCSSpostcss.config.jsnuxt.config中使用postcss
Vitevite.config.tsnuxt.config中使用vite
webpackwebpack.config.tsnuxt.config中使用webpack

以下是常见单独配置文件

名称配置文件
TypeScripttsconfig.json
ESLint.eslintrc.js
Prettier.prettierrc.json
Stylelint.stylelintrc.json
TailwindCSStailwind.config.js
Vitestvitest.config.ts

Vue 配置

如果你需要传递选项给 @vitejs/plugin-vue@vitejs/plugin-vue-jsx,你可以在你的 nuxt.config 文件中进行配置。

  • vite.vue 用于 @vitejs/plugin-vue。 可以在这里查看可用选项。

  • vite.vueJsx 用于 @vitejs/plugin-vue-jsx。可以在这里查看可用选项。

js
export default defineNuxtConfig({
  vite: {
    vue: {
      customElement: true,
    },
    vueJsx: {
      mergeProps: true,
    },
  },
});