preface
At present, the development of javascript is obvious. At the same time, HTML moved in tandem with the HTML5 standard, which gained popularity. This development is missing one character?
CSS, the seemingly insignificant guy, is playing as important a role as JS in development. CSS, which is a style script, seems to have some distance from the programming language, we can think of it as a description method. This seems to lead to CSS being looked down upon. However, CSS has been undergoing a major change in recent years — the CSS Module. I remember that the JS blowout should be said to have been brought about by Node, which introduced the concept of Module, allowing JS to be engineered for development projects. So, today’s CSS, will be better and better. If you like my article, welcome to comment, welcome to Star~. Welcome to my Github blog
The body of the
Since as a PostCSS article, we should first understand what this is, and we talked about CSS Module before what relationship? Let me explain it to you.
I want to say goodbye to you
Currently, Less, Sass, and Stylus are the most used in engineering development. First, let’s introduce them. They have a common name — CSS preprocessors. What is a CSS preprocessor? It should be something that converts the format you write according to its rules into CSS. They come at just the right time to address some of the shortcomings of CSS:
- The syntax is not powerful enough for nested writing, which is not conducive to modular development
- There is no reuse mechanism for variables and logic, resulting in the use of literal form in CSS attribute values, and the repeated writing of repeated styles, which makes it difficult to maintain.
In the face of the above problems, THE CSS preprocessor provides a very feasible solution:
-
Variables: Just like in other programming languages, they are protected from multiple changes.
- Sass: Declare variables with “$” and separate variable names and values with colons
- Less: uses @ to declare variables
- Variables declared in Stylus are not qualified; the ending semicolon is optional, but there must be an “equal sign” between the variable name and its value. Note, however, that Stylus compiles but does not assign to variables if you declare them with the “@” symbol. That is, Stylus does not use “@” to declare variables. Stylus invokes variables in exactly the same way as Less or Sass.
-
Scope: With variables, you must have scope to manage them. Just like JS, it looks up variables from the local scope.
- Sass: Its way is the worst of the three, there is no concept of global variables
- Less: It works in a similar way to JS, looking up variables step by step
- Stylus: It is similar in style to Less, but like Sass it prefers directive lookup
-
Nesting: For CSS, nesting is perfect, more like explicit parent-child relationships
- All three are treated the same here, using ampersand to indicate the parent element
With these solutions, we can write CSS styles with DPY, maintainability, and flexibility.
Getting back to the topic, the solution to the preprocessor is ultimately the result of the lag in the development of the CSS standard. At the same time, we should also consider, is the preprocessor really enough? When your project is too big, the problem of global variables will continue to haunt you due to the lack of a modular concept. Whenever you define a selector, always consider whether other files use the same name. After all, a project is a team, not an individual. Is there a way to solve these problems?
Predecessors’ method
The CSS naming conflict problem has a long history. We front-end developers are thinking hard every day about how to solve these problems gracefully. CSS does not have the same modular solution as JS with AMD, CMD, and ES6 modules.
So, back to the problem, how to solve it? Our predecessors have also proposed different schemes:
- Object-Oriented CSS
- BEM
- SMACSS
Solutions can be said to be endless, there is no lack of internal team solutions. But most of them have one thing in common — adding prefixes to selectors.
This is a manual task, and you may need to write long selectors manually, perhaps using pre-compiled CSS. But they do not seem to address the underlying question of why this is happening. Let’s look at an example written using the BEM specification:
<! -- True. Elements are in the 'search-form' module -->
<! -- 'search-form' module -->
<form class="search-form">
<! -- 'input' element in 'search-form' -->
<input class="search-form__input" />
<! -- 'button' element in 'search-form' -->
<button class="search-form__button"></button>
</form>
<! -- Not true. Element outside the context of the 'search-form' module -->
<! -- 'search-form' module -->
<form class=""search-block>
</form>
<! -- 'input' element in 'search-form' -->
<input class="search-form__input"/>
<! -- 'button' element in 'search-form' -->
<button class="search-form__button"></button>Copy the code
Every time write like this, estimate is a programmer, all have to work overtime, ha ha!
A kind of hope
Now the web development, pay attention to the idea of componentization, therefore, the urgent need to feasible CSS Module way to complete the development of web components. Since 2015, CSS-In-JS (a typical representative, react Styled components) has become popular in foreign countries, and there is also a STYLE called CSS Module.
This article talks about the latter. If you need to understand the former, just Google it
CSS, as we all know, is a descriptive language, not dynamic. So, how to form a Module. React uses postCSS as an example:
//example.css
.article {
font-size: 14px;
}
.title {
font-size: 20px;
}Copy the code
Then, shuffle the names:
.zxcvb{
font-size: 14px;
}
.zxcva{
font-size: 20px;
}Copy the code
Place the corresponding content of the name in a JSON file:
{
"article": "zxcvb"."title": "zxcva"
}Copy the code
Then, in the js file, use:
import style from 'style.json';
class Example extends Component{
render() {
return (
<div classname={style.article}>
<div classname={style.title}></div>
</div>)}}Copy the code
In this way, a CSS module prototype is drawn. Of course, we can’t always write these things manually. We need an automated plug-in to help us with this process. After that, we should take a look at postCSS.
I need to know you
What is PostCSS? You might think of it as a preprocessor, or a post-processor, or whatever. Well, it’s nothing. It can be understood as a plug-in system. Use the description on the GitHub home page:
PostCSS is a tool for transforming CSS with JS plugins. These plugins can support variables and mixins, transpile future CSS syntax, inline images, and more.
You can use it with preprocessors, or you can use it with native CSS. It’s all supported, and it has a huge ecosystem, such as Autoprefixer, a popular plugin for PostCSS, which is widely used by Google, Shopify, Twitter, Bootstrap and CodePen, among others.
Of course, we can also use it in CodePen:
I recommend you take a look at the PostCSS in-depth series
Next, let’s look at the PostCSS configuration:
Here we use a combination of webpack+ PostCSS + PostCSs-loader + CssNext + postCSs-import.
First, we can install these packages through YARN:
yarn add --dev webpack extract-text-webpack-plugin css-loader file-loader postcss postcss-loader postcss-cssnext postcss-importCopy the code
Then, let’s configure webpack.config.js:
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = {
context: path.resolve(__dirname, 'src'),
entry: {
app: './app.js';
},
module: {
loaders: [{test: /\.css$/.use: ExtractTextPlugin.extract({
use: [{loader: 'css-loader'.options: { importLoaders: 1}},'postcss-loader',],}),},],},output: {
path: path.resolve(__dirname, 'dist/assets'),},plugins: [
new ExtractTextPlugin('[name].bundle.css')]};Copy the code
Then configure postcss.config.js in the root directory
module.exports = {
plugins: {
'postcss-import': {},
'postcss-cssnext': {
browsers: ['last 2 versions'.'> 5%'],}}};Copy the code
After that, you can use cSSNext’s features in your development
/* Shared */
@import "shared/colors.css";
@import "shared/typography.css";
/* Components */
@import "components/Article.css";Copy the code
/* shared/ color.css */ :root {--color: RGB (0,0,0); --color-blue: #32c7ff; } /* shared/typography.css */ :root { --font-text: "FF DIN", sans-serif; --font-weight: 300; - the line - height: 1.5; } /* components/Article.css */ .article { font-size: 14px; & a { color: var(--color-blue); } & p { color: var(--color-black); font-family: var(--font-text); font-weight: var(--font-weight); line-height: var(--line-height); } @media (width > 600px) { max-width: 30em; }}Copy the code
Finally, use WebPack to compile.
conclusion
PostCSS, the domestic has not been too popular, but I believe that in the near future will gradually become popular, and the domestic resources are less, but recently a new desert teachers together translation of the book – “in-depth PostCSS Web design”. People who are interested can also look at it and learn something about the introduction. This article also only wrote about PostCSS, in view of the domestic resources are less, so reference to the foreign blog teaching materials, there will be links below.
If you have any questions about what I wrote, you can comment on it. If I wrote something wrong, you are welcome to correct it. You like my blog, please follow me Star~ yo. We summarize and make progress together. Welcome to my Github blog
Refer to the link
PostCSS-modules:
make CSS great again!
PostCSS Deep Dive: What You Need to Know
Advertisement: I heard that writing an article can get the book of asynchronous community, asynchronous community as the top IT professional book community in China, its book I want very much, so I try my best to write this article, I want this book, if you feel good to give me a thumbs-up