From Sass to Postcss

Source: Internet
Author: User
Tags postcss css preprocessor

From Sass to Postcss

I've been using sass for years. But recently I wanted to use POSTCSS and its Cssnext plugin to try to work with styles. I love it. You can now use future CSS features, which are more handy than the tools I used earlier. My personal site is the best place to test for new features.

The first step is to list my sass usage. I need to know what features I've used, and I'm sure there are alternatives to the new features in Postcss. Here are the features I'm using in this project:

    • Partial reference (partial import)

    • Variable (variables)

    • Nesting (nesting)

    • Mixed macro (Mixins)

    • Outreach (Extend)

    • Placeholder class (placeholder classes)

    • Color function (darken and RGBA color functions)

    • Compression (compression)

Preparatory work

I need to do some preparation after switching to the new syntax. The directory structure of the project is now a typical use of sass. I use an underscore (_) to name the file, and the extension of the file is named Scss. I use two folders to organize Sass files. Moudules folder save Sass files that do not directly produce CSS , such as variables, placeholder classes, and mixed macros. Partials Save the Sass file that compiles the CSS.

This is the original file structure:

css/  scss/    modules/      _module.scss      ...    partials/      _partial.scss ...    Tylergaw.scss

Each SASS component is introduced in the TYLERGAW.SCSS.

@import "Modules/setup", @import "Modules/reset", @import "modules/fonts";

I re-organized and renamed the file. I first changed the suffix name of all files from Scss to CSS. I used a bash script to do the work, not a single change.

' for f in *.scss; Do git mv--"$f" "${f%.scss}.css"; Done; '

The preceding underline is the habit of writing sass so I've also removed it. I can't use bash commands to do it all at once, so you can only manually modify each one.

The final step is to move all the CSS files to the Modules folder and delete the Partials folder. I think it is easier to manage all CSS as a modules than to split them into moudules/partials.

Environment construction

I started with the Postcss CLI and added a temporary build script command to the Package.json:

"Scripts": {  "postcss": "Postcss-o public/css/tylergaw.css src/css/tylergaw.css"}

I compiled the CSS without changing any of the styles:

' NPM run Postcss '

Work properly. The console does not have an error, but there is no CSS style on the page.

The build process is available, and the task now is to get the style back.

I've seen a lot of 404 messages in the chrome console. This means that the first feature we lost was that the inline @import.tylergaw.css introduced the CSS module via @import. The browser sees these, Know what it's going to do. The browser loads each module with an HTTP request. My build process replicates only a single CSS file, not every module. Because of this, browsers cannot find them.

I can change the build process to make the default @import work, but that's inefficient. I need a sass style inline @import alternative.

First Plug-in

The Postcss-import plugin can replace the @import in Sass, and after installing via NPM, I updated the build script code:

"Scripts": {  "postcss": "Postcss-u postcss-import-o public/css/tylergaw.css Src/css/tylergaw.css"}

Running NPM run Postcss again, a single CSS file contains all the modules. The page now shows some of the styles.

Will this be the future of CSS?

It is very powerful to show the @import function of inline mode in sass. It allows us to organize styles better. I'm not sure if this feature will be natively supported in the future. When we use this feature, we always need to compile it in one step and not look bad.

I think the Postcss-import plugin will be a major configuration for my postcss, and it should be the same for everyone else. The following is a reference to the plugin author's view:

This plugin should probably is used as the first plugin of your list. This is, other plugins would work on the AST as if there were only a single file to process, and would probably work as you Can expect.

[Postcss-import]

Cssnext

Cssnext is a plugin in postcss that compiles future CSS features into today's supported features. In particular, it should be noted that It is not a different language than sass or less. It provides the features of the CSS specification in progress. Some features have been supported by browsers. Others are in the initial stages of the specification.

I use Cssnext to fill the gap left by the lost Sass character.

Browser private Prefix

I've known autoprefixer before I built this site. I used custom sass to add a hybrid macro to solve the problem of adding the required prefixes. Cssnext contains autoprefixer, so I can remove this entire mixed macro module.

Variable

Next I'll change the sass variable to a CSS custom property. For example, in _setup.scss, I write:

$grey: #1e1e1d; $yellow: #ffad15; $offwhite: #f8f8f8; $darkerwhite: Darken ($offwhite, 15);

This is not all the sass variables I use, but that's mostly it. The rest is in a separate module.

Note: The difference between a custom attribute and a variable. CSS custom properties are valid only in property values and cannot be used for selectors, property names, or media queries.

The new setup.css:

: root {  --white: #fff;  --grey: #1e1e1d;  --yellow: #ffad15;  --offwhite: #f8f8f8;  ...}

The following are examples of use:

A {  color:var (--yellow);}

In addition to the syntax, CSS custom properties and SASS variables work the same way. Custom attribute values still need to be compiled due to browser-supported restrictions. In the example above, the compiled value is color: #ffad15.

Color function

In the previous example, I omitted a variable: $darkerwhite: Darken ($offwhite, 15);. This is another SASS feature I need to look for alternative. Here is a draft specification that provides CSS color functions. Cssnex now contains these functions, which is very cool. Here is Setup.css, where Darkerwhite custom properties are implemented by color functions and shadow conditioners.

: root {  ...  --offwhite: #f8f8f8;  --darkerwhite:color (Var (--offwhite) Shade (20%));  ...}

The color function provides a number of regulators. You can use multiple regulators in one function:

' Background-color:color (#d32c3f shade (40%) alpha (40%)); '

The result of the compilation is:

' Background-color:rgba (127, 26, 38, 0.4); '

Again, Cssnext will now compile color () to a color value of 16 or RGBA. When the color function is supported by the browser, the compilation process is not necessary. The color operation can occur at run time.

Nesting

Nesting is an essential feature of the CSS preprocessor. Anything that makes a comfortable style tool necessary. Tab Atkins has an ongoing specification for CSS nesting, and Cssnext makes it a reality.

The nested syntax for CSS consists of a & that is placed before the inner layer, and the following is a sass fragment:

. projects-list {  ...  Li {    & > P {...}  }  A {    ...    &:hover,    &:focus {...}    &::after {...}  }  @media (min-width:640px) {...}}

For CSS nesting, I'll modify it to the following form:

. projects-list {  ...  & li {    & > P {...}  }  & A {    ...    &:hover,    &:focus {...}    &::after {...}  }  @media (min-width:640px) {...}}

Basic nesting requires pre-& pseudo-classes and selectors are the same in sass and CSS. Media queries do not require a predecessor &

It is also noteworthy that @nest. As mentioned in the documentation, complex nesting may require the introduction of @nest instead of & This project I have not used, perhaps in the future to be used.

Expansion and Placeholder classes

The @extend and placeholder classes in SASS are the two features that I often use. Here is an example of the style of the Futura head:

%futura {  font-family: ' Futura-pt ', Helvetica, Sans-serif;} %futura-heading {  @extend%futura;  font-weight:700;  line-height:1.1;  Text-transform:uppercase;}

This is a use case:

. my-heading {  @extend%futura-heading;}

I've learned about the use of CSS custom properties before. Here is the specification of an ongoing @apply rule related to it. @apply allows you to store a series of properties and reference them in a selector. I used @apply to replace Sass's extend.

Back to Setup.css, I updated the properties of the Futura header:

: root {  ...  --franklin: {    font-family: ' Futura-pt ', Helvetica, Sans-serif;  };  --franklin-heading: {    @apply--franklin;    font-weight:700;    line-height:1.1;    Text-transform:uppercase;}  ;}

Here is an example:

. my-heading {  @apply--franklin-heading;}

@apply is not an inheritance. In the current Cssnext, the @apply copies the properties and values directly into each rule. It's a small project, so it's okay. However, in large projects, the style is redundant and the project is bloated. It is best to use generic class names for similar situations.

Now my website looks the same as before. The project page is an exception. It has different colors for each tile area. Next I'll explain how to write a style correctly and efficiently without sass.

Mixed macro with parameters

I use Sass's mixed macro to make it easier to write a project. This hybrid macro has a tile color parameter. Here is a hybrid macro for this project-block.

@mixin Project-block ($c) {  background-color: $c;  A {    color: $c;    &:hover {      background-color: $c;      Color: $offwhite);}}}  

Here is an example:

. p-jribbble {  @include project-block (#ff0066);}

While writing this article, I haven't found a feature in CSS that can simulate this feature. Custom properties Mate @apply is not a function, so we can't pass arguments to it. In the future, Custom selectors may allow parameters to be used. There is a complex example that looks promising in the draft specification. But I admit that I don't fully understand how it works right now.

It doesn't mean I'm unlucky. I write CSS longer than sass, but not for long. I also used another canonical feature in progress, matches selector.

Here is an example of a CSS instead of project-block mixed macros:

. p-jribbble,.p-jribbble a:matches (: hover,: Focus) {  Background-color:var (--COLOR-JRB);  & A {    color:var (--COLOR-JRB);  }}

The color variables are earlier in the file: the root scope is defined by the. Cssnext to compile the above CSS into:

. p-jribbble,.p-jribbble a:hover,.p-jribbble A:focus {  background-color: #ff0066}.p-jribbble a,.p-jribbble A: Hover A,.p-jribbble a:focus A {  color: #ff0066;}

Last two selectors ... a a:hover and ... a a:focus matches no element. They are not necessary. But they have no effect except for a few bits of space. For the readability of the code, I prefer to nest a selectors.

More POSTCSS Features

In order to style the regression, I decided to take advantage of more postcss plugins. I use CSS mqpacker to merge media queries that use the same query criteria. I also use Cssnano to optimize the code.

That's why I'm looking to use POSTCSS. I feel trapped in the current feature when I use sass. But because Postcss essence is a plug-in collection in the work, more extensibility. If I have special needs, I can write a plugin myself. Its potential is exciting.

I compromised.

After working with this new tool for a few days, I was completely put into it. It is very simple to move from sass to the new CSS syntax, and it was in the case that every project I wrote in the year five or six was written in sass.

I like the idea of change. Cssnext handles CSS much like Babel to JavaScript. They all allow you to write code using future features.


I've been using sass for years. But recently I wanted to use POSTCSS and its Cssnext plugin to try to work with styles. I love it. You can now use future CSS features, which are more handy than the tools I used earlier. My personal site is the best place to test for new features.

The first step is to list my sass usage. I need to know what features I've used, and I'm sure there are alternatives to the new features in Postcss. Here are the features I'm using in this project:

    • Partial reference (partial import)

    • Variable (variables)

    • Nesting (nesting)

    • Mixed macro (Mixins)

    • Outreach (Extend)

    • Placeholder class (placeholder classes)

    • Color function (darken and RGBA color functions)

    • Compression (compression)

Preparatory work

I need to do some preparation after switching to the new syntax. The directory structure of the project is now a typical use of sass. I use an underscore (_) to name the file, and the extension of the file is named Scss. I use two folders to organize Sass files. Moudules folder save Sass files that do not directly produce CSS , such as variables, placeholder classes, and mixed macros. Partials Save the Sass file that compiles the CSS.

This is the original file structure:

css/  scss/    modules/      _module.scss      ...    partials/      _partial.scss ...    Tylergaw.scss

Each SASS component is introduced in the TYLERGAW.SCSS.

@import "Modules/setup", @import "Modules/reset", @import "modules/fonts";

I re-organized and renamed the file. I first changed the suffix name of all files from Scss to CSS. I used a bash script to do the work, not a single change.

' for f in *.scss; Do git mv--"$f" "${f%.scss}.css"; Done; '

The preceding underline is the habit of writing sass so I've also removed it. I can't use bash commands to do it all at once, so you can only manually modify each one.

The final step is to move all the CSS files to the Modules folder and delete the Partials folder. I think it is easier to manage all CSS as a modules than to split them into moudules/partials.

Environment construction

I started with the Postcss CLI and added a temporary build script command to the Package.json:

"Scripts": {  "postcss": "Postcss-o public/css/tylergaw.css src/css/tylergaw.css"}

I compiled the CSS without changing any of the styles:

' NPM run Postcss '

Work properly. The console does not have an error, but there is no CSS style on the page.

The build process is available, and the task now is to get the style back.

I've seen a lot of 404 messages in the chrome console. This means that the first feature we lost was that the inline @import.tylergaw.css introduced the CSS module via @import. The browser sees these, Know what it's going to do. The browser loads each module with an HTTP request. My build process replicates only a single CSS file, not every module. Because of this, browsers cannot find them.

I can change the build process to make the default @import work, but that's inefficient. I need a sass style inline @import alternative.

First Plug-in

The Postcss-import plugin can replace the @import in Sass, and after installing via NPM, I updated the build script code:

"Scripts": {  "postcss": "Postcss-u postcss-import-o public/css/tylergaw.css Src/css/tylergaw.css"}

Running NPM run Postcss again, a single CSS file contains all the modules. The page now shows some of the styles.

Will this be the future of CSS?

It is very powerful to show the @import function of inline mode in sass. It allows us to organize styles better. I'm not sure if this feature will be natively supported in the future. When we use this feature, we always need to compile it in one step and not look bad.

I think the Postcss-import plugin will be a major configuration for my postcss, and it should be the same for everyone else. The following is a reference to the plugin author's view:

This plugin should probably is used as the first plugin of your list. This is, other plugins would work on the AST as if there were only a single file to process, and would probably work as you Can expect.

[Postcss-import]

Cssnext

Cssnext is a plugin in postcss that compiles future CSS features into today's supported features. In particular, it should be noted that It is not a different language than sass or less. It provides the features of the CSS specification in progress. Some features have been supported by browsers. Others are in the initial stages of the specification.

I use Cssnext to fill the gap left by the lost Sass character.

Browser private Prefix

I've known autoprefixer before I built this site. I used custom sass to add a hybrid macro to solve the problem of adding the required prefixes. Cssnext contains autoprefixer, so I can remove this entire mixed macro module.

Variable

Next I'll change the sass variable to a CSS custom property. For example, in _setup.scss, I write:

$grey: #1e1e1d; $yellow: #ffad15; $offwhite: #f8f8f8; $darkerwhite: Darken ($offwhite, 15);

This is not all the sass variables I use, but that's mostly it. The rest is in a separate module.

Note: The difference between a custom attribute and a variable. CSS custom properties are valid only in property values and cannot be used for selectors, property names, or media queries.

The new setup.css:

: root {  --white: #fff;  --grey: #1e1e1d;  --yellow: #ffad15;  --offwhite: #f8f8f8;  ...}

The following are examples of use:

A {  color:var (--yellow);}

In addition to the syntax, CSS custom properties and SASS variables work the same way. Custom attribute values still need to be compiled due to browser-supported restrictions. In the example above, the compiled value is color: #ffad15.

Color function

In the previous example, I omitted a variable: $darkerwhite: Darken ($offwhite, 15);. This is another SASS feature I need to look for alternative. Here is a draft specification that provides CSS color functions. Cssnex now contains these functions, which is very cool. Here is Setup.css, where Darkerwhite custom properties are implemented by color functions and shadow conditioners.

: root {  ...  --offwhite: #f8f8f8;  --darkerwhite:color (Var (--offwhite) Shade (20%));  ...}

The color function provides a number of regulators. You can use multiple regulators in one function:

' Background-color:color (#d32c3f shade (40%) alpha (40%)); '

The result of the compilation is:

' Background-color:rgba (127, 26, 38, 0.4); '

Again, Cssnext will now compile color () to a color value of 16 or RGBA. When the color function is supported by the browser, the compilation process is not necessary. The color operation can occur at run time.

Nesting

Nesting is an essential feature of the CSS preprocessor. Anything that makes a comfortable style tool necessary. Tab Atkins has an ongoing specification for CSS nesting, and Cssnext makes it a reality.

The nested syntax for CSS consists of a & that is placed before the inner layer, and the following is a sass fragment:

. projects-list {  ...  Li {    & > P {...}  }  A {    ...    &:hover,    &:focus {...}    &::after {...}  }  @media (min-width:640px) {...}}

For CSS nesting, I'll modify it to the following form:

. projects-list {  ...  & li {    & > P {...}  }  & A {    ...    &:hover,    &:focus {...}    &::after {...}  }  @media (min-width:640px) {...}}

Basic nesting requires pre-& pseudo-classes and selectors are the same in sass and CSS. Media queries do not require a predecessor &

It is also noteworthy that @nest. As mentioned in the documentation, complex nesting may require the introduction of @nest instead of & This project I have not used, perhaps in the future to be used.

Expansion and Placeholder classes

The @extend and placeholder classes in SASS are the two features that I often use. Here is an example of the style of the Futura head:

%futura {  font-family: ' Futura-pt ', Helvetica, Sans-serif;} %futura-heading {  @extend%futura;  font-weight:700;  line-height:1.1;  Text-transform:uppercase;}

This is a use case:

. my-heading {  @extend%futura-heading;}

I've learned about the use of CSS custom properties before. Here is the specification of an ongoing @apply rule related to it. @apply allows you to store a series of properties and reference them in a selector. I used @apply to replace Sass's extend.

Back to Setup.css, I updated the properties of the Futura header:

: root {  ...  --franklin: {    font-family: ' Futura-pt ', Helvetica, Sans-serif;  };  --franklin-heading: {    @apply--franklin;    font-weight:700;    line-height:1.1;    Text-transform:uppercase;}  ;}

Here is an example:

. my-heading {  @apply--franklin-heading;}

@apply is not an inheritance. In the current Cssnext, the @apply copies the properties and values directly into each rule. It's a small project, so it's okay. However, in large projects, the style is redundant and the project is bloated. It is best to use generic class names for similar situations.

Now my website looks the same as before. The project page is an exception. It has different colors for each tile area. Next I'll explain how to write a style correctly and efficiently without sass.

Mixed macro with parameters

I use Sass's mixed macro to make it easier to write a project. This hybrid macro has a tile color parameter. Here is a hybrid macro for this project-block.

@mixin Project-block ($c) {  background-color: $c;  A {    color: $c;    &:hover {      background-color: $c;      Color: $offwhite);}}}  

Here is an example:

. p-jribbble {  @include project-block (#ff0066);}

While writing this article, I haven't found a feature in CSS that can simulate this feature. Custom properties Mate @apply is not a function, so we can't pass arguments to it. In the future, Custom selectors may allow parameters to be used. There is a complex example that looks promising in the draft specification. But I admit that I don't fully understand how it works right now.

It doesn't mean I'm unlucky. I write CSS longer than sass, but not for long. I also used another canonical feature in progress, matches selector.

Here is an example of a CSS instead of project-block mixed macros:

. p-jribbble,.p-jribbble a:matches (: hover,: Focus) {  Background-color:var (--COLOR-JRB);  & A {    color:var (--COLOR-JRB);  }}

The color variables are earlier in the file: the root scope is defined by the. Cssnext to compile the above CSS into:

. p-jribbble,.p-jribbble a:hover,.p-jribbble A:focus {  background-color: #ff0066}.p-jribbble a,.p-jribbble A: Hover A,.p-jribbble a:focus A {  color: #ff0066;}

Last two selectors ... a a:hover and ... a a:focus matches no element. They are not necessary. But they have no effect except for a few bits of space. For the readability of the code, I prefer to nest a selectors.

More POSTCSS Features

In order to style the regression, I decided to take advantage of more postcss plugins. I use CSS mqpacker to merge media queries that use the same query criteria. I also use Cssnano to optimize the code.

That's why I'm looking to use POSTCSS. I feel trapped in the current feature when I use sass. But because Postcss essence is a plug-in collection in the work, more extensibility. If I have special needs, I can write a plugin myself. Its potential is exciting.

I compromised.

After working with this new tool for a few days, I was completely put into it. It is very simple to move from sass to the new CSS syntax, and it was in the case that every project I wrote in the year five or six was written in sass.

I like the idea of change. Cssnext handles CSS much like Babel to JavaScript. They all allow you to write code using future features.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.