本文正在参加「金石计划」
缘起
时光荏苒
,距离上次在掘金上写文章,已经有8个多月的时间了!
最近广州的天气是真冷!气温最低到6℃附近了,天大寒,键盘冰坚,手指不可屈伸...
赶着金石计划的末班车,记录下最近对于 Nuxt 3 框架的学习所得。
本文探索如何使用 Nuxt3 搭建一个项目,以及 Nuxt 3 项目的渲染模式、目录结构等内容。
前言
Nuxt 是什么?
根据 官网的介绍,Nuxt 是一个基于 Vue.js 的开源框架,可以用于构建类型安全、高性能的全栈网站。
Nuxt is a free and open-source framework with an intuitive and extendable way to create type-safe, performant and production-grade full-stack web applications and websites with Vue.js.
Nuxt 是广受欢迎的一个Vue框架,最新版本是 v3.8.2 ,Github 的 star 数高达 49.1k。
新建项目
废话不多说,先试着新建一个Nuxt项目。使用 pnpm 命令:
kotlin
pnpm dlx nuxi@latest init nuxt3-231219
不幸的是,安装过程中大概率会报错:Error: Failed to download template from registry: fetch failed
这里,我们可以直接打开链接,去下载对应的最新代码,得到压缩文件starter-3.tar.gz
,接着解压即可。
bash
cd nuxt3-231219
pnpm i
pnpm dev
打开浏览器 http://localhost:3000/ 进行预览,可以看到应用成功跑起来了:

目录结构

解压文件starter-3.tar.gz
后我们可以得到一个最简单的 Nuxt 3 应用,其目录结构如下所示:
arduino
.nuxt
在开发模式下,Nuxt 使用该文件夹生成 Vue 应用。
public
存放静态资源,比如 favicon.ico。
server
用于注册 API、存放 middleware、路由等。
app.vue
Nuxt应用的主组件。
nuxt.config.ts
应用的配置文件。比如:
export default defineNuxtConfig({
devtools: { enabled: true }
})
package.json
设置应用的依赖和运行命令等。
tsconfig.json
Nuxt 会自动生成 .nuxt/tsconfig.json(包含 sensible defaults and aliases)。在根目录新建文件 tsconfig.json 并设置如下:
{
"extends": "./.nuxt/tsconfig.json"
}
此外,可能还含有以下文件和目录:
lua
.output
包含构建生成的文件
assets
包含项目的资源文件,比如 .css, 字体文件、图片等。
components
放置页面组件。
layouts
放置模板文件。
middleware
放置中间件。
pages
放置新建的页面,Nuxt 3 支持以下类型的页面:.vue, .js, .jsx, .mjs, .ts or .tsx
运行脚本
- nuxt dev 启动本地开发模式
- nuxt build 构建应用
- nuxt generate && nuxt preview 静态站点生成+预览
- nuxt prepare 生成 .nuxt 文件夹、生成相应的TypeScript定义
package.json
json
{
"name": "nuxt3-231219",
"private": true,
"type": "module",
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"devDependencies": {
"@nuxt/devtools": "latest",
"nuxt": "^3.8.2",
"vue": "^3.3.12",
"vue-router": "^4.2.5"
}
}
渲染模式
Nuxt 3 是一种 SSR 框架,具有多种渲染模式,除了通用渲染外,还有单纯的客户端渲染模式、静态站点生成模式等。
通用渲染
通用渲染(Universal rendering),即 服务端渲染 + 水化(hydration)。
客户端渲染
客户端渲染(Client-Side Rendering) 是通过设置 nuxt.config.ts
:
arduino
export default defineNuxtConfig({
ssr: false
})
静态站点生成
使用命令 nuxt generate
命令就可以生成静态站点(Static Site Generate, SSG),使用nuxt preview
命令预览项目。
运行命令,Nuxt会依次构建客户端文件(Building client...)和服务端文件(Building server...),然后预渲染3个初始路由页面(/200.html, /404.html, /)。最后,生成 .output/public 文件夹,可以直接用于预览和部署。
我们可以看到输出如下:
bash
Nuxt 3.8.2 with Nitro 2.8.1
ℹ Using Nitro server preset: static
ℹ Compiled plugins/server.mjs in 533.12ms
ℹ Compiled plugins/client.mjs in 780.17ms
ℹ Building client...
ℹ vite v4.5.1 building for production...
ℹ ✓ 105 modules transformed.
Inspect report generated at E:/personal/demos/nuxt-demos/nuxt3-231219/.nuxt/analyze/.vite-inspect
ℹ .nuxt/dist/client/manifest.json 2.28 kB │ gzip: 0.36 kB
ℹ .nuxt/dist/client/_nuxt/error-500.cbe832a1.css 1.95 kB │ gzip: 0.74 kB
ℹ .nuxt/dist/client/_nuxt/error-404.7b8544b4.css 3.63 kB │ gzip: 1.12 kB
ℹ .nuxt/dist/client/_nuxt/entry.b0874c83.css 12.14 kB │ gzip: 2.50 kB
ℹ .nuxt/dist/client/_nuxt/error-500.b855ee54.js 1.88 kB │ gzip: 0.99 kB
ℹ .nuxt/dist/client/_nuxt/error-404.9e28e287.js 6.37 kB │ gzip: 2.81 kB
ℹ .nuxt/dist/client/_nuxt/entry.7d6554f8.js 203.61 kB │ gzip: 57.97 kB
ℹ ✓ built in 4.34s
✔ Client built in 4385ms
ℹ Building server...
ℹ vite v4.5.1 building SSR bundle for production...
ℹ ✓ 64 modules transformed.
Inspect report generated at E:/personal/demos/nuxt-demos/nuxt3-231219/.nuxt/analyze/.vite-inspect
ℹ .nuxt/dist/server/_nuxt/entry-styles.d255ae9b.mjs 0.08 kB
ℹ .nuxt/dist/server/_nuxt/error-404-styles.d352c5f6.mjs 0.15 kB
ℹ .nuxt/dist/server/_nuxt/error-500-styles.a47c06d2.mjs 0.15 kB
ℹ .nuxt/dist/server/styles.mjs 0.59 kB
ℹ .nuxt/dist/server/_nuxt/island-renderer-8418b861.js 1.23 kB │ map: 1.59 kB
ℹ .nuxt/dist/server/_nuxt/error-500-styles-1.mjs-ad5bc82f.js 2.17 kB │ map: 0.12 kB
ℹ .nuxt/dist/server/_nuxt/error-500-57b8c5e5.js 3.19 kB │ map: 3.84 kB
ℹ .nuxt/dist/server/_nuxt/error-404-styles-1.mjs-712507d9.js 3.86 kB │ map: 0.12 kB
ℹ .nuxt/dist/server/_nuxt/multipart-parser-71ea4b82.js 7.31 kB │ map: 10.83 kB
ℹ .nuxt/dist/server/_nuxt/error-404-2bafce18.js 10.22 kB │ map: 21.25 kB
ℹ .nuxt/dist/server/_nuxt/entry-styles-1.mjs-c95fda03.js 12.40 kB │ map: 0.11 kB
ℹ .nuxt/dist/server/server.mjs 288.64 kB │ map: 433.21 kB
ℹ ✓ built in 3.94s
✔ Server built in 3965ms
ℹ Initializing prerenderer
ℹ Prerendering 3 initial routes with crawler
├─ /200.html (136ms)
├─ /404.html (137ms)
├─ / (144ms)
├─ /_payload.json (3ms)
✔ Generated public .output/public
✔ You can preview this build using npx serve .output/public
✔ You can now deploy .output/public to any static hosting!
混合渲染
根据文档:
Hybrid rendering allows different caching rules per route using Route Rules and decides how the server should respond to a new request on a given URL.
需要注意的是,nuxt generate
不支持混合渲染模式(Hybrid Rendering)。
配置如下:
arduino
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
// Homepage pre-rendered at build time
'/': { prerender: true },
// Product page generated on-demand, revalidates in background
'/products/**': { swr: 3600 },
// Blog post generated on-demand once until next deploy
'/blog/**': { isr: true },
// Admin dashboard renders only on client-side
'/admin/**': { ssr: false },
// Add cors headers on API routes
'/api/**': { cors: true },
// Redirects legacy urls
'/old-page': { redirect: '/new-page' }
}
})
其中,路由规则是:
vbnet
redirect: string - Define server-side redirects.
ssr: boolean - Disables server-side rendering for sections of your app and make them SPA-only with ssr: false
cors: boolean - Automatically adds cors headers with cors: true - you can customize the output by overriding with headers
headers: object - Add specific headers to sections of your site - for example, your assets
swr: number|boolean - Add cache headers to the server response and cache it on the server or reverse proxy for a configurable TTL (time to live). The node-server preset of Nitro is able to cache the full response. When the TTL expired, the cached response will be sent while the page will be regenerated in the background. If true is used, a stale-while-revalidate header is added without a MaxAge.
isr: number|boolean - The behavior is the same as swr except that we are able to add the response to the CDN cache on platforms that support this (currently Netlify or Vercel). If true is used, the content persists until the next deploy inside the CDN.
prerender:boolean - Prerenders routes at build time and includes them in your build as static assets
experimentalNoScripts: boolean - Disables rendering of Nuxt scripts and JS resource hints for sections of your site.
边缘渲染
边缘渲染(Edge Side Rendering, ESR)就是借助 CDN 的边缘计算能力,将返回的内容进行静态+动态部分拆分并以流的形式返回,优化了网站性能、减少延迟。参考链接。
Nuxt 3 是借助 Nitro 实现的。Nuxt3 提供了跨平台支持,能够同时运行在 Node.js、Deno、Cloudflare Workers 等运行环境中。
Nuxt3 vs Nuxt2
接下来,比较下 Nuxt3 和 Nuxt2 各自的优缺点。
总的来说,Nuxt 3 有很多优点,比如 Nuxt 3 性能更佳,使用了 Nitro 引擎,对于 ESM 和 TS 完全支持,支持 Vite 和 webpack 5,支持 Composition API 和 Options API(Nuxt 2 只支持 Options API),等等。具体比较如下:
Feature / Version | Nuxt 2 | Nuxt Bridge | Nuxt 3 |
---|---|---|---|
Vue | 2 | 2 | 3 |
Stability | 😊 Stable | 😌 Semi-stable | 😊 Stable |
Performance | 🏎 Fast | ✈️ Faster | 🚀 Fastest |
Nitro Engine | ❌ | ✅ | ✅ |
ESM support | 🌙 Partial | 👍 Better | ✅ |
TypeScript | ☑️ Opt-in | 🚧 Partial | ✅ |
Composition API | ❌ | 🚧 Partial | ✅ |
Options API | ✅ | ✅ | ✅ |
Components Auto Import | ✅ | ✅ | ✅ |
<script setup> syntax |
❌ | 🚧 Partial | ✅ |
Auto Imports | ❌ | ✅ | ✅ |
webpack | 4 | 4 | 5 |
Vite | ⚠️ Partial | 🚧 Partial | ✅ |
Nuxi CLI | ❌ Old | ✅ nuxi | ✅ nuxi |
Static sites | ✅ | ✅ | ✅ |
后记
这段时间,心血来潮在考虑做些什么、偶尔在深入学习某个知识点、时常在摸鱼 ==!