search
HomeWeb Front-endHTML Tutorial[翻译]理解CSS模块方法_html/css_WEB-ITnose

在这个前端发展日新月异的世界,能够找到有所影响的概念相当困难,而将其准确无误的传达,让人们愿意尝试,更是难上加难。

拿CSS来看,在我们写CSS时,工具侧最大的变化,也就是CSS处理器的使用,如:可能公认最好的SASS。还有PostCSS,提供了另一种不同的解决方案,但也相差不大,属于同种东西,都是输入浏览器不支持的语法,然后输出浏览器支持的语法。(这里和之前的文章认识不同可以点击《PostCSS的认识误区》查看详细)

现在,引入了CSS模块的概念。本文,将介绍这方面的技术,会讲到这种技术的几点,并且会告诉你怎么使用它。

CSS模块是什么?

官方定义:

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default.

一个CSS模块就是一个CSS文件,这个文件包含的所有类名和动画名默认都是局部作用域的。

实际比上面讲的要复杂一些,类名默认是局部作用域的,这涉及到一些配置,一个构建过程和一些很难把握的东西。

最终我们把CSS模块定义为一种把相关CSS代码组织成组件,并避免命名冲突的方法。(不用为你组件的命名担心,在构建的过程中会自动生成)。

CSS模块是怎么工作的?

CSS模块要放到构建过程中处理,它本身并不做什么。这看上去像是webpack或browserify的插件。它的工作原理是:当你在js模块里调用CSS模块时(比如:React组件),CSS模块将根据文件中动态作用域或命名空间里的类名, 声明一个对象字面量,字面量中的类名将被js以字符串的形式调用。

让我们用一个例子来说明。

建一个简单的CSS文件,.base类不是项目中唯一的,它不是作为实际的类名来使用的。它相当于样式里的一个别名,这个别名将在js模块中使用。

.base {  color: deeppink;  max-width: 42em;  margin: 0 auto;}

这里看一下,怎么在JS组件中使用。

import styles from './styles.css';element.innerHTML = `<div class="${styles.base}">  CSS Modules are fun.</div>`;

以上代码会生成下面这样的代码(使用webpack构建工具的默认配置):

<div class="_20WEds96_Ee1ra54-24ePy">CSS Modules are fun.</div>
._20WEds96_Ee1ra54-24ePy {  color: deeppink;  max-width: 42em;  margin: 0 auto;}

类名,可以通过配置把类名加上特殊前缀,或使用短命名,但这并不是重点(虽然短命名,代表着更少的CSS样式)。

重点是指出,类名是动态生成的,唯一的,并且和样式表正确映射的。

几个关于CSS模块的观点

上面讲了它是如何工作的。现在你心里一定有疑惑,下面让我们一一解决。

生成的代码太丑了!

类名又不是为了漂亮。它存在的目的是把样式应用到元素上,所以这并不值得关注。

不太容易调试

只是是要通过构建过程生成的代码,调试起来都不容易。Sass也不容易调试,但可以使用sourcemap,css模块也可以。实际上尽量类名是生成的,但根据模块里的具体样式调试并不难。如果你知道你正在调试的是哪个模块,你就可以去对应模块找到对应的样式了。

样式没法重用

重用性是没错的,但CSS模块的目的就是把样式组件化,清除全局的冲突和依赖。

另外,你也可以定义全局的类(用:global()),比如一些公用的样式。这些类名也是可以在js组件中调用的

:global(.clearfix::after) {  content: '';  clear: both;  display: table;}

CSS模块也可以像SASS的@extend一样,通过存在的模块来扩展。不是直接复制一份样式过来,而是对各选择器样式进行合并。

.base {  composes: appearance from '../AnoherModule/styles.css';}

CSS模块需要其它的构建工具,如:webpack,browserify等工具

这和SASS编译.scss文件为正确的CSS样式,PostCSS把样式处理为浏览器兼容的代码一样。既然已经使用了构建工具,这点也不用多想了。

为什么还在讨论这些点?

因为不确定未来的CSS模块是不是现在这样的,但这一定是样式书写的方向。大型网站使用的大量的全局样式,不适合分解成小的组件。

全局唯一的CSS名,既强大又脆弱。无论是CSS模块还是以后其它工具。都需要找到既可以具备全局样式的公用,又可以避免同作用域下样式的命名冲突的解决方案。

入门

上面提到了,使用CSS模块需要webpack或browserify来构建。

Webpack

使用webpack,先修改webpack.config.js文件,添加以下配置项,开启CSS模块功能。

{  test: /\.css$/,  loader: 'style-loader!css-loader?modules'}

以上配置会在你的页面插件

{  test: /\.css$/,  loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules')}

Browserify

使用Browserify,直接用命令行,代码参数有点多。可以使用npm来运行命令,配置一下package.json文件,代码如下:

{  "scripts": {    "build": "browserify -p [ css-modulesify -o dist/main.css ] -o dist/index.js src/index.js"  }}

解释一下,运行npm build,就相当于调用build对应的相关命令。处理src/index.js生成为dist/index.js,并通过css-modulesify插件编译dist/main.css样式。如果想通过Autoprefixer插件添加浏览器前缀,命令可改成下面这样:

{  "scripts": {    "build": "browserify -p [ css-modulesify --after autoprefixer -o dist/main.css ] -o dist/index.js src/index.js"  }}

--after 在编译完样式后再运行autoprefixer插件。

总结

现在,CSS模块系统的生态圈还太小,但我相信,随着越来越多的人认识到,这是适应于从小到大项目的解决方案,它会发展得越来越好。

CSS模块化思想是正确的路。我也不是说本文介绍的方法,就是最好的解决方案,但已经可以把CSS书写得,具备以下特征:模块化,作用域或可重用。

想了解更多相关信息,可参阅CSS模块项目创建人,Glen Maddern的《this introduction to CSS Modules》的文章。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools