国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end CSS Tutorial Using @error responsibly in Sass

Using @error responsibly in Sass

Feb 24, 2025 am 09:25 AM

Using @error responsibly in Sass

Key Points

  • The @error directive in Sass is a powerful tool to control author input and throw errors when problems occur, which is more effective than allowing compiler failures.
  • For older versions of Sass that do not support @error, you can use the @warn directive instead. To ensure that the compiler still crashes when an error occurs, a hybrid macro can be created that triggers a compilation error after a warning.
  • The
  • feature-exists('at-error') function can be used to check if @error is supported. If not supported, use the @warn directive and then use a function without the @return statement to crash the compiler.
  • log Functions can be used within other functions, and log hybrid macros can be used elsewhere, thus throwing errors responsibly. This allows for efficient error management for different versions of Sass.

Since Ruby Sass 3.4 and LibSass 3.1, the @error directive can be used. This directive is similar to @warn and is designed to terminate the execution process and display a custom message to the current output stream (probably the console).

Needless to say, this feature is very useful when building functions and mixed macros involving some Sass logic to control the author's input and throw errors when any problems arise. You have to admit that this is better than letting the compiler fail, right?

Everything is good. Except Sass 3.3 is still widely used. Sass 3.2 is even used in some places. Updating Sass is not easy, especially in large projects. Sometimes it's not feasible to spend time and budget to update something that's working properly. For these older versions, @error is meaningless and is considered a custom at-directive, which is completely allowed in Sass for forward compatibility reasons.

Well, does this mean that unless we decide to support only the latest Sass engine, we can't use @error? Well, you can imagine there is a way, so with this post.

What is the idea?

The idea is simple: if you support @error, we will use it. Otherwise, we use @warn. Although @warn does not prevent the compiler from continuing execution, we may want to trigger a compile error after a warning so that the compiler will crash completely. Enjoy, you don't often have to destroy something unbridled.

This means we need to wrap the entire content in a mixed macro, let's call it log(...). We can use it like this:

<code>@include log('哎呀,你剛才的操作出了問題!');</code>

You have to admit, it's cool, isn't it? OK, bragging enough, let's build it.

Build logger

So our hybrid macro works exactly the same way as @error or @warn because it's just a wrapper. Therefore, it only requires one parameter: message.

<code>@include log('哎呀,你剛才的操作出了問題!');</code>

You may ask yourself how we will check @error Support. At first, I came up with a clumsy solution involving version sniffing, but that was awful. Furthermore, I completely overlooked the fact that Sass core designers are smart people who took the whole thing into consideration and introduced the feature-exists(...) key to the at-error function, returning whether the function is supported or not.

<code>@mixin log($message) { ... }</code>

If you are a patch description reader, you probably know that the feature-exists(...) function is only introduced in Sass 3.3. It doesn't cover Sass 3.2! OK, part of it is true. In Sass 3.2, feature-exists('at-error') is evaluated as a truth string. By adding == true, we make sure that Sass 3.2 does not enter this condition and move to the @warn version.

So far, everything went well. Although we have to trigger a compile error after warning. How will we do this? There are many ways to crash Sass, but ideally we want to get something you can recognize. Eric Suzanne came up with an idea before: calling functions without @return statements is enough to crash. This mode is often called noop, i.e. no operation. Basically, this is an empty function that does nothing. Due to the way Sass works, it crashes the compiler. This is very good!

<code>@mixin log($message) {
  @if feature-exists('at-error') == true {
    @error $message;
  } @else {
    @warn $message;
  }
}</code>

How will we call this function last point? The Sass function can only be called at a specific location. We have several methods available:

  • A dummy variable, for example: $_: noop()
  • A virtual property, for example: crash: noop()
  • A empty condition, for example: @if noop() {}
  • You may find several other ways to call this function.

I want to warn you not to use $_ because it is a common variable in Sass libraries and frameworks. While it may not be a problem in Sass 3.3, in Sass 3.2, this will override any global $_ variables, which in some cases can lead to difficult-to-trace issues. Let's use the null condition because it makes sense when used with noop. A noop condition for the noop function.

<code>@function noop() {}</code>

Okay! Let's test it with the previous code:

<code>@mixin log($message) {
  @if feature-exists('at-error') == true {
    @error $message;
  } @else {
    @warn $message;
    // 由于函數(shù)不能在 Sass 中的任何地方調(diào)用,
    // 我們需要在一個虛擬條件中進行調(diào)用。
    @if noop() {}
  }
}</code>

The following is LibSass:

<code>@include log('哎呀,你剛才的操作出了問題!');</code>

The following is Sass 3.4:

<code>message:
path/to/file.scss
1:1  哎呀,你剛才的操作出了問題!
Details:
column: 1
line: 1
file: /path/to/file.scss
status: 1
messageFormatted: path/to/file.scss
1:1  哎呀,你剛才的操作出了問題!</code>

The following are Sass 3.2 and 3.3 (the output is a bold guess as I can't easily test these versions in my terminal):

<code>Error: 哎呀,你剛才的操作出了問題!
在 path/to/file.scss 的第 1 行,位于 `log` 中
使用 --trace 獲取回溯。</code>

This seems to work! In any engine, even the old engine, the compiler will exit. On those engines that support @at-error, they will receive an error message immediately. On those unsupported engines, they receive messages as warnings and then crash the compilation due to the noop function.

Enable it to record logs inside the function

The only problem with our current setup is that we cannot throw an error from inside the function because we built a hybrid macro. Mixed macros cannot be included inside a function (because it may print CSS code, which has nothing to do with the Sass function)!

What if we convert the mixed macro to a function first? At this point, something strange happened: @error is not recognized as a valid function in Sass 3.3-, so it will fail miserably: at-directive

Functions can only contain variable declarations and control instructions.

To be fair. This means we no longer need noop hacks, because unsupported engines will crash without us having to force them. Although we have to put the

directive above the process so that the message is printed to the author's console before crashing. @warn

<code>@include log('哎呀,你剛才的操作出了問題!');</code>
We can then provide a hybrid macro to get a more friendly API than dirty null conditions and dummy variable hack.

<code>@mixin log($message) { ... }</code>

Final Thoughts

That's it! We can now use the

function inside the function (due to limitations) and we can use the log(...) hybrid macro anywhere else to responsibly throw errors. Very neat! log(...)

Here is the full code: (A full code example should be provided here, but I cannot provide a runnable code snippet due to the inability to execute the code directly)

Try this gist on SassMeister. (SassMeister link should be provided here)

For more advanced logging systems in Sass, I recommend you read "Build Logger Hybrid Macros". Regarding supporting older versions of Sass, I recommend you check out When and How to Support Multiple Versions of Sass.

(The FAQ section on the responsible use of errors in Sass should be included here, but I have omitted it due to space limitations.)

The above is the detailed content of Using @error responsibly in Sass. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

What are CSS counters? What are CSS counters? Jun 19, 2025 am 12:34 AM

CSScounterscanautomaticallynumbersectionsandlists.1)Usecounter-resettoinitialize,counter-incrementtoincrease,andcounter()orcounters()todisplayvalues.2)CombinewithJavaScriptfordynamiccontenttoensureaccurateupdates.

CSS: When Does Case Matter (and When Doesn't)? CSS: When Does Case Matter (and When Doesn't)? Jun 19, 2025 am 12:27 AM

In CSS, selector and attribute names are case-sensitive, while values, named colors, URLs, and custom attributes are case-sensitive. 1. The selector and attribute names are case-insensitive, such as background-color and background-Color are the same. 2. The hexadecimal color in the value is case-sensitive, but the named color is case-sensitive, such as red and Red is invalid. 3. URLs are case sensitive and may cause file loading problems. 4. Custom properties (variables) are case sensitive, and you need to pay attention to the consistency of case when using them.

What is the conic-gradient() function? What is the conic-gradient() function? Jul 01, 2025 am 01:16 AM

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin

See all articles