小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
Vite 从入门到精通 | 处理 CSS
准备环境
创建 vite-css-vue3 项目
$ yarn create vite
✔ Project name: … vite-css-vue3
✔ Select a framework: › vue
✔ Select a variant: › vue
$ cd vite-css-vue3
$ yarn
$ cd src
# 创建 style 文件夹
$ mkdir style
# 创建 index.css
$ touch index.css
配置 vue-jsx 插件
$ yarn add @vitejs/plugin-vue-jsx -D
// vim vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 引入 jsx 依赖
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),// 使用 vue-jsx
]
})
- 在 src 目录下创建 App.jsx
import { defineComponent } from "@vue/runtime-core";
import "./style/index.css"
export default defineComponent({
setup() {
return () => <div class="root">Hello Vue3 Jsx</div>
}
})
- 修改 main.js
-- import App from './App.vue'
++ import App from './App'
- Vim index.css
.root {
color: red;
}
- 在浏览器中查看效果
原生 CSS variable [官方推荐]
简单来说, css 中可以支持变量的定义了~
vim index.css
/* :root 代表命名空间 */
:root {
--main-bg-color: blue
}
.root {
color: var(--main-bg-color);
}
- 在浏览器中查看效果
postcss
# ~根目录
$ yarn add @postcss-plugins/console -d # 安装插件
$ touch postcss.config.js
// postcss.config.js
module.exports = {
// css console 输出插件
plugins: [require("@postcss-plugins/console")]
}
在 css 中写日志~
/* index.css */
/* :root 代表命名空间 */
:root {
--main-bg-color: blue
}
.root {
@console.error hello root;
color: var(--main-bg-color);
}
- 在控制台查看日志
/vite-css-vue3/src/style/index.css
[postcss-console] hello root (7, 5)
@import alias (css import 映射设置)
// vim vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// 引入 jsx 依赖
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),// 使用 vue-jsx
],
resolve: {
alias: {
"@style": "/src/style",// 增加@styles 映射
}
}
})
// App.jsx
import { defineComponent } from "@vue/runtime-core";
import "@style/index.css" // 使用 alias
export default defineComponent({
setup() {
return () => <div class="root">Hello Vue3 Jsx</div>
}
})
css-modules
什么是 css-modules?
/*test.module.css*/
.moduleClass {
color: yellow
}
// App.jsx
import { defineComponent } from "@vue/runtime-core";
import "@style/index.css"
import classes from '@style/test.module.css'
export default defineComponent({
setup() {
return () => {
return <div class={`root ${classes.moduleClass}`}>Hello Vue3 Jsx</div>
}
}
})
核心: CSS pre-processors [sass,less,stylus]
Vite CSS 预处理工具
使用 less
yarn add less -D
touch /src/style/index.less
// /src/style/index.less
@bgColor: red;
.root {
background-color: @bgColor;
}
// App.jsx
import { defineComponent } from "@vue/runtime-core";
import "@style/index.css"
import "@style/index.less"
import classes from '@style/test.module.css'
export default defineComponent({
setup() {
return () => {
return <div class={`root ${classes.moduleClass}`}>Hello Vue3 Jsx</div>
}
}
})