虽然 Nuxt 模块提供了丰富的功能,但有时某个特定的 Vite 插件可能更直接地满足你的需求。
首先,我们需要安装 Vite 插件,在本例中,我们将使用 @rollup/plugin-yaml:
npm install @rollup/plugin-yaml
yarn add @rollup/plugin-yaml
pnpm add @rollup/plugin-yaml
bun add @rollup/plugin-yaml
接下来,我们需要在 nuxt.config.ts 文件中导入并添加它:
import yaml from '@rollup/plugin-yaml'
export default defineNuxtConfig({
vite: {
plugins: [
yaml(),
],
},
})
现在我们已经安装并配置好了 Vite 插件,可以开始在项目中直接使用 YAML 文件了。
例如,我们可以有一个存储配置信息的 config.yaml,并在 Nuxt 组件中导入这份数据:
greeting: "Hello, Nuxt with Vite!"
<script setup>
import config from '~/data/hello.yaml'
</script>
<template>
<h1>{{ config.greeting }}</h1>
</template>
如果你正在开发 Nuxt 模块并需要添加 Vite 插件,应使用 addVitePlugin 工具:
import { addVitePlugin, defineNuxtModule } from '@nuxt/kit'
import yaml from '@rollup/plugin-yaml'
export default defineNuxtModule({
setup () {
addVitePlugin(yaml())
},
})
对于 Nuxt 5+ 中的特定环境插件,请使用 applyToEnvironment() 方法:
import { addVitePlugin, defineNuxtModule } from '@nuxt/kit'
export default defineNuxtModule({
setup () {
addVitePlugin(() => ({
name: 'my-client-plugin',
applyToEnvironment (environment) {
return environment.name === 'client'
},
// 插件配置
}))
},
})
config 和 configResolved 钩子,而不是使用 Nuxt 的 vite:extend、vite:extendConfig 和 vite:configResolved。