NuxtJS - 01.基础教程

82 阅读4分钟

nuxtJS官网:nuxt.com/

nuxtJS中文官网:www.nuxtjs.cn/

1. 开发环境:

开发环境:Node.js - v18.0.0+

开发工具:Visual Studio Code

2.项目基础依赖:

animate.css 4.1.1

nuxt 3.13.0

sass 1.79.4

vue 3.5.12

vue-router 4.4.5

3.项目搭建及相关配置:

1. 项目搭建

安装NuxtJS:npx nuxi@latest init

image.png

这边告诉我们使用的是v3 template,其实就是基于vue3的template(模板)

运行命令 :npm run dev,在浏览器中打开:http://localhost:3000/

2. 使用vs code打开项目

第一步:安装扩展

image.png

安装了Nuxtr这个扩展会出现在vs code左侧下方,在里面可以(build)构建项目/(dev)运行项目等,还可以查看依赖(Dependencies)以及创建文件模板(File Templates)

image.png

第二步:在vs code 运行和调试(图标包含个小虫子)处,创建launch.json

image.png

接着把如下配置粘进去

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "client: chrome",
            //"runtimeExecutable":"C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe",
            "url": "http://localhost:3000",
            "webRoot": "${workspaceFolder}"
        },
        {
            "type": "node",
            "request": "launch",
            "name": "server: nuxt",
            "outputCapture": "console",//std or console
            // "program": "${workspaceFolder}//.nuxt//dist//server//server.mjs",
            "program": "${workspaceFolder}/node_modules/nuxi/bin/nuxi.mjs",
            "args": [
                "dev"
            ],
            "sourceMaps": true, // 启用源代码映射,这对于调试编译后的代码(如TypeScript)很有用  
            // "outFiles": [
            //     "${workspaceFolder}/.nuxt/dist/server/server.js" // 这是Nuxt项目编译后服务器代码的路径,你可能需要根据实际情况修改  
            // ],
            "skipFiles": [
                "<node_internals>/**" // 跳过Node.js内部文件的调试  
            ],
            "env": {
                "NODE_ENV": "development" // 设置环境变量为开发模式  
            },
        },
        //先使用npm run dev运行程序  然后找到bin/nuxt.js的程序进行attach
        {
            "type": "node",
            "request": "attach",
            "name": "server: nuxt attach",
            "processId": "${command:PickProcess}",
            "port": 9229
        }
    ],
    "compounds": [
        {
            "name": "fullstack: nuxt",
            "configurations": [
                "server: nuxt",
                "client: chrome"
            ]
        }
    ]
}

image.png

成功后,你可以看到运行和调试处有如下选项,分别是

1.client:chrome 使用浏览器对客户端(其实就是前端代码)调试

2.server:nuxt 调试nuxt服务端

3.fullstack:nuxt 调试所有的nuxt(全栈:包含前后端)

4. 目录结构:

image.png

package.json里面主要是脚本信息和依赖信息。

tsconfig.json 是ts(typescript的相关配置),目前是继承了基础配置

“extends”: “./.nuxt/tsconfig.json”

5. nuxt的配置:

1. 在nuxt.config.ts中添加

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  compatibilityDate: '2024-04-03',
  devtools: { enabled: true },
  routeRules: {
    // 为了SEO目的,在构建时生成
    '/': { prerender: true },
    // 缓存1小时
    '/api/*': { cache: { maxAge: 60 * 60 } },
    // 重定向以避免404
    '/old-page': {
      redirect: { to: '/new-page', statusCode: 302 }
    }
    // ...
  },
  $production: {
    routeRules: {
      '/**': { isr: true }
    }
  },
  $development: {
    //
  },
  runtimeConfig: {
    // 只在服务器端可用的私有键
    apiSecret: '123',
    // public中的键也可以在客户端使用
    public: {
      apiBase: '/api'
    }
  },
  vite: {
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/assets/_colors.scss" as *;'
        }
      }
    }
  },
  css: ['~/assets/css/main.css', 'animate.css'],
  //页面过渡效果 真的所有页面
  app: {
    pageTransition: { name: 'page', mode: 'out-in' }
  },
  sourcemap: {
    server: true,
    client: true
  },
})

2.局部解释

$production: {
  routeRules: {
    '/**': { isr: true }
  }
},

isr: true 允许你在构建网站后创建或更新静态页面,意味着我们运行项目后添加的页面及配置 仍然能生效 不需要重新启动项目

runtimeConfig: {
    apiSecret: '123',
    public: {
      apiBase: '/api'
    }
}

在runtimeConfig里面有public - apiBase 这个是后端接口的前缀,如果需要访问接口需要带上api,例如后端接口看起来是127.0.0.1:3000/foo,实际你访问需要访问的是127.0.0.1:3000/api/foo

3. 应用程序配置

这个我们需要在项目根目录下新建一个ts文件: app.config.ts

export default defineAppConfig({
  title: 'Hello Nuxt',
  theme: {
    dark: true,
    colors: {
      primary: '#ff0000'
    }
  },
})

app.config.ts 文件用于公开在构建时可以确定的公共变量。与 runtimeConfig 选项相反,这些变量不能使用环境变量覆盖。(这里意味着,以title属性为例在运行期间他是不能被覆盖 被更改的)

4. nuxt配置(nuxt.config.ts)和应用程序配置(app.config.ts)的区别

如上所述,runtimeConfig和app.config都用于向应用程序的其余部分公开变量。为了确定应该使用其中之一,以下是一些指导原则:

runtimeConfig:需要在构建后使用环境变量指定的私有或公共令牌。

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

5. 资源(assets)

Nuxt提供了两种选项来处理你的资源。

Nuxt使用两个目录来处理样式表、字体或图片等资源。

–| public/ 目录中的内容会按原样作为服务器根目录下的公共资源提供。

–| assets/ 目录按约定包含了你希望构建工具(Vite或webpack)处理的所有资源。

1. 公共目录(public folder)

public/ 目录用作应用程序的公共服务器,用于存放在应用程序的指定URL下公开访问的静态资源。

你可以通过应用程序的代码或浏览器的根URL / 获取 public/ 目录中的文件。

2. 资源目录(assert folder)

Nuxt使用 Vite(默认)或 webpack 来构建和打包你的应用程序。这些构建工具的主要功能是处理JavaScript文件,但它们可以通过 插件(对于Vite)或 加载器(对于webpack)来处理其他类型的资源,如样式表、字体或SVG。此步骤主要是为了提高性能或缓存目的而对原始文件进行转换(例如样式表的缩小或浏览器缓存失效)。

按照约定,Nuxt使用 assets/ 目录来存储这些文件,但该目录没有自动扫描功能,你可以使用任何其他名称。

在应用程序的代码中,你可以通过使用 ~/assets/ 路径来引用位于 assets/ 目录中的文件。

3. 样式

本地样式表

如果你正在编写本地样式表,将它们放在 assets目录下是最自然的位置。

这边我们新建一个first.css,这时我们有两种方式访问到它

方式1:页面中引入first.css

1.1 在javaScript中 import 相关样式 这边有静态和动态导入

1.2 或者使用 css 的 @import 语句

<script>
// 使用静态导入以实现服务器端兼容性
import '~/assets/css/first.css'

// 注意:动态导入不兼容服务器端
import('~/assets/css/first.css')
</script>

<style>
@import url("~/assets/css/first.css");
</style>

方式2:配置全局样式,意味着所有页面都能访问到css

(在nuxt.config.ts中配置如下代码)

export default defineNuxtConfig({
  css: ['~/assets/css/first.css']
})

此处仅介绍这两种方式,其他的方式请移步官网。