1664370906
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.
There are 4 ways to use retina.js
:
src
paths on img
tags.src
attributes and inline styles).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.
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.
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>
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:
path
- The path to your standard resolution image.cap
- Optional. The highest resolution level for which you have prepared images. Defaults to 2.size
- Optional. A value to be applied to the background-size
property. Defaults to auto auto
.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;
}
}
retina.js
is compatible with all modern browsers and should not throw errors in old browsers all the way back through IE6.
There are 2 ways to use the JavaScript version of retina.js
:
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.
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.
The process for including the CSS mixins is relatively straightforward. Here is a breakdown for each:
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
.
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
.
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
.
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
.
...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:
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.
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.
Author: Strues
Source Code: https://github.com/strues/retinajs
License: MIT license
1662773640
Lint, or a linter, is a static code analysis tool used to flag programming errors, bugs, stylistic errors and suspicious constructs.
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.
SASS offers a galore of features that make it a better tool than CSS for developers. Some of its major highlights are:
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.
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:
In this article below, We'll share 3 Static Analysis Tools & Linters for SCSS and SASS
A Node-only Sass linter for both sass
and scss
syntax!
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
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.
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.
The following are options that you can use to config the Sass Linter.
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'
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
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.
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.
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 Flag | Description |
---|---|
-c /--config | Specify a configuration file to use |
-e /--exclude | Exclude one or more files from being linted |
-f /--format | Output format (see Formatters) |
-o /--out | Write output to a file instead of STDOUT |
-r /--require | Require file/library (mind $LOAD_PATH , uses Kernel.require ) |
-i /--include-linter | Specify which linters you specifically want to run |
-x /--exclude-linter | Specify which linters you don't want to run |
--stdin-file-path | When linting a file passed via standard input, treat it as having the specified path to apply the appropriate configuration |
--[no-]color | Whether to output in color |
-h /--help | Show command line flag documentation |
--show-formatters | Show all available formatters |
--show-linters | Show all available linters |
-v /--version | Show version |
When running scss-lint
with JRuby, using JRuby's --dev
flag will probably improve performance.
A mighty, modern linter that helps you avoid errors and enforce conventions in your styles.
It's mighty as it:
And can be extended to:
It'll help you avoid errors, for example styles that are:
And enforce conventions, for example:
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.
We recommend you lint your CSS before applying any transformations. You can do this by either:
plugins
option of postcss-import
or postcss-easy-import
to lint your files before any transformations.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
).
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.
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));
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
1662440880
PostCSS SCSS Syntax
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.
npm --save install postcss postcss-scss
There are two ways to use this parser:
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: {
…
}
}
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.
To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.
Author: Postcss
Source Code: https://github.com/postcss/postcss-scss
License: MIT license
1662032700
Svelte boilerplate to kick-start new project with SCSS + Bootstrap
# 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
Author: akunzai
Source code: https://github.com/akunzai/svelte-boilerplate
License: MIT license
#svelte #javascript #scss
1661030340
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.
React Native | Figma | WordPress | NextJS |
---|---|---|---|
![]() | ![]() | ![]() | ![]() |
HTML | React | Vue |
---|---|---|
![]() | ![]() | ![]() |
Buttons | Inputs | Navbars |
---|---|---|
![]() | ![]() | ![]() |
Login Page | Landing Page | Profile Page |
---|---|---|
![]() | ![]() | ![]() |
git clone https://github.com/creativetimofficial/nextjs-material-kit.git
.npm i nextjs-material-kit
bower install nextjs-material-kit
.The documentation for the NextJS Material Kit is hosted at our website.
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
At present, we officially aim to support the last two versions of the following browsers:
HTML | React | Vue | Angular |
---|---|---|---|
![]() | ![]() | ![]() | ![]() |
HTML Dark | Laravel | Vuetify |
---|---|---|
![]() | ![]() | ![]() |
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:
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)
Twitter: https://twitter.com/CreativeTim
Facebook: https://www.facebook.com/CreativeTim
Dribbble: https://dribbble.com/creativetim
Instagram: https://www.instagram.com/CreativeTimOfficial
Author: creativetimofficial
Source code: https://github.com/creativetimofficial/nextjs-material-kit
License: MIT license
#nextjs #react #reactjs #javascript #scss
1660900560
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.
Example screenshoots 🖼️
Example syntax 📟
<>
<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> > <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>
</>
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 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
./Tags.js
./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"
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>
</>
)
}
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
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>
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>
There are 4 types of titles/headings: h1, h2, h3, h4 as Title1, Title2, ...
Props
background
- Add a background for the titletext
- Text contentstyle
- Styles objectid
- 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
H2
H3
Clasic paragraph to write text, also we can write special characters by adding them inside a JS string
Props
text
- Text contentstyle
- Styles objectid
- 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" />
The link widget is the same as the <a>
tag but with its own styles
Props
href
- Target location of the linktitle
- Add a title attribute to the tagtext
- Text contentstyle
- Styles objectid
- Add an ID attribute
Lorem Ipsum <Tags.Link href="www.example.com">Link text</Tags.Link> de relleno.
Display an image, this component can be used in 3 diferent ways based on the props
height
and width
propsThe image aspect-ratio will respected no matter the option used
Props
img
- Image object/pathalt
- Alt texttitle
- Add a title attributewidth
- Width of the imageheight
- Height of the imagehideCaption
- Hides the caption text shown when clicking the imagestyle
- Styles objectid
- 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}/>
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 stringcolor
- Color for the inline codecaption
- Add a caption text for the code snippetoutput
- Add an nested div to print some kind of command outputtext
- Text contentstyle
- Styles objectid
- 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
This widget take an array as a prop to generate the list
Props
items
- Array of the item stringsitemStyle
- Style of the idividual itemsstyle
- Styles objectid
- Add an ID attribute
<Tags.UList items={myItemList} />
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:
label
value can the following values (warning, info, tip, danger) with predefined stylesProps
label
- Text shown at the top in an outter blocklabelData
- Text, color, style (Data taken here only when label='custom')text
- Text contentstyle
- Styles objectid
- 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"] } />
Props
title
Add a title attributetext
- Text contentstyle
- Styles objectid
- 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" />
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:
Yellow
, Blue
, Red
, etc...)(not all colors included)Str
, Cmd
, Opt
, Flag
)Color
)// 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
Syntax of the screenshoot
Creates a simple horizontal line to divide content, it can also take parameter small
to create a shorter line
Props
small
- Make shorter linestyle
- Styles objectid
- Add an ID attribute
<Hr />
<Hr small />
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>
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 buttonicon
- This props receives an image as an object from animport
statementid
- Add an ID attribute to the widgetcallback
- Callback function triggered when the button is clickedhref
- URL to navigate when the button is clickedButton
borderRadius
- Round the corners (px)background
- Background style of the buttonIcon
iconScale
- Multiplier of the icon size (%): Ex: 120%iconInvert
- Invert the colors of the icon (0-100)iconBackground
- Background of the iconText
fontSize
- Size of the text (px)color
- Color of the textObject 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 divstyleText
- Style of the text divstyleHover
- Style of the button when hover (css syntax)styleActive
- Style of the button when active (css syntax)
// 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"}}
/>
This widget can expand to show more content
Props
title
- The title is shown always, wont be hidedbackground
- Background of the containerbackgroundHover
- Background of the header when hoverarrowColor
- Color of the toggle arrowarrowSize
- size of the toggle arrow (use units)color
- Color of the title textfontSize
- Font size of the title (use units)style
- Styles wrapper objectid
- 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>
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 cardcallback
- This function will be called when the usesr clicks the central carddefault
- Index of the card that will be show in the centerspacing
- This value detemine the distance between the side cards and the center (use units)duration
- Duration of the spinning animationstyle
- Styles objectid
- 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"/>
]}
/>
This widget is really simple, it just wraps content in a box to diferenciate from the code around
Props
background
- Background of the blockbulletColor
- Item bullet colorstyle
- Styles objectid
- 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>
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 embedtitle
- Title for the URL carddescription
- Description of the URL contentstyle
- Styles objectid
- 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"/>
Author: PortiESP
Source code: https://github.com/PortiESP/MarkupWidgets
#nextjs #react #reactjs #javascript #scss
1660169160
This project was bootstrapped with Create React App.
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.
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
1658766791
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.
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)
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
. Mais il a depuis été renommé en sass
.// 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.
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
1658766729
尽管 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 存储库中执行此操作,我将看到以下错误消息。
这是完整的错误消息:
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 会自动选择它。
我们可以使用一些包来实现这一点:
// NPM
npm i -D sass
// Yarn
yarn add -D sass
// PNPM
pnpm add -D sass
然后你应该看到上面的错误信息消失了。
如果错误消息没有消失,请尝试重新加载您的编辑器。如果您在 Mac 上使用 VS Code,您可以使用 cmd + p 执行此操作,然后搜索 Developer: reload window。
注意:您可能还需要重新启动 SvelteKit 应用程序才能使其生效。
来源:https ://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit
1658763060
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.
Đâ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)
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
. Nhưng nó đã được đổi tên thành sass
.// 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.
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
1658762940
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.
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)
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
. Pero desde entonces ha sido renombrado a sass
.// 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.
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
1658759400
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.
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)
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
. Mas desde então foi renomeado para sass
.// 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.
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
1658758980
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リポジトリでこれを実行しようとすると、次のエラーメッセージが表示されます。
完全なエラーメッセージは次のとおりです。
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
。しかし、その後、名前がに変更されましたsass
。// NPM
npm i -D sass
// Yarn
yarn add -D sass
// PNPM
pnpm add -D sass
次に、上記のエラーメッセージが消えるはずです。
エラーメッセージが消えない場合は、エディタをリロードしてみてください。MacでVSCodeを使用している場合は、cmd + pを使用してこれを実行し、Developer:reloadwindowを検索できます。
注:これを有効にするには、SvelteKitアプリを再起動する必要がある場合もあります。
ソース:https ://blog.hao.dev/how-to-add-scss-or-sass-to-sveltekit
1658741705
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
1652517180
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.
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.
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 Flag | Description |
---|---|
-c /--config | Specify a configuration file to use |
-e /--exclude | Exclude one or more files from being linted |
-f /--format | Output format (see Formatters) |
-o /--out | Write output to a file instead of STDOUT |
-r /--require | Require file/library (mind $LOAD_PATH , uses Kernel.require ) |
-i /--include-linter | Specify which linters you specifically want to run |
-x /--exclude-linter | Specify which linters you don't want to run |
--stdin-file-path | When linting a file passed via standard input, treat it as having the specified path to apply the appropriate configuration |
--[no-]color | Whether to output in color |
-h /--help | Show command line flag documentation |
--show-formatters | Show all available formatters |
--show-linters | Show all available linters |
-v /--version | Show version |
When running scss-lint
with JRuby, using JRuby's --dev
flag will probably improve performance.
scss-lint
loads configuration in the following order of precedence:
--config
flag.scss-lint.yml
in the current working directory, if it exists.scss-lint.yml
in the user's home directory, if it existsAll 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
.
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.
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.
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.
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
}
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
Displays a list of all files that were free of lints.
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
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
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"}
]
}
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
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)
There are also formatters that integrate with third-party tools which are available as plugins.
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>
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 Status | Description |
---|---|
0 | No lints were found |
1 | Lints with a severity of warning were reported (no errors) |
2 | One or more errors were reported (and any number of warnings) |
64 | Command line usage error (invalid flag, etc.) |
66 | One or more files specified were not found |
69 | Required library specified via -r /--require flag was not found |
70 | Unexpected error (i.e. a bug); please report it |
78 | Invalid configuration file; your YAML is likely incorrect |
80 | Files glob patterns specified did not match any files. |
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.
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.
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.
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.
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
.
Install the SCSS Lint plugin for IntelliJ
Install the Sublime scss-lint plugin.
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.
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
.
If you use TextMate 2
, you can install the SCSS-Lint.tmbundle bundle.
If you use Visual Studio Code
, you can install the scss-lint extension
If you'd like to integrate scss-lint
into your Git workflow, check out our Git hook manager, overcommit.
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 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.
Code documentation is generated with YARD and hosted by RubyDoc.info.
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
All major discussion surrounding SCSS-Lint happens on the GitHub issues page.
You can also follow @scss_lint on Twitter.
If you're interested in seeing the changes and bug fixes between each version of scss-lint
, read the SCSS-Lint Changelog.
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