Assets
Nuxt使用两个目录来处理样式表、字体或图像等资产。
public/
目录
public/
目录用作应用程序定义URL公开可用的静态资产的公共服务器。
您可以从应用程序的代码或通过根URL/
从浏览器中获取public/
目录中的文件。
示例:
例如,引用public/img/
目录中的图像文件,可在静态URL/img/nuxt.png
:
app.vue
<template>
<img src="/img/nuxt.png" alt="Discover Nuxt 3" />
</template>
assets/
目录
Nuxt使用Vite或Webpack构建和捆绑您的应用程序。这些构建工具的主要功能是处理JavaScript文件,但它们可以通过plugins(适用于Vite)或loaders(用于Webpack)进行扩展,以处理其他类型的资产,如样式表、字体或SVG。此步骤主要出于性能或缓存目的转换原始文件(例如样式表缩小或浏览器缓存无效)。
按照惯例,Nuxt使用assets/
目录来存储这些文件,但此目录没有自动扫描功能,您可以使用任何其他名称。
在应用程序的代码中,您可以使用~/assets/
路径引用位于assets/
目录中的文件。
示例:
例如,引用如果构建工具配置为处理此文件扩展名,则将处理的图像文件:
app.vue
<template>
<img src="~/assets/img/nuxt.png" alt="Discover Nuxt 3" />
</template>
Nuxt不会将assets/目录中的文件当成静态url,比如/assets/my-file.png。如果需要静态URL,请使用public/
全局样式引入
要在Nuxt组件样式中全局插入声明,可以在Nuxt.config文件中使用Vite选项。
示例:
在本例中,有一个sass部分文件,其中包含颜色变量,供您的Nuxt页面和组件使用
assets/_colors.scss
$primary: #49240F;
$secondary: #E4A79D;
assets/_colors.sass
$primary: #49240F
$secondary: #E4A79D
在nuxt.config
SCSS
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: '@use "@/assets/_colors.scss" as *;'
}
}
}
}
})
SASS
export default defineNuxtConfig({
vite: {
css: {
preprocessorOptions: {
sass: {
additionalData: '@use "@/assets/_colors.sass" as *\n'
}
}
}
}
})