NaiveUI和TailwindCSS的样式冲突问题解决

NaiveUI和TailwindCSS的样式冲突问题解决

hash070 1,140 2023-03-17

简介

一般情况下,当NaiveUI和TailwindCSS被同时引入到一个项目中时,会出现一些组件样式异常的问题,本篇文章用于记录如何解决NaiveUI和TailwindCSS样式冲突的问题。

创建项目

创建一个新的Vue项目

首先用pnpm+vite创建一个空的vue项目

pnpm create vite

image.webp

如果你没有安装pnpm和vite,可以通过这行命令安装:npm i -g pnpm vite

引入NaiveUI和TailwindCSS

引入NaiveUI组件库

pnpm add -D naive-ui vfonts

引入TailwindCSS

pnpm add -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

执行上面两个命令后,根目录下会出现:tailwind.config.cjs这个文件,将这个文件中的内容修改如下:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{vue,js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

将CSS引入到src/style.css

@tailwind base;
@tailwind components;
@tailwind utilities;

然后在App.vue放点NButton先试试效果:

<script setup lang="ts">
import {NButton} from "naive-ui";
</script>

<template>
    <n-button>Default</n-button>
    <n-button type="tertiary">
      Tertiary
    </n-button>
    <n-button type="primary">
      Primary
    </n-button>
    <n-button type="info">
      Info
    </n-button>
    <n-button type="success">
      Success
    </n-button>
    <n-button type="warning">
      Warning
    </n-button>
    <n-button type="error">
      Error
    </n-button>
</template>

<style scoped>

</style>

效果如下:

image.webp

可以看到这里的按钮样式出现了问题

解决样式冲突

src/main.ts改成下面这样,原理是让naive-ui-style在 app 挂载之前动态的插入 meta 标签,防止TailwindCSS造成样式覆盖:

import { createApp } from 'vue'
import './style.css'
import App from './App.vue'

async function bootstrap() {
    const app = createApp(App)
    const meta = document.createElement('meta')
    meta.name = 'naive-ui-style'
    document.head.appendChild(meta)
    app.mount('#app')
}

bootstrap()

效果如图:

image.webp

参考文章:NaiveUI文档-潜在的样式冲突