CSS引入和预处理
这篇笔记我们介绍如何在Vite工程中引入CSS样式,使用CSS预处理语言,以及如何集成TailwindCSS。
引入CSS
在Vite工程的JavaScript代码中,我们可以直接使用import
引入CSS文件,这种写法一般都出现在顶层组件中,常用于引入一个全局生效的CSS样式表文件。具体来说,这种写法引入的CSS会被处理为HTML页面上直接的CSS文件引入。
import "@/index.css";
使用CSS Module
和其它框架类似,Vite中所有以.module.css
为后缀名的CSS文件被视为CSS Module,导入这样的CSS文件会返回一个模块。CSS Module是局部生效的,这是因为构建后框架会处理CSS Module中的CSS类名,同一个页面上属于不同CSS Module的CSS类即使名字相同,经过框架处理后它们也不会互相冲突。下面例子中,我们简单的编写了一个组件,它使用CSS Module引入局部的CSS。
import styles from "@/components/Title/index.module.css";
const Title = ({ children }) => {
return <h1 className={styles.mytitle}>{children}</h1>;
};
export default Title;
.mytitle {
color: red;
font-size: 2rem;
text-align: center;
}
加载CSS预处理语言
Vite也提供了对Less、Scss、Sass、Stylus的内置支持,但我们需要额外安装相应的预处理器才能使用。以Less为例,执行以下命令安装Less预处理器。
npm install less --save-dev
然后我们像前面使用CSS一样引入Less即可。
import styles from "@/components/Title/index.module.less";
使用TailwindCSS
在Vite中使用TailwindCSS最简单的方式是使用TailwindCSS官方提供的Vite插件。
npm install tailwindcss @tailwindcss/vite --save-dev
在vite.config.js
中,我们需要添加TailwindCSS的Vite插件。
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
import tailwindcss from "@tailwindcss/vite";
import react from "@vitejs/plugin-react";
const __dirname = dirname(fileURLToPath(import.meta.url));
export default defineConfig({
resolve: {
alias: {
"@": resolve(__dirname, "./src"),
},
},
plugins: [react(), tailwindcss()],
});
在全局CSS中,我们还需要使用@import
引入Tailwind相关的CSS。
@import "tailwindcss";
至此,TailwindCSS在Vite工程中就可以正常使用了,下面是一个例子。
const Title = ({ children }) => {
return <h1 className="text-4xl font-bold text-gray-800 tracking-tight mb-4">{children}</h1>;
};
export default Title;
作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。