Lawrence  Lesch

Lawrence Lesch

1664370906

JavaScript, SCSS Helpers for Rendering High-resolution Image Variants

retina.js

JavaScript, Sass, Less, and Stylus helpers for rendering high-resolution image variants

retina.js makes it easy to serve high-resolution images to devices with displays that support them. You can prepare images for as many levels of pixel density as you want and let retina.js dynamically serve the right image to the user.

How it works

There are 4 ways to use retina.js:

  1. Automatically swapping out src paths on img tags.
  2. Automatically swapping out background image URLs in inline styles.
  3. Manually specifying the location of a high-res image variant (works for src attributes and inline styles).
  4. Automatically creating media queries for CSS background images.

Img Tags

retina.js assumes you are using Apple's prescribed high-resolution modifiers (@2x, @3x, etc) to denote high-res image variants on your server. It also assumes that if you have prepared a variant for a given high-res environment, that you have also prepared variants for each environment below it. For example, if you have prepared 3x variants, retina.js will assume that you have also prepared 2x variants.

With this in mind, you'll specify your highest environment level with the data-rjs attribute and let retina.js take it from there.

Let's say you have an image on your page that looks like this:

<img src="/images/my_image.png" data-rjs="3" />

In this case, we've set our resolution cap at "3", denoting that we've prepared 3x and 2x image variants. When the page loads, retina.js will check the actual resolution of the device environment to decide whether it should really serve up a 3x image. If the user happens to be in a 2x environment, retina.js will serve up the 2x image instead, assuming it will find the image at /images/my_image@2x.png.

If the environment does have 3x capabilities, retina.js will serve up the 3x image. It will expect that url to be /images/my_image@3x.png. If the environment has the ability to display images at higher densities than 3x, retina.js will serve up the image of the highest resolution that you've provided, in this case 3x.

Inline Styles

Previous versions of retina.js were unable to target background images set via inline styles. Now, if you apply a data-rjs attribute to any kind of element other than an img, the script will target inline background images instead of src attributes.

So if you created an element like this:

<div style="background: url(/images/my_image.png)" data-rjs="3"></div>

retina.js would convert it to something like this:

<div style="background: url(/images/my_image@3x.png)" data-rjs="3"></div>

The logic behind image swapping is exactly the same when dealing with background images as it is when dealing with src attributes. If the user's environment only supports 2x variants, retina.js will load the 2x variant instead of the 3x.

Note that it is up to you in a case like this to correctly apply background sizing and any other necessary background-related styles to the element. retina.js will not affect these.

Manually Specifying a High-Res URL

In previous versions, you could tell the script where to find your high-res file by using the data-at2x attribute. Now, if you pass a URL to the data-rjs attribute, retina.js will use the image at the path you specify for all high-resolution environments instead of trying to dynamically serve an auto-suffixed image path based on the environment's capabilities. This will work for both src attributes on img tags and inline background images on all other tags.

For example, you might write something like this:

<img
  src="/images/my_image.png"
  data-rjs="/images/2x/my-image.png" />

<!-- or -->

<div
  style="background: url(/images/my_image.png)"
  data-rjs="/images/2x/my-image.png">
</div>

If the user then loads the page in any kind of high-resolution environment, they'll get the following:

<img
  src="/images/2x/my-image.png"
  data-rjs="/images/2x/my-image.png" />

<!-- or -->

<div
  style="background: url(/images/2x/my-image.png)"
  data-rjs="/images/2x/my-image.png">
</div>

Media Queries

retina.js comes with mixins for SCSS, Sass, Less, and Stylus. These mixins work similarly to the JavaScript version in that they will dynamically serve images for as many high-res environments as you've prepared image variants for. Previously, these mixins were named "at2x" but because they now serve images for multiple environments, they have been renamed "retina".

In each language, the retina mixin allows 4 parameters:

  1. path - The path to your standard resolution image.
  2. cap - Optional. The highest resolution level for which you have prepared images. Defaults to 2.
  3. size- Optional. A value to be applied to the background-size property. Defaults to auto auto.
  4. extras- Optional. Any other values to be added to the background property. Defaults to nothing.

Here is an example wherein we are specifying that we have prepared images for both 2x and 3x environments:

SCSS

#item {
  @include retina('/images/my_image.png', 3, cover, center center no-repeat);
}

Sass

#item
  +retina('/images/my_image.png', 3, cover, center center no-repeat)

Less

#item {
  .retina('/images/my_image.png', 3, cover, center center no-repeat);
}

Stylus

#item
  retina('/images/my_image.png', 3, cover, center center no-repeat)

Regardless of the dialect, the output is effectively the same:

#item {
  background: url("/images/my_image.png") center center no-repeat;
  background-size: cover;
}

@media all and (-webkit-min-device-pixel-ratio: 1.5),
       all and (-o-min-device-pixel-ratio: 3 / 2),
       all and (min--moz-device-pixel-ratio: 1.5),
       all and (min-device-pixel-ratio: 1.5) {
  #item {
    background: url("/images/my_image@2x.png") center center no-repeat;
    background-size: cover;
  }
}

@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  #item {
    background: url("/images/my_image@2x.png") center center no-repeat;
    background-size: cover;
  }
}

@media (-webkit-min-device-pixel-ratio: 3), (min-resolution: 288dpi) {
  #item {
    background: url("/images/my_image@3x.png") center center no-repeat;
    background-size: cover;
  }
}

Compatibility

retina.js is compatible with all modern browsers and should not throw errors in old browsers all the way back through IE6.

Installing & Launching

JavaScript

There are 2 ways to use the JavaScript version of retina.js:

  1. The old-school way (manually dropping the script into an html file).
  2. The new-school way (importing it into a larger JavaScript build process).

Old-School

To use retina.js the old-school way, download retina.min.js and put it on your server. Then, include the script in your html file at the bottom of your template, before your closing </body> tag.

<script type="text/javascript" src="/scripts/retina.min.js"></script>

Using this technique, retina.js will run automatically on page load. It will also create a globally available function called retinajs. Whenever you'd like to manually re-initialize the script, simply call window.retinajs().

If you don't pass any arguments to the retinajs function, it will only attempt to process images that have not previously been processed by the script. Optionally, you can pass a collection of HTML elements to the script, in which case it will only attempt to process elements in that collection, specifically the ones that have not been processed before. Your collection may take the form of an Array, NodeList, or jQuery selection.

retinajs();
// Finds all images not previously processed and processes them.

retinajs( [img, img, img] );
// Only attempts to process the images in the collection.

retinajs( $('img') );
// Same.

retinajs( document.querySelectorAll('img') );
// Same.

New-School

To use retina.js the new-school way, you'll want to require it (or import it if you're using ES6) into your Gulp/Webpack/Grunt/CommonJS/etc application. In this case, the script won't run automatically. Instead, it'll let you determine when you'd like it to run.

import retina from 'retina';

window.addEventListener('load', retina);

Notice that the retina function can be called as often as you need in order to re-initialize the image swapping.

If you don't pass any arguments to the retina function, it will only attempt to process images that have not previously been processed by the script. Optionally, you can pass a collection of HTML elements to the script, in which case it will only attempt to process elements in that collection, specifically the ones that have not been processed before. Your collection may take the form of an Array, NodeList, or jQuery selection.

retina();
// Finds all images not previously processed and processes them.

retina( [img, img, img] );
// Only attempts to process the images in the collection.

retina( $('img') );
// Same.

retina( document.querySelectorAll('img') );
// Same.

CSS Preprocessors

The process for including the CSS mixins is relatively straightforward. Here is a breakdown for each:

SCSS

Add the @mixin retina( ... ) mixin from _retina.scss to your SCSS stylesheet (or reference it in an @import). In your stylesheet, call the mixin using @include retina( ... ) anywhere instead of using background or background-image.

Sass

Add the =retina( ... ) mixin from _retina.sass to your Sass stylesheet (or reference it in an @import). In your stylesheet, call the mixin using +retina( ... ) anywhere instead of using background or background-image.

Less

Add the .retina( ... ) mixin from retina.less to your Less stylesheet (or reference it in an @import). In your stylesheet, call the mixin using .retina( ... ) anywhere instead of using background or background-image.

Stylus

Add the retina( ... ) mixin from retina.styl to your Stylus stylesheet (or reference it in an @import). In your stylesheet, call the mixin using retina( ... ) anywhere instead of using background or background-image.

Considerations for Ruby on Rails 3+

...or any framework that embeds some digest/hash to the asset URLs based on the contents, e.g. /images/image-{hash1}.jpg.

The problem with this is that the high-resolution version would have a different hash, and would not conform to the usual pattern, i.e. /images/image@2x-{hash2}.jpg. So automatic detection would fail because retina.js would check the existence of /images/image-{hash1}@2x.jpg.

There's no way for retina.js to know beforehand what the high-resolution image's hash would be without some sort of help from the server side. So in this case, there are a couple of options for handling it:

Bypass Digesting

One potential method is to bypass digesting altogether by implementing a process like team-umlaut's asset compile rake file which will generate non-digested asset files as necessary.

Use Manual Paths

Although it's not quite as fancy as dynamically serving up files based on the resolution of the user's environment, this may be a good time to pass a URL string to the data-rjs attribute so that you can manually tell retina.js exactly where to look for a high-resolution variant of your image.

Download Details:

Author: Strues
Source Code: https://github.com/strues/retinajs 
License: MIT license

#javascript #scss #sass #image 

JavaScript, SCSS Helpers for Rendering High-resolution Image Variants
Dominic  Feeney

Dominic Feeney

1662773640

3 Static Analysis Tools & Linters for SCSS and SASS

Lint, or a linter, is a static code analysis tool used to flag programming errors, bugs, stylistic errors and suspicious constructs

What is SASS?

SASS is short for Syntactically Awesome Style Sheets, and it is among the most popular CSS preprocessors. It extends CSS by adding features of traditional programming languages, particularly object-oriented programming languages.

Designed by Hampton Catlin, SASS was developed by Chris Eppstein and Natalie Weizenbaum and released in 2006. It uses SassScript, which is a dynamically-typed scripting language.

Originally SASS was written in Ruby, and it was required to have Ruby installed on the system where SASS is to be used. But with the decreasing popularity of Ruby, it became obsolete in March 2019. Then came Dart Sass and LibSass. Both are easy to install, fast, and available on npm.

While Dart Sass is a Sass implementation in Dart, LibSass is the Sass implementation in C and C++. However, LibSass is now deprecated and thus, the use of Dart Sass is promoted. If you wish to use Sass on a JS-based system then you need to integrate Dart Sass as a JS library.

Key Features of SASS

SASS offers a galore of features that make it a better tool than CSS for developers. Some of its major highlights are:

  • Compatibility with CSS: One of the major features of SASS is its high compatibility with cascading style sheets, which means SASS provides support for many versions of CSS. Irrespective of the CSS version, Sass is compatible with them all. It allows developers to use any CSS library with Sass easily.
  • Multi-featured: Compared to other popular CSS preprocessors, SASS brings a plethora of features to the table, including interpolation, partials and importing, control directives, nesting, etc. These features make it more productive for developers to use SASS instead of CSS.
  • Mature and Backed by a Huge Community: Sass was first released in 2006 and since then it has been actively developed by its core team that includes many big tech organizations and independent developers. You can find so many resources to make working with SASS even better.

    The core team that is responsible for developing SASS comprises tech giants from around the world as well as professional developers. Other independent members of the community are busy developing complementary tools for making working with SASS more productive.
  • Industry-Standard: SASS is not just loved by individual developers and hobbyists but it is also a preferred CSS extension language by organizations to develop complex web projects. SASS is used for developing commercial-grade web applications.
  • Tools and Frameworks: There are several CSS frameworks that are developed using SASS. Bourbon and Compass are examples of such frameworks. Also, there are a galore of tools developed using SASS.

What is SCSS?

SASS consists of two syntaxes. The older one is called the indented syntax and is similar to Haml, which is a templating system aimed at generating clean HTML code by avoiding writing inline code in a web document.

The other syntax, the newer SASS syntax, is SCSS or Sassy CSS. Unlike the indented syntax, it uses CSS-like block formatting. While braces denote code blocks, semicolons separate rules with a code block. This makes the SCSS syntax strict but at the same time more expressive in terms of readability. SCSS is built on top of CSS and contains more features in addition to all the features of CSS. Thus, SCSS is a superset of CSS. The main aim of SCSS is to fill the gaps and incompatibilities between CSS and SASS.

Key Features of SCSS

SCSS is just a different syntax for using SASS. Hence, it shares most of its features with SASS. However, a few features that give it an edge over SASS are:

  • SCSS syntax is a superset of CSS syntax. Therefore, anything you can do with CSS, you can do with SCSS. This is not the case with SASS.
  • It allows inline documentation, i.e., you can add comments alongside the code in SCSS.
  • It can handle many classes and nested styles.
  • SCSS gives you more control over the code as its syntax is more expressive.

In this article below, We'll share 3 Static Analysis Tools & Linters for SCSS and SASS

1.   sass-lint

A Node-only Sass linter for both sass and scss syntax!

Install

You can get sass-lint from NPM:

Install globally

npm install -g sass-lint

To save to a project as a dev dependency

npm install sass-lint --save-dev

Configuring

Sass-lint can be configured from a .sass-lint.yml or .sasslintrc file in your project. The .sasslintrc file can be in either JSON format or YAML. Both formats are interchangeable easily using tools such as json2yaml. If you don't either file in the root of your project or you would like all your projects to follow a standard config file then you can specify the path to one in your project's package.json file with the sasslintConfig option.

For example:

{
  "name": "my-project",
  "version": "1.0.0",
  "sasslintConfig": "PATH/TO/YOUR/CONFIG/FILE"
}

Use the Sample Config (YAML) or Sample Config (JSON) as a guide to create your own config file. The default configuration can be found here.

Configuration Documentation

Migrating from SCSS-Lint: If you already have a config for SCSS-Lint, you can instantly convert it to the equivalent Sass Lint config at sasstools.github.io/make-sass-lint-config.

Options

The following are options that you can use to config the Sass Linter.

  • cache-config - Allows you to cache your config for a small speed boost when not changing the contents of your config file
  • config-file - Specify another config file to load
  • cwd - Specify a directory to treat as the current working directory - formatters only for now
  • formatter - Choose the format for any warnings/errors to be displayed
  • merge-default-rules - Allows you to merge your rules with the default config file included with sass-lint
  • output-file - Choose to write the linters output to a file

Files

The files option contains two properties, include and ignore. Both can be set to either a glob or an array of glob strings/file paths depending on your projects' needs and setup.

For example below we are providing a singular glob string to our include property and an array of patterns to our ignore property:

files:
  include: 'sass/**/*.s+(a|c)ss'
  ignore:
    - 'sass/vendor/**/*.scss'
    - 'sass/tests/**/*.scss'

As mentioned you can also provide an array to the include property like so

files:
  include:
    - 'sass/blocks/*.s+(a|c)ss'
    - 'sass/elements/*.s+(a|c)ss'
  ignore:
    - 'sass/vendor/**/*.scss'
    - 'sass/tests/**/*.scss'

Rules

For all rules, setting their severity to 0 turns it off, setting to 1 sets it as a warning (something that should not be committed in), and setting to 2 sets it to an error (something that should not be written). If a rule is set to just a severity, it will use the default configuration (where available).

If you want to configure options, set the rule to an array, where the first item in the array is the severity, and the second item in the array is an object including the options you would like to set.

Here is an example configuration of a rule, where we are specifying that breaking the indentation rule should be treated as an error (its severity set to two), and setting the size option of the rule to 2 spaces:

rules:
  indentation:
    - 2
    -
      size: 2

View Github

2.   scss-lint

scss-lint is a tool to help keep your SCSS files clean and readable by running it against a collection of configurable linter rules. You can run it manually from the command line, or integrate it into your SCM hooks.

Installation

gem install scss_lint

...or add the following to your Gemfile and run bundle install:

gem 'scss_lint', require: false

The require: false is necessary because scss-lint monkey patches Sass in order to properly traverse the parse tree created by the Sass parser. This can interfere with other applications that invoke the Sass parser after scss-lint libraries have been loaded at runtime, so you should only require it in the context in which you are linting, nowhere else.

Usage

Run scss-lint from the command line by passing in a directory (or multiple directories) to recursively scan:

scss-lint app/assets/stylesheets/

You can also specify a list of files explicitly:

scss-lint app/assets/stylesheets/**/*.css.scss

...or you can lint a file passed via standard input (note the --stdin-file-path flag is required when passing via standard input):

cat some-file | scss-lint --stdin-file-path=path/to/treat/stdin/as/having.scss

scss-lint will output any problems with your SCSS, including the offending filename and line number (if available).

Command Line FlagDescription
-c/--configSpecify a configuration file to use
-e/--excludeExclude one or more files from being linted
-f/--formatOutput format (see Formatters)
-o/--outWrite output to a file instead of STDOUT
-r/--requireRequire file/library (mind $LOAD_PATH, uses Kernel.require)
-i/--include-linterSpecify which linters you specifically want to run
-x/--exclude-linterSpecify which linters you don't want to run
--stdin-file-pathWhen linting a file passed via standard input, treat it as having the specified path to apply the appropriate configuration
--[no-]colorWhether to output in color
-h/--helpShow command line flag documentation
--show-formattersShow all available formatters
--show-lintersShow all available linters
-v/--versionShow version

When running scss-lint with JRuby, using JRuby's --dev flag will probably improve performance.

View Github

3.   stylelint

A mighty, modern linter that helps you avoid errors and enforce conventions in your styles.

Features

It's mighty as it:

  • has over 170 built-in rules for modern CSS syntax and features
  • supports plugins so you can create your own rules
  • automatically fixes problems where possible
  • is well tested with over 15000 unit tests
  • supports shareable configs that you can extend or create
  • is unopinionated so that you can customize it to your exact needs
  • complements pretty printers like Prettier
  • has a growing community and is used by Google, GitHub and WordPress

And can be extended to:

  • parse CSS-like syntaxes like SCSS, Sass, Less and SugarSS
  • extract embedded styles from HTML, Markdown and CSS-in-JS object & template literals

How it'll help you

It'll help you avoid errors, for example styles that are:

  • invalid, e.g. malformed hex colors and named grid areas
  • valid but with unintended consequences, e.g. duplicated selectors and overridden properties

And enforce conventions, for example:

  • what units, functions, at-rules etc are allowed
  • consistent patterns for selector names, at-rule names, custom properties etc
  • maximum specificity or maximum quantity of each selector type
  • your preferred notation for color functions, font weight etc

There are also rules for enforcing stylistic consistency, but we now recommend you use Stylelint alongside a pretty printer like Prettier. Linters and pretty printers are complementary tools that work together.

Usage examples

We recommend you lint your CSS before applying any transformations. You can do this by either:

  • creating a separate lint task that is independent of your build one.
  • using the plugins option of postcss-import or postcss-easy-import to lint your files before any transformations.
  • placing Stylelint at the beginning of your plugin pipeline.

You'll also need to use a reporter. The Stylelint plugin registers warnings via PostCSS. Therefore, you'll want to use it with a PostCSS runner that prints warnings or another PostCSS plugin whose purpose is to format and print warnings (e.g. postcss-reporter).

Example A

A separate lint task that uses the plugin via the PostCSS JS API to lint Less using postcss-less.

const fs = require("fs");
const less = require("postcss-less");
const postcss = require("postcss");

// Code to be processed
const code = fs.readFileSync("input.less", "utf8");

postcss([
  require("stylelint")({
    /* your options */
  }),
  require("postcss-reporter")({ clearReportedMessages: true })
])
  .process(code, {
    from: "input.less",
    syntax: less
  })
  .then(() => {})
  .catch((err) => console.error(err.stack));

The same pattern can be used to lint Less, SCSS or SugarSS syntax.

Example B

A combined lint and build task where the plugin is used via the PostCSS JS API, but within postcss-import (using the its plugins option) so that the source files are linted before any transformations.

const fs = require("fs");
const postcss = require("postcss");
const stylelint = require("stylelint");

// CSS to be processed
const css = fs.readFileSync("lib/app.css", "utf8");

postcss([
  require("postcss-import")({
    plugins: [
      require("stylelint")({
        /* your options */
      })
    ]
  }),
  require("postcss-preset-env"),
  require("postcss-reporter")({ clearReportedMessages: true })
])
  .process(css, {
    from: "lib/app.css",
    to: "app.css"
  })
  .then((result) => {
    fs.writeFileSync("app.css", result.css);

    if (result.map) {
      fs.writeFileSync("app.css.map", result.map);
    }
  })
  .catch((err) => console.error(err.stack));

View Github

Here are all 3 Static Analysis Tools & Linters for SCSS and SASS for Developers in my opinion. If you find it interesting, please like and share to support.

#sass #scss #analysistool

3 Static Analysis Tools & Linters for SCSS and SASS
Lawrence  Lesch

Lawrence Lesch

1662440880

Postcss-scss: SCSS Parser for PostCSS

PostCSS SCSS Syntax

A SCSS parser for PostCSS.

This module does not compile SCSS. It simply parses mixins as custom at-rules & variables as properties, so that PostCSS plugins can then transform SCSS source code alongside CSS.

Install

npm --save install postcss postcss-scss

Usage

There are two ways to use this parser:

1. SCSS Transformations

The main use case of this plugin is to apply PostCSS transformations directly to SCSS source code.

For example, you can lint SCSS source with Stylelint and linter will automatically fix issues in the source.

// postcss.config.js
module.exports = {
  syntax: 'postcss-scss',
  plugins: {
    …
  }
}

2. Inline Comments for PostCSS

Also you can use this parser just to add // single-line comment to your PostCSS project (without any Sass):

:root {
    // Main theme color
    --color: red;
}

Note that you don’t need a special stringifier to handle the output; the default one will automatically convert single line comments into block comments.

// postcss.config.js
module.exports = {
  parser: 'postcss-scss',
  plugins: {
    …
  }
}

If you want Sass behaviour with removing inline comments, you can use postcss-strip-inline-comments plugin.

Security Contact

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

Download Details:

Author: Postcss
Source Code: https://github.com/postcss/postcss-scss 
License: MIT license

#javascript #scss 

Postcss-scss: SCSS Parser for PostCSS
Joseph  Murray

Joseph Murray

1662032700

A Svelte Boilerplate to Kick-start New Project with SCSS & Bootstrap

My Svelte Boilerplate

Svelte boilerplate to kick-start new project with SCSS + Bootstrap

Requirement

Get started

# activate the yarn package manager
corepack enable

# install npm packages
yarn install

# watch and serve a dev server at http://localhost:8080/
yarn start

# Running unit tests
yarn test

# build the project in production mode. The build artifacts will be stored in the `public/build/` directory
yarn build

# extracts i18n messages from source code
yarn i18n:extract src/locales/zh-Hant.json

Reference

Download details:

Author: akunzai
Source code: https://github.com/akunzai/svelte-boilerplate 
License: MIT license

#svelte #javascript #scss

A Svelte Boilerplate to Kick-start New Project with SCSS & Bootstrap

NextJS Material Kit: A Free Material-UI Kit with A Fresh, New Design

NextJS Material Kit  

NextJS Material Kit is a Free Material-UI Kit with a fresh, new design inspired by Google's material design and is was developed using NextJS, starting from this starter project by Material-UI and Material Kit React by Creative Tim. You asked for it, so we built it. It's a great pleasure to introduce to you the material concepts in an easy to use and beautiful set of components. Along with the restyling of the Material-UI elements, you will find three fully-coded example pages, to help you design your NextJS project.

NextJS Material Kit makes use of light, surface and movement. It uses a deliberate color choice, edge-to-edge imagery and large scale typography. The general layout resembles sheets of paper following multiple different layers, so that the depth and order is obvious. The navigation stays mainly on the left and the actions on the right.

This new design has elements that have been the result of research regarding ink and paper and the way objects and materials interact in real life. The result is a beautiful and consistent set of elements that can get you started with your next project. NextJS Material Kit is a great tool if you are looking to create a web presence for your web application and need to be consistent, leaving the impression of visually similar elements. It is also a great resource in its own right, looking gorgeous and helping you build your web pages.

NextJS Material Kit was built with the help of nextjs and it uses a framework built by our friends from Material-UI, who did an amazing job creating the backbone for the material effects, animations, ripples and transitions. Big thanks to this team for the effort and forward thinking they put into it.

Table of Contents

  • Versions
  • Demo
  • Quick Start
  • Documentation
  • File Structure
  • Browser Support
  • Resources
  • Reporting Issues
  • Licensing
  • Useful Links

Versions

React NativeFigmaWordPressNextJS
Material Kit React NativeMaterial Kit FigmaMaterial Kit WordPressNextJS Material Kit
HTMLReactVue
Material Kit  HTMLMaterial Kit ReactVue Material Kit

Demo

ButtonsInputsNavbars
ButtonsInputsNavbar
Login PageLanding PageProfile Page
Login PageLanding PageProfile Page

View More

Quick start

Documentation

The documentation for the NextJS Material Kit is hosted at our website.

File Structure

Within the download you'll find the following directories and files:

nextjs-material-kit
.
├── CHANGELOG.md
├── ISSUE_TEMPLATE.md
├── LICENSE.md
├── README.md
├── next.config.js
├── package.json
├── Documentation
│   ├── assets
│   └── tutorial-components.html
├── assets
│   ├── css
│   ├── img
│   │   ├── examples
│   │   └── faces
│   ├── jss
│   │   ├── nextjs-material-kit
│   │   │   ├── components
│   │   │   └── pages
│   │   │       ├── componentsSections
│   │   │       └── landingPageSections
│   │   └── nextjs-material-kit.js
│   └── scss
│       ├── core
│       │   ├── mixins
│       │   └── variables
│       ├── plugins
│       └── nextjs-material-kit.scss
├── pages
│   ├── _app.js
│   ├── _document.js
│   ├── _error.js
│   ├── components.js
│   ├── index.js
│   ├── landingpage.js
│   ├── loginpage.js
│   └── profilepage.js
├── components
│   ├── Badge
│   │   └── Badge.js
│   ├── Card
│   │   ├── Card.js
│   │   ├── CardBody.js
│   │   ├── CardFooter.js
│   │   └── CardHeader.js
│   ├── Clearfix
│   │   └── Clearfix.js
│   ├── CustomButtons
│   │   └── Button.js
│   ├── CustomDropdown
│   │   └── CustomDropdown.js
│   ├── CustomInput
│   │   └── CustomInput.js
│   ├── CustomLinearProgress
│   │   └── CustomLinearProgress.js
│   ├── CustomTabs
│   │   └── CustomTabs.js
│   ├── Footer
│   │   └── Footer.js
│   ├── Grid
│   │   ├── GridContainer.js
│   │   └── GridItem.js
│   ├── Header
│   │   ├── Header.js
│   │   └── HeaderLinks.js
│   ├── InfoArea
│   │   └── InfoArea.js
│   ├── NavPills
│   │   └── NavPills.js
│   ├── PageChange
│   │   └── PageChange.js
│   ├── Pagination
│   │   └── Pagination.js
│   ├── Parallax
│   │   └── Parallax.js
│   ├── Snackbar
│   │   └── SnackbarContent.js
│   └── Typography
│       ├── Danger.js
│       ├── Info.js
│       ├── Muted.js
│       ├── Primary.js
│       ├── Quote.js
│       ├── Small.js
│       ├── Success.js
│       └── Warning.js
└── pages-sections
    ├── Components-Sections
    │   ├── SectionBasics.js
    │   ├── SectionCarousel.js
    │   ├── SectionCompletedExamples.js
    │   ├── SectionDownload.js
    │   ├── SectionExamples.js
    │   ├── SectionJavascript.js
    │   ├── SectionLogin.js
    │   ├── SectionNavbars.js
    │   ├── SectionNotifications.js
    │   ├── SectionPills.js
    │   ├── SectionTabs.js
    │   └── SectionTypography.js
    └── LandingPage-Sections
        ├── ProductSection.js
        ├── TeamSection.js
        └── WorkSection.js

Browser Support

At present, we officially aim to support the last two versions of the following browsers:

Resources

HTMLReactVueAngular
Material Dashboard  HTMLMaterial Dashboard  ReactVue Material DashboardMaterial Dashboard Angular
HTML DarkLaravelVuetify
Material Dashboard DarkMaterial Dashboard LaravelMaterial Dashboard Vuetify

Reporting Issues

We use GitHub Issues as the official bug tracker for the NextJS Material Kit. Here are some advices for our users that want to report an issue:

  1. Make sure that you are using the latest version of the Material Kit. Check the CHANGELOG from your dashboard on our website.
  2. Providing us reproducible steps for the issue will shorten the time it takes for it to be fixed.
  3. Some issues may be browser specific, so specifying in what browser you encountered the issue might help.

Licensing

Copyright 2022 Creative Tim (https://www.creative-tim.com/?ref=njsmk-readme)

Licensed under MIT (https://github.com/creativetimofficial/nextjs-material-kit/blob/main/LICENSE.md)

Useful Links

Social Media

Twitter: https://twitter.com/CreativeTim

Facebook: https://www.facebook.com/CreativeTim

Dribbble: https://dribbble.com/creativetim

Instagram: https://www.instagram.com/CreativeTimOfficial

Download details:

Author: creativetimofficial
Source code: https://github.com/creativetimofficial/nextjs-material-kit
License: MIT license

#nextjs #react #reactjs #javascript #scss

NextJS Material Kit: A Free Material-UI Kit with A Fresh, New Design

A Set Of Customizable Widgets As React Components

MarkupWidgets docs 📖

The MarkupWidgets module is a packet of React components (widgets) that provides more tags for building web pages that the programmer can use as default but also customize the base component.

Features

  • 🎨 Fully customizable
  • 🕹️ Interactive widgets
  • 💼 Prop | wrap based content
  • 😍 Nice designs
  • 🏷️ Styles, IDs, etc...

Example page:

Example screenshoots 🖼️

Screenshoot page 1 Screenshoot page 2 Screenshoot page 3

Example syntax 📟

Code of the screenshoots above...

<>
    <Tags.Title>
        Title
    </Tags.Title>
    <Tags.Paragraph>
        Lorem Ipsum es simplemente el texto de relleno de las imprentas y archivos de texto. Lorem Ipsum ha sido el texto de relleno estándar de las industrias desde el año 1500, cuando un impresor (N. del T. persona que se dedica a la imprenta) desconocido usó una galería de textos y los mezcló de tal manera que logró hacer un libro de textos especimen. No sólo sobrevivió 500 años, sino que tambien ingresó como texto de relleno en documentos electrónicos, quedando esencialmente igual al original. Fue popularizado en los 60s con la creación de las hojas Letraset, las cuales contenian pasajes de Lorem Ipsum, y más recientemente con software de autoedición, como por ejemplo Aldus PageMaker, el cual incluye versiones de Lorem Ipsum.
    </Tags.Paragraph>
    <Tags.Title2>
        Subtitle
    </Tags.Title2>
    <Tags.Code>
                                                                // Escaping collons
        <Cmd>git</Cmd> <Opt>commit</Opt> <Flag>-m</Flag> <Str>{'"This is a new commit"'}</Str> &gt; <Path>./text.txt</Path>
    </Tags.Code>
    <Tags.Title3>
        Subtitle
    </Tags.Title3>
    <Tags.Img img={testImg} alt="Alt text"/>
    <Tags.UList items={["Item 1", "Item 2", "Item 3", "Item 4"]} />
    <Tags.Callout label="custom" labelData={{text: "Secret", color: "#25AA88", style: ["font-weight: 500;", "filter: brightness(130%);"]}}>
        This is a custom callout block
    </Tags.Callout>
    <Tags.Callout  >
        This is a custom callout block
    </Tags.Callout>
    <Tags.Quote title="Quote title" text="This is a template text for a quote element as a text prop" />
    <Tags.Quote title="Quote title children">This is a template text for a quote element as a children</Tags.Quote>
    <Tags.Paragraph>
        Lorem Ipsum es simplemente el texto <Tags.Link href="google.com">Link text</Tags.Link> de relleno de las imprentas y archivos.
    </Tags.Paragraph>
</>

How to use the widgets?

Download the module 📥

Navigate to the path of the folder where you want to install the module and clone from the github

git clone https://github.com/PortiESP/MarkupWidgets.git

Import the module 🧩

Import the module from the file where you want to have access to the components, the module is structured in a way that the components can be imported in 3 diferent ways

  • Import directly from the component file
  • Import each component from the ./Tags.js
  • Import the default object of the file ./Tags.js
// Import component directly
import Paragraph from "./MarkupWidgets/tags/Paragraph"
// Import each component separately
import {Title, Paragraph, Code, Callout} from "./MarkupWidgets/Tags"
// Import all components as an object
import Tags from "./MarkupWidgets/Tags"

Use the widgets 🖨️

Using the widgets in the return of a React component

import Tags from "./MarkupWidgets/Tags"
import {Code, Callout}

export default function MyComponent(){

    return (
        <>
            // Using the component from the default imported object
            <Tags.Paragraph>Example title</Tags.Paragraph>
            // Using the component from the specific export
            <Code>sudo chmod +x myScript.sh</Code>
        </>
    )
}

Wrapper & prop based widgets 💼

Most of the widget in the module are compatible with both, wrapper and prop based tags

Wrapper based tag

<Title>
    This is the title content
</Title>

Prop based tag

<Title text="This is the title content" />

If both options are used, the wrapper content will be priorized over the prop value

But other widget like the Img, UList, etc..., this ones only support props to handle their content

Styling the widgets

All the widgets support the style prop to handle the component style, anyways there are a few widgets that offer a bit more advanced features to style the diferent parts of the component

<Title style={myStyles}></Title>

FAQs

How do is escape characters inside a component:

// The inner collons are parsed as part of a JS string and the interpolated in the JSX code
<> This is an {'"example"'} string </>

How do I add a new line in my paragraph, code, callout, etc...:

// The code is parsed as normal text but the <br/> will be parsed as HTML
<Code>
const myArray = {
  elem1,  <br/>
  elem2,  <br/>
  elem3   <br/>
}
</Code>

Widgets list 📜

Title

There are 4 types of titles/headings: h1, h2, h3, h4 as Title1, Title2, ...

Props

  • background - Add a background for the title
  • text - Text content
  • style - Styles object
  • id - Add an ID attribute
<Tags.Title>
    Text template title
</Tags.Title>


<Tags.Title text="Text template title h1" />
<Tags.Title2 text="Text template title h2" background="#303030" />
<Tags.Title3 text="Text template title h3" />

H1

Title example screenshoot

H2

Title example screenshoot

H3

Title example screenshoot

Paragraph

Clasic paragraph to write text, also we can write special characters by adding them inside a JS string

Props

  • text - Text content
  • style - Styles object
  • id - Add an ID attribute
<Tags.Paragraph>
    Lorem Ipsum es simplemente el texto de relleno de las imprentas y 
    archivos de texto. Lorem {'"Ipsum"'} ha sido el texto de relleno estándar de 
    las industrias desde el año 1500.
</Tags.Paragraph>


<Tags.Paragraph text="Text template title" />

Paragraph example screenshoot

Link

The link widget is the same as the <a> tag but with its own styles

Props

  • href - Target location of the link
  • title - Add a title attribute to the tag
  • text - Text content
  • style - Styles object
  • id - Add an ID attribute
Lorem Ipsum <Tags.Link href="www.example.com">Link text</Tags.Link> de relleno.

Link example screenshoot

Img

Display an image, this component can be used in 3 diferent ways based on the props

  • Passing an image object imported from a path
  • Passing the image path, the image will fit the parent container
  • Passing the image path and the height and width props

The image aspect-ratio will respected no matter the option used

Props

  • img - Image object/path
  • alt - Alt text
  • title - Add a title attribute
  • width - Width of the image
  • height - Height of the image
  • hideCaption - Hides the caption text shown when clicking the image
  • style - Styles object
  • id - Add an ID attribute
import testImg from "./exampleImage.jpg"


<Tags.Img img={testImg} alt="Alt text"/>
<Tags.Img img="./images/image.jpg" alt="Alt text"/>
<Tags.Img img="./images/image.jpg" width="100px" height="50px" alt="Alt text"/>

<Tags.Img img={testImg} alt="Alt text" title="Title" caption="Caption"/>
<Tags.Img img={testImg} alt="Alt text" onClick={myCallback}/>

Img example screenshoot

Code

The code widget provides a snippet of some piece of code, if you hover into the block an icon will appear at the bottom-right corner that you can click to copy the code to the clipboard, a copy message will appear when the button is clicked

There are also 3 decorative buttons at the top-right corder, this buttons are just decorative and dont have any action

Props

  • inline - Flag for code string
  • color - Color for the inline code
  • caption - Add a caption text for the code snippet
  • output - Add an nested div to print some kind of command output
  • text - Text content
  • style - Styles object
  • id - Add an ID attribute
// Example from the first image
<Tags.Code>
    git commit -m "This is a new commit" ./text.txt
</Tags.Code>

// Example for second image
// This is how we parse special characters, new lines and tabs
<Tags.Code>{`
export default (<br/>
    {"<>"}                            <br/>
        {"  "}<Flag>comment</Flag>    <br/>
    {"</>"}                           <br/>
)
`}</Tags.Code>


// Example with text prop
<Tags.Code text="Text template title" />

There is also an alternative prop to use this component for writtring inline code

// Example from the second image
This is some content <Tags.Code inline>npm install react</Tags.Code> blablaba
This is some content <Tags.Code inline color="#ab124F">npm install react</Tags.Code> blablaba

To add a new line in your code just type 
as the HTML tag

Both options allow custom styles with the style prop

Code example screenshoot Code2 example screenshoot Inline code example screenshoot

UList

This widget take an array as a prop to generate the list

Props

  • items - Array of the item strings
  • itemStyle - Style of the idividual items
  • style - Styles object
  • id - Add an ID attribute
<Tags.UList items={myItemList} />

UList example screenshoot

Callout

This widget creates a text block to spotlight some text, it also can take a label prop to show a small text at the top of the block (as show in the screenshoots)

This widget can take 3 styles:

  • No label, only the text
  • Predefined labels, The label value can the following values (warning, info, tip, danger) with predefined styles
  • Custom label, The label with custon text & color, but also custom styles

Props

  • label - Text shown at the top in an outter block
  • labelData - Text, color, style (Data taken here only when label='custom')
  • text - Text content
  • style - Styles object
  • id - Add an ID attribute
<Tags.Callout label="warning">
    This is a custom callout block
</Tags.Callout>


// Basic callout
<Tags.Callout text="This is a custom callout block"/>
// Callout with label
<Tags.Callout label="warning" text="This is a custom callout block"/>
// Callout with custom label with default styles
<Tags.Callout label="custom" text="Callout text" labelData={ text: "data", color="#ffffff" } />
// Callout with custom label with custom styles
<Tags.Callout label="custom" text="Callout text" labelData={ text: "Secret", color="#10A5FE", style: [ "background-color: red", "border-radius: 20px"] } /> 

Callout example screenshoot Callout example screenshoot Callout example screenshoot Callout example screenshoot

Quote

Props

  • title Add a title attribute
  • text - Text content
  • style - Styles object
  • id - Add an ID attribute

Quote block, colors can be personalized with the style props

<Tags.Quote title="Quote title">
    This is a template text for a quote element as a text prop
</Tags.Qoute>


<Tags.Quote title="Quote title" text="This is a template text for a quote element as a text prop" />

Quote example screenshoot

Colors

We can apply color styles to some piece of text by using the components of the ./tags/Colors.js, this file contains the color components to apply colors to the wrapped text

This file is not exported by the ./Tags.js file and it needs to be imported manualy

There are 3 types of color here based on their component name:

  • Colors: Colors by name (Yellow, Blue, Red, etc...)(not all colors included)
  • Color of context: Colors that represent the meaning of the text, (Str, Cmd, Opt, Flag)
  • Custom color: Personalized color (Color)

Import module

// Import necesary colors
import {Blue, Red, Orange, Color, Flag} from "./MarkupWidgets/Tags/Colors"
// Import default component: `Color`
import MyColor from "./MarkupWidgets/Tags/Colors"

If you want to rename the components you can use the import as

import {
    Red as R,
    Blue as B,
    Green as G,
    Color as C,
    Flag as F
} from "./MarkupWidgets/Tags/Colors"
// Example 
This is an <R>example</R> text to <F>try</F> the colors

// Nested
<Paragraph>
    This is an <R>example</R> text to <F>try</F> the colors
</Paragraph>

Remember that we have imported the component colors as its initial letter

If we use the Color component we can pass only the CSS color name or the prop color with the value

Lets colour the <C aquamarine>example</C> text
Lets colour the <C color="aquamarine">example</C> text
Lets colour the <C color="rgb(127, 255, 212)">example</C> text

Example of the colors usage in a code widget

Code example screenshoot

Syntax of the screenshoot

Code syntax screenshoot

Hr

Creates a simple horizontal line to divide content, it can also take parameter small to create a shorter line

Props

  • small - Make shorter line
  • style - Styles object
  • id - Add an ID attribute
<Hr />
<Hr small />

Hr screenshoot Hr small screenshoot

Italic & Bold styles

To apply italic or bold styles to some text you can add it as you will do in HTML:

<Paragraph>
    This is an <i>italic</i> word
</Paragraph>

Button

Adds custommizable button, with optional icon and easy-access styling props for the most common attributes, for more specific ones use the style prop

Text content can be passed as a wrapped child or by the text prop, if text is not passed as a wrapped child the prop text must be passed

Props

All of the props are optional

  • text - Text content of the button
  • icon - This props receives an image as an object from an import statement
  • id - Add an ID attribute to the widget
  • callback - Callback function triggered when the button is clicked
  • href - URL to navigate when the button is clicked

Button

  • borderRadius - Round the corners (px)
  • background - Background style of the button

Icon

  • iconScale - Multiplier of the icon size (%): Ex: 120%
  • iconInvert - Invert the colors of the icon (0-100)
  • iconBackground - Background of the icon

Text

  • fontSize - Size of the text (px)
  • color - Color of the text

Object styles

  • style - Global styles of the widget, (styles not recommended here)
  • styleButton - Style of the inner div, (button styles are recommentded here)
  • styleIcon - Style of the icon image div
  • styleText - Style of the text div
  • styleHover - Style of the button when hover (css syntax)
  • styleActive - Style of the button when active (css syntax)

Example button screenshoot

// Import icon from path
import icon from "./myIcon.png"

<Tags.Button // Some example props
    text="Example" 
    icon={icon} 
    callback={myCallback}
    borderRadius="10px" 
    iconScale="140%" 
    iconInvert="100" 
    styleActive="background: red;"
    styleButton={{padding: "30px"}}
/>

Toggle

This widget can expand to show more content

Props

  • title - The title is shown always, wont be hided
  • background - Background of the container
  • backgroundHover - Background of the header when hover
  • arrowColor - Color of the toggle arrow
  • arrowSize - size of the toggle arrow (use units)
  • color - Color of the title text
  • fontSize - Font size of the title (use units)
  • style - Styles wrapper object
  • id - Add an ID attribute
<Tags.Toggle title="Example toggle">

    <Tags.Callout label="info" >
        This is a custom callout block
    </Tags.Callout>
    <Tags.Paragraph>
    Lorem Ipsum es simplemente el texto <Tags.Link href="google.com" title="ggg">Link text</Tags.Link> de relleno de las imprentas y archivos.
    </Tags.Paragraph>
    <Tags.Quote title="Quote title children">This is a template text for a quote element as a children</Tags.Quote>
    
</Tags.Toggle>

Toggle screenshoot Toggle screenshoot

Carousel

The content carousel will display an infinite number of contents as cards, 3 cards are displayed at the same time while the rest is hided, the content can rotate in any direction infinitely, to navigate through the rest of the content cards you can use the arrows, the bubbles or clicking on the side cards

Props

  • cards - Array where each index holds the content of one card
  • callback - This function will be called when the usesr clicks the central card
  • default - Index of the card that will be show in the center
  • spacing - This value detemine the distance between the side cards and the center (use units)
  • duration - Duration of the spinning animation
  • style - Styles object
  • id - Add an ID attribute
<Tags.Carousel 
    callback={ i => console.log(i)}
    spacing="80%"
    cards={[
        <Tags.Title key="" text="Title 1"/>, 
        <Tags.Title key="" text="Title 2"/>, 
        <Tags.Title key="" text="Title 3"/>, 
        <Tags.Title key="" text="Title 4"/>, 
        <Tags.Title key="" text="Title 5"/>, 
        <Tags.Title key="" text="Title 6"/>, 
        <Tags.Title key="" text="Title 7"/>
    ]}
/>

Carousel screenshoot

Block

This widget is really simple, it just wraps content in a box to diferenciate from the code around

Props

  • background - Background of the block
  • bulletColor - Item bullet color
  • style - Styles object
  • id - Add an ID attribute
 <Tags.Block>
    <Tags.UList items={["Item 1", "Item 2", "Item 3", "Item 4"]}/>
    <Tags.Img img="/example1.jpg" height="300px" width="500px" alt="Alt text" caption="Enviorement"/>
</Tags.Block>

Block screenshoot

Url

This widget takes and url and a few information to create a card to make the URL stand out, this widgets will show a title, description, url and a screenshoot of the URL

Props

  • src - URL we want to embed
  • title - Title for the URL card
  • description - Description of the URL content
  • style - Styles object
  • id - Add an ID attribute
<Tags.Url src="https://porti.dev/" title="My personal site" description="An online portfolio and blog where I show my skills"/>

URL screenshoot

Download details:

Author: PortiESP
Source code: https://github.com/PortiESP/MarkupWidgets

#nextjs #react #reactjs #javascript #scss

A Set Of Customizable Widgets As React Components
Quinten  Boehm

Quinten Boehm

1660169160

Weather App: How to Build A Weather App using React and Redux

Weather App

Получение погоды на 5 дней вперед

Используемый Stack

  • React
  • Redux
  • TypeScript
  • axios
  • react-icons
  • redux-thunk
  • sass
  • react-apexcharts

Превьюшка

This project was bootstrapped with Create React App.

Available Scripts

In the project directory, you can run:

npm start

Runs the app in the development mode.
Open http://localhost:3000 to view it in the browser.

The page will reload if you make edits.
You will also see any lint errors in the console.

npm test

Launches the test runner in the interactive watch mode.
See the section about running tests for more information.

npm run build

Builds the app for production to the build folder.
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.
Your app is ready to be deployed!

See the section about deployment for more information.

npm run eject

Note: this is a one-way operation. Once you eject, you can’t go back!

If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

Learn More

You can learn more in the Create React App documentation.

To learn React, check out the React documentation.


Author: Myakis
Source code: https://github.com/Myakis/weather-app

#react-native  #typescript #scss #redux 

Weather App: How to Build A Weather App using React and Redux

Comment Ajouter SCSS Ou SASS à SvelteKit

Bien que Svelte/SvelteKit prenne en charge d'autres préprocesseurs CSS, rien n'est intégré, nous devons donc installer manuellement les dépendances afin de les utiliser dans notre projet. Dans cet article de blog, nous allons passer en revue le moyen le plus simple d'y parvenir.

Pour les personnes qui découvrent Svelte ou SvelteKit, la syntaxe d'utilisation de SCSS ou SASS est simple, il suffit d'ajouter l'attribut lang="sass" à la balise de style.

// SASS

<style lang="sass">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

// SCSS

<style lang="scss">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

Cependant, si j'essaie de le faire dans un nouveau référentiel SvelteKit, je verrai le message d'erreur suivant.

sveltekit-erreur-pas-sass

Voici le message d'erreur complet :

Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/modules/utils.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/autoProcess.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/index.js

The file cannot be parsed because style requires a preprocessor that doesn't seem to be setup or failed during setup. Did you setup a `svelte.config.js`? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. 

See https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info.svelte(style)

La solution

Tout ce que nous avons à faire est d'ajouter du sass à nos dépendances de développement, puis SvelteKit le récupérera automatiquement.

Il existe quelques packages que nous pouvons utiliser pour y parvenir :

  • node-sass est celui qui est le plus référencé, mais comme il est obsolète , je vous recommande fortement d'éviter de l'utiliser.
  • dart-sass est une implémentation plus moderne de node-sass. Mais il a depuis été renommé en sass.
  • sass est celui que vous devriez utiliser !
// NPM

npm i -D sass

// Yarn

yarn add -D sass

// PNPM

pnpm add -D sass

Ensuite, vous devriez voir le message d'erreur ci-dessus disparaître.

erreur sass sveltekit corrigée

Si le message d'erreur ne disparaît pas, essayez de recharger votre éditeur. Si vous utilisez VS Code sur un Mac, vous pouvez le faire avec cmd + p puis recherchez Developer: reload window.

Remarque : vous devrez peut-être également redémarrer l'application SvelteKit pour que cela prenne effet.

Source : https://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit

#scss #sass #sveltekit 

Comment Ajouter SCSS Ou SASS à SvelteKit
曾 俊

曾 俊

1658766729

如何将 SCSS 或 SASS 添加到 SvelteKit

尽管 Svelte/SvelteKit 支持其他 CSS 预处理器,但没有内置任何东西,因此我们需要手动安装依赖项才能在我们的项目中使用它们。在这篇博文中,我们将介绍实现这一目标的最简单方法。

对于刚接触 Svelte 或 SvelteKit 的人来说,使用 SCSS 或 SASS 的语法很简单,只需在 style 标签中添加 lang="sass" 属性即可。

// SASS

<style lang="sass">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

// SCSS

<style lang="scss">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

但是,如果我尝试在新的 SvelteKit 存储库中执行此操作,我将看到以下错误消息。

sveltekit-error-no-sass

这是完整的错误消息:

Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/modules/utils.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/autoProcess.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/index.js

The file cannot be parsed because style requires a preprocessor that doesn't seem to be setup or failed during setup. Did you setup a `svelte.config.js`? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. 

See https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info.svelte(style)

解决方案

我们所要做的就是将 sass 添加到我们的开发依赖项中,然后 SvelteKit 会自动选择它。

我们可以使用一些包来实现这一点:

  • node-sass是被引用最多的一个,但由于它已被弃用,我强烈建议您避免使用它。
  • dart-sassnode-sass. 但后来改名为sass.
  • sass是你应该使用的!
// NPM

npm i -D sass

// Yarn

yarn add -D sass

// PNPM

pnpm add -D sass

然后你应该看到上面的错误信息消失了。

sass sveltekit 错误已修复

如果错误消息没有消失,请尝试重新加载您的编辑器。如果您在 Mac 上使用 VS Code,您可以使用 cmd + p 执行此操作,然后搜索 Developer: reload window。

注意:您可能还需要重新启动 SvelteKit 应用程序才能使其生效。

来源:https ://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit

#scss #sass #sveltekit 

如何将 SCSS 或 SASS 添加到 SvelteKit
Thai  Son

Thai Son

1658763060

Cách Thêm SCSS Hoặc SASS Vào SvelteKit

Mặc dù Svelte / SvelteKit hỗ trợ các bộ tiền xử lý CSS khác, nhưng không có gì tích hợp sẵn, vì vậy chúng tôi cần cài đặt thủ công các phần phụ thuộc để sử dụng chúng trong dự án của mình. Trong bài đăng trên blog này, chúng ta sẽ xem xét cách đơn giản nhất để đạt được điều này.

Đối với những người mới sử dụng Svelte hoặc SvelteKit, cú pháp sử dụng SCSS hoặc SASS rất đơn giản, chỉ cần thêm thuộc tính lang = "sass" vào thẻ style.

// SASS

<style lang="sass">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

// SCSS

<style lang="scss">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

Tuy nhiên, nếu tôi cố gắng thực hiện việc này trong kho lưu trữ SvelteKit mới, tôi sẽ thấy thông báo lỗi sau.

sveltekit-error-no-sass

Đây là thông báo lỗi đầy đủ:

Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/modules/utils.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/autoProcess.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/index.js

The file cannot be parsed because style requires a preprocessor that doesn't seem to be setup or failed during setup. Did you setup a `svelte.config.js`? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. 

See https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info.svelte(style)

Dung dịch

Tất cả những gì chúng ta phải làm là thêm sass vào các phụ thuộc nhà phát triển của mình, sau đó SvelteKit sẽ tự động nhận nó.

Có một số gói chúng tôi có thể sử dụng để đạt được điều này:

  • node-sass là cái được tham chiếu nhiều nhất, nhưng vì nó đã không còn được dùng nữa , tôi thực sự khuyên bạn nên tránh sử dụng cái này.
  • dart-sass là một triển khai hiện đại hơn của node-sass. Nhưng nó đã được đổi tên thành sass.
  • sass là một trong những bạn nên sử dụng!
// NPM

npm i -D sass

// Yarn

yarn add -D sass

// PNPM

pnpm add -D sass

Sau đó, bạn sẽ thấy thông báo lỗi trên biến mất.

lỗi sass sveltekit đã sửa

Nếu thông báo lỗi không biến mất, hãy thử tải lại trình chỉnh sửa của bạn. Nếu bạn sử dụng VS Code trên Mac, bạn có thể thực hiện việc này với cmd + p rồi tìm kiếm Developer: reload window.

Lưu ý: bạn cũng có thể cần phải khởi động lại ứng dụng SvelteKit để điều này có hiệu lực.

Nguồn: https://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit

#scss #sass #sveltekit 

Cách Thêm SCSS Hoặc SASS Vào SvelteKit
Saul  Alaniz

Saul Alaniz

1658762940

Cómo Agregar SCSS O SASS A SvelteKit

Aunque Svelte/SvelteKit es compatible con otros preprocesadores de CSS, no viene nada incorporado, por lo que debemos instalar manualmente las dependencias para usarlas en nuestro proyecto. En esta publicación de blog, repasaremos la forma más sencilla de lograrlo.

Para las personas que son nuevas en Svelte o SvelteKit, la sintaxis para usar SCSS o SASS es simple, solo necesita agregar el atributo lang="sass" a la etiqueta de estilo.

// SASS

<style lang="sass">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

// SCSS

<style lang="scss">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

Sin embargo, si trato de hacer esto en un nuevo repositorio de SvelteKit, veré el siguiente mensaje de error.

Sveltekit-error-no-sass

Aquí está el mensaje de error completo:

Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/modules/utils.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/autoProcess.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/index.js

The file cannot be parsed because style requires a preprocessor that doesn't seem to be setup or failed during setup. Did you setup a `svelte.config.js`? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. 

See https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info.svelte(style)

Solución

Todo lo que tenemos que hacer es agregar sass a nuestras dependencias de desarrollo, luego SvelteKit lo recogerá automáticamente.

Hay algunos paquetes que podemos usar para lograr esto:

  • node-sass es el que más se menciona, pero dado que ha quedado obsoleto , le recomiendo que evite usarlo.
  • dart-sass es una implementación más moderna de node-sass. Pero desde entonces ha sido renombrado a sass.
  • ¡ Sass es el que debes usar!
// NPM

npm i -D sass

// Yarn

yarn add -D sass

// PNPM

pnpm add -D sass

Entonces debería ver desaparecer el mensaje de error anterior.

error de sass sveltekit arreglado

Si el mensaje de error no desaparece, intente recargar su editor. Si usa VS Code en una Mac, puede hacerlo con cmd + p y luego buscar Desarrollador: ventana de recarga.

Nota: es posible que también deba reiniciar la aplicación SvelteKit para que esto surta efecto.

Fuente: https://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit

#scss #sass #sveltekit 

Cómo Agregar SCSS O SASS A SvelteKit

Como Adicionar SCSS Ou SASS Ao SvelteKit

Embora o Svelte/SvelteKit suporte outros pré-processadores CSS, nada vem embutido, então precisamos instalar manualmente as dependências para usá-las em nosso projeto. Nesta postagem do blog, abordaremos a maneira mais simples de conseguir isso.

Para pessoas que são novas no Svelte ou SvelteKit, a sintaxe para usar SCSS ou SASS é simples, basta adicionar o atributo lang="sass" à tag de estilo.

// SASS

<style lang="sass">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

// SCSS

<style lang="scss">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

No entanto, se eu tentar fazer isso em um novo repositório SvelteKit, verei a seguinte mensagem de erro.

sveltekit-error-no-sass

Aqui está a mensagem de erro completa:

Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/modules/utils.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/autoProcess.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/index.js

The file cannot be parsed because style requires a preprocessor that doesn't seem to be setup or failed during setup. Did you setup a `svelte.config.js`? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. 

See https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info.svelte(style)

Solução

Tudo o que temos a fazer é adicionar sass às ​​nossas dependências de desenvolvimento, então o SvelteKit irá buscá-lo automaticamente.

Existem alguns pacotes que podemos usar para conseguir isso:

  • node-sass é o que é mais referenciado, mas como foi preterido , recomendo fortemente que você evite usá-lo.
  • dart-sass é uma implementação mais moderna do node-sass. Mas desde então foi renomeado para sass.
  • sass é o que você deve usar!
// NPM

npm i -D sass

// Yarn

yarn add -D sass

// PNPM

pnpm add -D sass

Então você deve ver a mensagem de erro acima desaparecer.

erro sass sveltekit corrigido

Se a mensagem de erro não desaparecer, tente recarregar seu editor. Se você usa o VS Code em um Mac, pode fazer isso com cmd + p e pesquisar Developer: reload window.

Nota: você também pode precisar reiniciar o aplicativo SvelteKit para que isso tenha efeito.

Fonte: https://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit

#scss #sass #sveltekit 

Como Adicionar SCSS Ou SASS Ao SvelteKit
渚  直樹

渚 直樹

1658758980

SvelteKitにSCSSまたはSASSを追加する方法

Svelte / SvelteKitは他のCSSプリプロセッサをサポートしていますが、何も組み込まれていないため、プロジェクトで使用するには、依存関係を手動でインストールする必要があります。このブログ投稿では、これを実現するための最も簡単な方法について説明します。

SvelteまたはSvelteKitを初めて使用する場合、SCSSまたはSASSを使用するための構文は単純であり、スタイルタグにlang="sass"属性を追加するだけです。

// SASS

<style lang="sass">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

// SCSS

<style lang="scss">
	.page {
		width: 100%;
		max-width: var(--column-width);
		margin: var(--column-margin-top) auto 0 auto;
	}
</style>

ただし、新しいSvelteKitリポジトリでこれを実行しようとすると、次のエラーメッセージが表示されます。

sveltekit-error-no-sass

完全なエラーメッセージは次のとおりです。

Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/modules/utils.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/autoProcess.js
- /Users/hao/workspace/demo/node_modules/.pnpm/svelte-preprocess@4.10.5_svelte@3.46.6+typescript@4.6.3/node_modules/svelte-preprocess/dist/index.js

The file cannot be parsed because style requires a preprocessor that doesn't seem to be setup or failed during setup. Did you setup a `svelte.config.js`? If you use SCSS, it may be necessary to add the path to your NODE runtime to the setting `svelte.language-server.runtime`, or use `sass` instead of `node-sass`. 

See https://github.com/sveltejs/language-tools/tree/master/docs#using-with-preprocessors for more info.svelte(style)

解決

私たちがしなければならないのは、開発依存関係にsassを追加することだけです。そうすれば、SvelteKitが自動的にそれを取得します。

これを実現するために使用できるパッケージがいくつかあります。

  • node-sassは最も参照されているものですが、非推奨になっているため、これを使用しないことを強くお勧めします。
  • dart-sassは、のより現代的な実装ですnode-sass。しかし、その後、名前がに変更されましたsass
  • sassはあなたが使うべきものです!
// NPM

npm i -D sass

// Yarn

yarn add -D sass

// PNPM

pnpm add -D sass

次に、上記のエラーメッセージが消えるはずです。

sasssveltekitエラーが修正されました

エラーメッセージが消えない場合は、エディタをリロードしてみてください。MacでVSCodeを使用している場合は、cmd + pを使用してこれを実行し、Developer:reloadwindowを検索できます。

注:これを有効にするには、SvelteKitアプリを再起動する必要がある場合もあります。

ソース:https ://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit

#scss #sass #sveltekit 

SvelteKitにSCSSまたはSASSを追加する方法

How to Add SCSS or SASS to SvelteKit

Although Svelte/SvelteKit support other CSS preprocessors, nothing comes baked-in so we need to manually install dependencies in order to use them in our project. In this blog post, we'll go over the simplest way to achieve this.

For people who are new to Svelte or SvelteKit, the syntax for using SCSS or SASS is simple, just need to add lang="sass" attribute to style tag.

See more at: https://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit

#scss #sass #sveltekit 

How to Add SCSS or SASS to SvelteKit
Annie  Emard

Annie Emard

1652517180

SCSS Lint: Configurable Tool for Writing Clean, Consistent SCSS

scss-lint is a tool to help keep your SCSS files clean and readable by running it against a collection of configurable linter rules. You can run it manually from the command line, or integrate it into your SCM hooks.

NOTICE: Consider other tools before adopting SCSS-Lint

The Sass core team is now building Sass in Dart instead of Ruby, and will no longer be maintaining the Ruby implementation unless a maintainer steps up to help. Since the SCSS-Lint project relies on the Ruby Sass implementation, this means it will eventually not support the latest Sass features and bug fixes.

One alternative worthy of consideration is stylelint, which supports SCSS natively. If you want to use SCSS-specific rules in addition to stylelint core rules, you need to configure stylelint plugins like stylelint-scss or stylelint-order.

The SCSS-Lint project will continue to accept pull requests and provide basic support on the issue tracker.

Requirements

  • Ruby 2.4+
  • Sass 3.5.5+
  • Files you wish to lint must be written in SCSS (not Sass) syntax

Installation

gem install scss_lint

...or add the following to your Gemfile and run bundle install:

gem 'scss_lint', require: false

The require: false is necessary because scss-lint monkey patches Sass in order to properly traverse the parse tree created by the Sass parser. This can interfere with other applications that invoke the Sass parser after scss-lint libraries have been loaded at runtime, so you should only require it in the context in which you are linting, nowhere else.

Usage

Run scss-lint from the command line by passing in a directory (or multiple directories) to recursively scan:

scss-lint app/assets/stylesheets/

You can also specify a list of files explicitly:

scss-lint app/assets/stylesheets/**/*.css.scss

...or you can lint a file passed via standard input (note the --stdin-file-path flag is required when passing via standard input):

cat some-file | scss-lint --stdin-file-path=path/to/treat/stdin/as/having.scss

scss-lint will output any problems with your SCSS, including the offending filename and line number (if available).

Command Line FlagDescription
-c/--configSpecify a configuration file to use
-e/--excludeExclude one or more files from being linted
-f/--formatOutput format (see Formatters)
-o/--outWrite output to a file instead of STDOUT
-r/--requireRequire file/library (mind $LOAD_PATH, uses Kernel.require)
-i/--include-linterSpecify which linters you specifically want to run
-x/--exclude-linterSpecify which linters you don't want to run
--stdin-file-pathWhen linting a file passed via standard input, treat it as having the specified path to apply the appropriate configuration
--[no-]colorWhether to output in color
-h/--helpShow command line flag documentation
--show-formattersShow all available formatters
--show-lintersShow all available linters
-v/--versionShow version

When running scss-lint with JRuby, using JRuby's --dev flag will probably improve performance.

Configuration

scss-lint loads configuration in the following order of precedence:

  1. Configuration file specified via the --config flag
  2. Configuration from .scss-lint.yml in the current working directory, if it exists
  3. Configuration from .scss-lint.yml in the user's home directory, if it exists

All configurations extend the default configuration.

Note: The first configuration file found is the one that is loaded, e.g. the .scss-lint.yml file in the current working directory is loaded instead of the one in the user's home directory—they are not merged with each other.

Here's an example configuration file:

scss_files: 'app/assets/stylesheets/**/*.css.scss'

exclude: 'app/assets/stylesheets/plugins/**'

linters:
  BorderZero:
    enabled: false

  Indentation:
    exclude:
      - 'path/to/file.scss'
      - 'path/to/directory/**'
    severity: warning
    width: 2

All linters have an enabled option which can be true or false, which controls whether the linter is run, along with linter-specific options. The defaults are defined in config/default.yml.

Severities

The severity linter option allows you to specify whether the lint should be treated as a warning or an error. Warnings cause scss-lint to exit with a different error code than errors (unless both warnings and errors are present, in which case the error exit code is returned). This is useful when integrating scss-lint with build systems or other executables, as you can rely on its exit status code to indicate whether a lint actually requires attention.

You can also define the default severity for all linters by setting the global severity option.

Excluding Files

The exclude directive allows you to specify a glob pattern of files that should not be linted by scss-lint. Paths are relative to the location of the config file itself if they are not absolute paths. If an inherited file specifies the exclude directive, the two exclusion lists are combined. Any additional exclusions specified via the --exclude flag are also combined. If you need to exclude files for a single linter you can specify the list of files using the linter's exclude configuration option.

Generating a Configuration

To start using scss-lint you can use the Config Formatter, which will generate an .scss-lint.yml configuration file with all linters which caused a lint disabled. Starting with this as your configuration you can slowly enable each linter and fix any lints one by one.

Disabling Linters via Source

For special cases where a particular lint doesn't make sense in a specific area of a file, special inline comments can be used to enable/disable linters. Some examples are provided below:

Disable for the entire file

// scss-lint:disable BorderZero
p {
  border: none; // No lint reported
}

Disable a few linters

// scss-lint:disable BorderZero, StringQuotes
p {
  border: none; // No lint reported
  content: "hello"; // No lint reported
}

Disable all lints within a block (and all contained blocks)

p {
  // scss-lint:disable BorderZero
  border: none; // No lint reported
}

a {
  border: none; // Lint reported
}

Disable and enable again

// scss-lint:disable BorderZero
p {
  border: none; // No lint reported
}
// scss-lint:enable BorderZero

a {
  border: none; // Lint reported
}

Disable for just one line

p {
  // No lint reported:
  border: none; // scss-lint:disable BorderZero

  a {
    border: none; // Lint reported
  }
}

Disable/enable all linters

// scss-lint:disable all
p {
  border: none; // No lint reported
}
// scss-lint:enable all

a {
  border: none; // Lint reported
}

Formatters

Default

The default formatter is intended to be easy to consume by both humans and external tools.

scss-lint [scss-files...]
test.scss:2:1 [W] StringQuotes: Prefer single quoted strings
test.scss:2:1 [W] Indentation: Line should be indented 0 spaces, but was indented 1 space
test.scss:5:1 [W] StringQuotes: Prefer single quoted strings
test.scss:6:8 [W] UrlQuotes: URLs should be enclosed in quotes

CleanFiles

Displays a list of all files that were free of lints.

Config

Returns a valid .scss-lint.yml configuration where all linters which caused a lint are disabled. Starting with this as your configuration, you can slowly enable each linter and fix any lints one by one.

scss-lint --format=Config [scss-files...]
linters:
  Indentation:
    enabled: false
  StringQuotes:
    enabled: false
  UrlQuotes:
    enabled: false

Files

Useful when you just want to open all offending files in an editor. This will just output the names of the files so that you can execute the following to open them all:

scss-lint --format=Files [scss-files...] | xargs vim

JSON

Outputs JSON with filenames and an array of issue objects.

{
  "test.css": [
    {"line": 2, "column": 1, "length": 2, "severity": "warning", "reason": "Prefer single quoted strings", "linter": "StringQuotes"},
    {"line": 2, "column": 1, "length": 1, "severity": "warning", "reason": "Line should be indented 0 spaces, but was indented 1 spaces", "linter": "Indentation"},
    {"line": 5, "column": 5, "length": 2, "severity": "warning", "reason": "Prefer single quoted strings", "linter": "StringQuotes"},
    {"line": 6, "column": 4, "length": 9, "severity": "warning", "reason": "URLs should be enclosed in quotes", "linter": "UrlQuotes"}
  ]
}

TAP

Outputs TAP version 13 format.

TAP version 13
1..5
ok 1 - ok1.scss
not ok 2 - not-ok1.scss:123:10 SCSSLint::Linter::PrivateNamingConvention
  ---
  message: Description of lint 1
  severity: warning
  data:
    file: not-ok1.scss
    line: 123
    column: 10
  ---
not ok 3 - not-ok2.scss:20:2 SCSSLint::Linter::PrivateNamingConvention
  ---
  message: Description of lint 2
  severity: error
  data:
    file: not-ok2.scss
    line: 20
    column: 2
  ---
not ok 4 - not-ok2.scss:21:3 SCSSLint::Linter::PrivateNamingConvention
  ---
  message: Description of lint 3
  severity: warning
  data:
    file: not-ok2.scss
    line: 21
    column: 3
  ---
ok 5 - ok2.scss

Stats

Outputs statistics about how many lints of each type were found, and across how many files. This reporter can help in cleaning up a large codebase, allowing you to fix and then enable one lint type at a time.

15  ColorKeyword                  (across  1 files)
15  ColorVariable                 (across  1 files)
11  StringQuotes                  (across 11 files)
11  EmptyLineBetweenBlocks        (across 11 files)
 5  Indentation                   (across  1 files)
 5  QualifyingElement             (across  2 files)
 4  MergeableSelector             (across  1 files)
--  ----------------------        -----------------
66  total                         (across 12 files)

Plugins

There are also formatters that integrate with third-party tools which are available as plugins.

Checkstyle

Outputs an XML document with <checkstyle>, <file>, and <error> tags. Suitable for consumption by tools like Jenkins with the Checkstyle plugin.

gem install scss_lint_reporter_checkstyle
scss-lint --require=scss_lint_reporter_checkstyle --format=Checkstyle [scss-files...]
<?xml version="1.0" encoding="utf-8"?>
<checkstyle version="1.5.6">
  <file name="test.css">
    <error line="2" severity="warning" message="Prefer single quoted strings" />
    <error line="2" severity="warning" message="Line should be indented 0 spaces, but was indented 1 spaces" />
    <error line="5" severity="warning" message="Prefer single quoted strings" />
    <error line="6" severity="warning" message="URLs should be enclosed in quotes" />
  </file>
</checkstyle>

Exit Status Codes

scss-lint tries to use semantic exit statuses wherever possible, but the full list of codes and the conditions under which they are returned is listed here for completeness.

Exit StatusDescription
0No lints were found
1Lints with a severity of warning were reported (no errors)
2One or more errors were reported (and any number of warnings)
64Command line usage error (invalid flag, etc.)
66One or more files specified were not found
69Required library specified via -r/--require flag was not found
70Unexpected error (i.e. a bug); please report it
78Invalid configuration file; your YAML is likely incorrect
80Files glob patterns specified did not match any files.

Linters

scss-lint is a customizable tool with opinionated defaults that helps you enforce a consistent style in your SCSS. For these opinionated defaults, we've had to make calls about what we think are the "best" style conventions, even when there are often reasonable arguments for more than one possible style.

Should you want to customize the checks run against your code, you can do so by editing your configuration file to match your preferred style.

» Linters Documentation

Custom Linters

scss-lint allows you to create custom linters specific to your project. By default, it will load linters from the .scss-linters in the root of your repository. You can customize which directories to load from via the plugin_directories option in your .scss-lint.yml configuration file. See the linters directory for examples of how to write linters. All linters loaded from directories in plugin_directories are enabled by default, and you can set their configuration in your .scss-lint.yml.

# .scss-linters/another_linter.rb

module SCSSLint
  class Linter::AnotherLinter < Linter
    include LinterRegistry

    ...
  end
end
# .scss-lint.yml
plugin_directories: ['.scss-linters', '.another_directory']

linters:
  AnotherLinter:
    enabled: true
    some_option: [1, 2, 3]

You can also load linters packaged as gems by specifying the gems via the plugin_gems configuration option. See the scss_lint_plugin_example for an example of how to structure these plugins.

If the gem is packaged with an .scss-lint.yml file in its root directory then this will be merged with your configuration. This provides a convenient way for organizations to define a single repo with their scss-lint configuration and custom linters and use them across multiple projects. You can always override plugin configuration with your repo's .scss-lint.yml file.

# .scss-lint.yml
plugin_gems: ['scss_lint_plugin_example']

Note that you don't need to publish a gem to Rubygems to take advantage of this feature. Using Bundler, you can specify your plugin gem in your project's Gemfile and reference its git repository instead:

# Gemfile
gem 'scss_lint_plugin_example', git: 'git://github.com/cih/scss_lint_plugin_example'

As long as you execute scss-lint via bundle exec scss-lint, it should be able to load the gem.

Preprocessing

Sometimes SCSS files need to be preprocessed before being linted. This is made possible with two options that can be specified in your configuration file.

The preprocess_command option specifies the command to run once per SCSS file. The command can be specified with arguments. The contents of a SCSS file will be written to STDIN, and the processed SCSS contents must be written to STDOUT. If the process exits with a code other than 0, scss-lint will immediately exit with an error.

For example, preprocess_command: "cat" specifies a simple no-op preprocessor (on Unix-like systems). cat simply writes the contents of STDIN back out to STDOUT.

Metadata codeblocks like Jekyll Front Matter at the beginning of SCSS files can cause a syntax error when SCSS-Lint does not encounter Sass at the first line of the file, e.g. Invalid CSS after "@charset "utf-8"": expected "{", was ";". To search the first line for front matter's triple dash delimiter ---, strip out the YAML codeblock and pass the result to SCSS-Lint with line numbers preserved, you can use preprocess_command: "sed '1{/^---$/{:a N;/---$/!ba;d}}'" -- please note this sed command is valid for gnu-sed. If you are using the FreeBSD version of sed that ships with Mac OS X by default, it will throw an EOF error. You may solve this error by installing Homebrew, running brew install gnu-sed, and then substituting gsed for sed in the preprocess_command.

If only some SCSS files need to be preprocessed, you may use the preprocess_files option to specify a list of file globs that need preprocessing. Preprocessing only a subset of files should make scss-lint more performant.

Automated Code Review

Codacy

Codacy automates code reviews and monitors code quality on every commit and pull request. With Codacy you have scss-lint analysis out-of-the-box, and it is free for open source projects. It gives visibility into the technical debt and it can track code style and security issues, code coverage, code duplication, cyclomatic complexity and enforce best practices.

Editor Integration

Vim

You can have scss-lint automatically run against your SCSS files after saving by using the Syntastic plugin. If you already have the plugin, just add let g:syntastic_scss_checkers = ['scss_lint'] to your .vimrc.

IntelliJ

Install the SCSS Lint plugin for IntelliJ

Sublime Text

Install the Sublime scss-lint plugin.

Atom

Install the Atom scss-lint plugin. It is a part of the atomlinter project, so if you are already using other linter plugins, you can keep them in one place.

Emacs

Install and enable both scss-mode and flycheck-mode. You can enable automatic linting for scss-mode buffers with (add-hook 'scss-mode-hook 'flycheck-mode) in your init.el.

TextMate 2

If you use TextMate 2, you can install the SCSS-Lint.tmbundle bundle.

Visual Studio Code

If you use Visual Studio Code, you can install the scss-lint extension

Git Integration

If you'd like to integrate scss-lint into your Git workflow, check out our Git hook manager, overcommit.

Rake Integration

To execute scss-lint via a Rake task, ensure you have rake in your gem path (e.g. by adding to your Gemfile), and add the following to your Rakefile:

require 'scss_lint/rake_task'

SCSSLint::RakeTask.new

When you execute rake scss_lint, the above configuration is equivalent to just running scss-lint, which will lint all .scss files in the current working directory and its descendants.

You can customize the task by writing:

require 'scss_lint/rake_task'

SCSSLint::RakeTask.new do |t|
  t.config = 'custom/config.yml'
  t.args = ['--format', 'JSON', '--out', 'results.txt']
  t.files = Dir.glob(['app/assets', 'custom/*.scss'])
end

You can specify any command line arguments in the args attribute that are allowed by the scss-lint Ruby binary script. Each argument must be passed as an Array element, rather than one String with spaces.

You can also use this custom configuration with a set of files specified via the command line (note that this will not expand glob patterns):

# Single quotes prevent shell glob expansion
rake 'scss_lint[app/assets, custom/file-with-a-literal-asterisk-*.scss]'

Files specified in this manner take precedence over the files attribute initialized in the configuration above.

Maven Integration

Maven integration is available as part of the Sass maven plugin scss-lint since version 2.3 Check out the plugin documentation.

The Maven plugin comes with the necessary libraries included, a separate installation of ruby or scss-lint is not required.

Documentation

Code documentation is generated with YARD and hosted by RubyDoc.info.

Contributing

We love getting feedback with or without pull requests. If you do add a new feature, please add tests so that we can avoid breaking it in the future.

Speaking of tests, we use rspec, which can be run like so:

bundle exec rspec

After you get the unit tests passing, you probably want to see your version of scss-lint in action. You can use Bundler to execute your binary locally from within your project's directory:

bundle exec bin/scss-lint

Community

All major discussion surrounding SCSS-Lint happens on the GitHub issues page.

You can also follow @scss_lint on Twitter.

Changelog

If you're interested in seeing the changes and bug fixes between each version of scss-lint, read the SCSS-Lint Changelog.

Code of conduct

This project adheres to the Open Code of Conduct. By participating, you are expected to honor this code.

Author: sds
Source Code: https://github.com/sds/scss-lint
License: MIT License

#scss #lint 

SCSS Lint: Configurable Tool for Writing Clean, Consistent SCSS