大家好,我是Ysh,谨以此系列文章献给正在找工作的开发兄弟们,愿大家年年高升无寒冬。
创作不易,还请兄弟们多多点赞、收藏、关注 三联走起~
现代CSS模块化技术
CSS in JS
CSS in JS 是一种将CSS直接嵌入到JavaScript代码中的技术,主要用于React等现代前端框架。它允许开发者在编写组件时,将样式与组件逻辑紧密结合在一起。styled-components 和 Emotion 是两个流行的CSS in JS库。
styled-components
styled-components 是一个允许你在JavaScript中写CSS的库。它利用了ES6的模板字符串语法来定义样式,并与React组件绑定。
-
安装
npm install styled-components -
使用示例
// App.js import React from 'react'; import styled from 'styled-components'; const Button = styled.button` background: palevioletred; border: none; border-radius: 3px; color: white; padding: 0.5em 1em; font-size: 1em; `; const App = () => ( <div> <Button>Click Me</Button> </div> ); export default App;
Emotion
Emotion 是另一个流行的CSS in JS库,它提供了类似styled-components的API,同时支持更高的性能和灵活性。
-
安装
npm install @emotion/react @emotion/styled -
使用示例
// App.js /** @jsxImportSource @emotion/react */ import { css } from '@emotion/react'; import styled from '@emotion/styled'; const buttonStyle = css` background: lightblue; border: none; border-radius: 3px; color: white; padding: 0.5em 1em; font-size: 1em; `; const Button = styled.button` ${buttonStyle}; `; const App = () => ( <div> <Button>Click Me</Button> </div> ); export default App;
CSS Modules
CSS Modules 是一种CSS的模块化方案,它将每个CSS文件视为一个独立的模块,并且在编译时自动生成唯一的类名,防止样式冲突。
使用示例
-
安装(如果使用Create React App,则已默认支持)
npm install --save-dev css-loader -
定义样式
/* App.module.css */ .button { background: lightcoral; border: none; border-radius: 3px; color: white; padding: 0.5em 1em; font-size: 1em; } -
引入并使用样式
// App.js import React from 'react'; import styles from './App.module.css'; const App = () => ( <div> <button className={styles.button}>Click Me</button> </div> ); export default App;
Less和Sass
Less 和 Sass 是两种流行的CSS预处理器,提供了变量、嵌套、混合等功能,使CSS编写更加灵活和高效。
Less
Less 是一种CSS预处理语言,它扩展了CSS语言,添加了变量、嵌套规则、混合等功能。
-
安装
npm install less -
定义样式
// styles.less @primary-color: lightblue; .button { background: @primary-color; border: none; border-radius: 3px; color: white; padding: 0.5em 1em; font-size: 1em; } -
编译和使用
lessc styles.less styles.css<link rel="stylesheet" href="styles.css">
Sass
Sass 是另一种CSS预处理语言,提供了更强大的功能和灵活性。
-
安装
npm install sass -
定义样式
// styles.scss $primary-color: lightblue; .button { background: $primary-color; border: none; border-radius: 3px; color: white; padding: 0.5em 1em; font-size: 1em; } -
编译和使用
sass styles.scss styles.css<link rel="stylesheet" href="styles.css">
优缺点对比
-
Less
- 优点:
- 语法简单,容易上手。
- 与CSS兼容,现有CSS文件可以直接使用。
- 缺点:
- 功能相对较少,灵活性不如Sass。
- 优点:
-
Sass
- 优点:
- 功能强大,提供了嵌套规则、变量、混合等高级功能。
- 支持两种语法:Sass(缩进语法)和SCSS(类似CSS的语法)。
- 缺点:
- 语法复杂,学习曲线较高。
- 优点: