Nuxt快速学习开发(四)-Nuxt3静态资源Assets

2,725 阅读1分钟

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

  • public/目录内容按原样在服务器根目录中提供。
  • assets/目录包含您希望构建工具(Vite 或 webpack)处理的所有资产。

public/目录

public目录用作静态资产的公共服务器,可在您的应用程序定义的URL上公开访问。 public/您可以从您的应用程序代码或通过根 URL 从浏览器中获取目录中的文件/

例如,引用public/img/目录中的图像文件,可在静态 URL 获得/img/nuxt.png

image.png

``app.vue
<template>
  <img src="/img/nuxt.png" alt="Discover Nuxt 3" />
</template>

assets/目录

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

Nuxt 使用该assets/目录来存储这些文件,但该目录没有自动扫描功能,可以为它使用任何其他名称。 例如,如果构建工具配置为处理此文件扩展名,则引用将被处理的图像文件:

``app.vue
<template>
  <img src="~/assets/img/nuxt.png" alt="Discover Nuxt 3" />
</template>

可以通过配置nuxt.config.ts配置别名,以便更好的访问资源,例:

``nuxt.config.ts
export default defineNuxtConfig({
  alias: {
    //配置别名
    images: fileURLToPath(new URL("./assets/img", import.meta.url)),
    style: fileURLToPath(new URL("./assets/style", import.meta.url)),
    data: fileURLToPath(new URL("./assets/other", import.meta.url)),
  },
 )}
``app.vue
<template> <div> <img src="~/img/nuxt.png" /> </div> </template>

全局样式导入

要在 Nuxt 组件样式中全局插入语句,需要再nuxt.config.ts中配置vite选项 资产/_colors.scss资产/_colors.sass

assets/_colors.scss

$primary: #49240F;
$secondary: #E4A79D;
``nuxt.config.ts
export default defineNuxtConfig({
  vite: {
    css: {
      preprocessorOptions: {
        sass: {
         additionalData: '@use "@/assets/_colors.scss" as *;'
        }
      }
    }
  }
})

后续学习使用到其他技能更新❤