Node js scss to css

sass

The sass package on npm is a pure-JavaScript package built from the Dart Sass implementation. In addition to Dart Sass’s command-line interface, it provides a JavaScript API that can be used to drive Sass compilations from JavaScript. It even allows an application to control how stylesheets are loaded and define custom functions.

Usage

The JavaScript API provides two entrypoints for compiling Sass to CSS , each of which has a synchronous variant that returns a plain CompileResult and an asynchronous variant that returns a Promise . The asynchronous variants are much slower, but they allow custom importers and functions to run asynchronously.

    compile and compileAsync take a path to a Sass file and return the result of compiling that file to CSS . These functions accept an additional Options argument.

const sass = require('sass');

const result = sass.compile("style.scss");
console.log(result.css);

const compressed = sass.compile("style.scss", style: "compressed">);
console.log(compressed.css);
const sass = require('sass');

const input = `
h1
font-size: 40px;
code
font-face: Roboto Mono;
>
>`;

const result = sass.compileString(input);
console.log(result.css);

const compressed = sass.compileString(input, style: "compressed">);
console.log(compressed.css);

Integrations

Most popular Node.js build systems have integrations available for the JS API :

  • Webpack uses the sass-loader package.
  • Gulp uses the gulp-sass package.
  • Broccoli uses the broccoli-sass-source-maps package.
  • Ember uses the ember-cli-sass package.
  • Grunt uses the grunt-sass package.

Legacy API

The sass package also supports an older API . Although this API is deprecated, it will continue to be supported until the release of version 2.0.0 of the sass package. The legacy API is also supported by the node-sass package, which is a native extension wrapper for the deprecated LibSass implementation.

The legacy API has two entrypoints for compiling Sass to CSS . Each one can compile either a Sass file by passing in LegacyFileOptions or a string of Sass code by passing in a LegacyStringOptions.

    renderSync runs synchronously. It’s by far the fastest option when using Dart Sass, but at the cost of only supporting synchronous importer and function plugins.

const sass = require('sass'); // or require('node-sass');

const result = sass.renderSync(file: "style.scss">);
console.log(result.css.toString());
const sass = require('sass'); // or require('node-sass');

sass.render(
file: "style.scss"
>, function(err, result)
if (err)
// .
> else
console.log(result.css.toString());
>
>);

Источник

Сборка CSS, SCSS и SASS с помощью node-sass

Обычно сборку SCSS и SASS делают с помощью специальных сборщиков Webpack или Gulp. Да, эти инструменты хороши, но когда ты делаешь простой сайт или лендинг, то настройка этих самых сборщиков может занять очень много времени. Я покажу как за несколько минут можно настроить сборку и минимизацию стилей при помощи пакета node-sass. Для выполнения всех приведенных действий вам потребуется установленный nodejs.

Немного о SCSS и SASS

SCSS — это по сути тот же CSS только с возможностью использовать переменные, как в PHP $имя_переменной . А SASS(Syntactically Awesome Stylesheets) — это SCSS с упрощенным синткасисом без фигурных скобок и точек с запятой в конце каждой строки. Оба языка позволяют использовать переменные в таблицах стилей, а так же импортировтаь и объединять стили между собой. Хотя, на данный момент CSS уже поддерживает переменные нативно, еще не все браузеры их поддерживают(привет IE!).

Как правило, в более сложных веб-приложениях файлы стилей разделяются на исходники и сборки. Исходники стилей принято разделять на отдельные файлы. Например, стили для таблиц в одном файле, стили списков в другом и так далее. Потом это все объединяется с помощью директивы @import в один главный sass файл, который обрабатывается препроцессором в обычный CSS.

Если вы пользуетесь CSS фреймворками, такими как bootstrap или bulma, с помощью SASS вы сможете легко кастомизировать их.

$base-text: #343434; $gray-text: #BBB; p < color: $base-text; >p.gray
$base-text: #343434 $gray-text: #BBB p color: $base-text p.gray color: $gray-text

Настройка и подготовка проекта

Инициализация проекта и установка node-sass

mkdir node-sass cd node-sass npm init -y npm i node-sass --save-dev

После завершания установки в папке должны появиться следующие файлы:

ls node_modules package.json package-lock.json

Теперь надо создать папки для исходников, где будут лежать SASS-стили и папку, куда будут складываться собранные стили.

mkdir -p src/sass mkdir -p public/build

В директории src/sass будут лежать исходники, а в public/build собранные стили.

Установка Bootstrap и создание таблиц стилей

В качестве примера я буду использовать CSS фреймворк Bootstrap 4 и несколько собственных таблиц силей.

Для начала надо установить bootstrap:

Теперь можно создать несколько таблиц стилей и подключить Bootstrap в наш проект. Я создам один главный файл theme.sass, импортирую в него bootstrap и добавлю несколько кастомных стилей.

@import 'bootstrap/scss/bootstrap' $main-color: #4c4c4c $main-bg: #fafafa body background-color: $main-bg p color: $main-color 

Строка @import ‘bootstrap/scss/bootstrap’ означает импорт файла корень_проекта/node_modules/bootstrap/scss/bootstrap.scss (расширение файла можно не указывать) . В данном случае импортируются все стили библиотеки bootstrap. Но можно импортировать их и частями, если открыть папку node_modules/bootstrap/scss , то вы увидите много файлов scss. Например, если хотите использовать только сетку, то надо импортировать файл bootstrap-grid.scss.

Имя импортируемого файла может быть относительно текущего файла, например @import ‘./lists’ либо относительно директории node_modules, как в моем примере. Если вы указываете путь относительно node_modules надо будет добавить опцию —include-path node_modules для команды npx node-sass .

Сборка стилей

Теперь мы можем собрать наши стили. Мы будем использовать ранее установленный пакет node-sass. Для запуска бинарников из npm пакетов надо использовать консольную команду npx __название_пакета__ . В нашем случае запуск node-sass будет выполняться командой npx node-sass .

npx node-sass \ --include-path node_modules \ --output-style compressed \ src/sass/theme.sass > public/build/theme.css

Если команда выполнилась без ошибок, то должен появиться файл public/build/theme.css — это и есть наш собранный и минимизированный CSS, который теперь можно подключить к html странице.

Во время разработки сайта, чтобы каждый раз не выполнять команду для сборки стилей можно использовать опцию —watch . Тогда node-sass будет отслеживать изменения в исходниках стилей и автоматически пересобирать CSS.

Добавление команд в package.json

Синтаксис некоторых комманд получается довольно громоздкий. Чтобы каждый раз не воодить их полностью, им придумывают короткие alias’ы и сохраняют в файл package.json, в раздел scripts.

 < "name": "node_sass_example", "version": "1.0.0", "description": "", "main": "index.js", "scripts": < "sass": "npx node-sass --include-path node_modules --output-style compressed src/sass/theme.sass >public/build/theme.css", "sass:watch": "npx node-sass --watch --include-path node_modules --output-style compressed src/sass/theme.sass > public/build/theme.css", "test": "echo \"Error: no test specified\" && exit 1" >, "keywords": [], "author": "", "license": "ISC", "dependencies": < "bootstrap": "^4.0.0" >, "devDependencies": < "node-sass": "^4.7.2" >>

После сохранения команд в package.json сборку можно выполнить командой npm run sass или npm run sass:watch чтобы css стили автоматически пересобиралились при изменении sass/scss исходников.

Источник

5 Quick Steps Transpiling SCSS to CSS Using Node (with watch & minify mode)

package.json file

Open vscode terminal. Run the command
npm init Press enter to all the options(description, author, keyword etc.) one by one or put the information in every option(if you wish, but not mandatory). After that, package.json file will generate in your file structure.

3. Install Sass

Go to npm website to find sass package. npm sass package Execute the command on terminal
npm install sass After that node_modules folder and package-lock.json file will be added the file structure. node_modules package-lock json file

4. Write sass Command

Go to the package.json file. In the scripts section remove «test»: «echo \»Error: no test specified\» && exit 1″ and add the small script

css folder

After executing the script, it will generate style.css and style.css.map in the css folder.

  • If you want to avoid style.css.map file, the script will be

5. Run the Script

Execute the command on terminal to run the script

npm run scss
or
npm run scss-no-source-map
or
npm run minify
or
npm run minify-no-source-map

Point to be Noted
In html file, you must link with the css file generated in css folder.

css link in html

For more effectiveness, use live server extension on vscode.

Top comments (0)

For further actions, you may consider blocking this person and/or reporting abuse

Static Web Apps CLI and Node.js 18: could not connect to API

NestJS tip: type safety on parameter decorators

extracting RGBA values of an Image

Dockerfiles for Node and TypeScript: Slim Containers with Distroless

Andreas Bergström — May 20

🖥Developer💻⌨ || Tech enthusiast and Tech writer 📝|| You can find me on twitter@SampadSarker || Linkedin Profile linkedin.com/in/sampad-sarker || My codepen is codepen.io/sampad-sarker

More from Sampad Sarker

Once suspended, sampadsarker will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, sampadsarker will be able to comment and publish posts again.

Once unpublished, all posts by sampadsarker will become hidden and only accessible to themselves.

If sampadsarker is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Sampad Sarker.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag sampadsarker:

sampadsarker consistently posts content that violates DEV Community’s code of conduct because it is harassing, offensive or spammy.

Unflagging sampadsarker will restore default visibility to their posts.

DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey.

Built on Forem — the open source software that powers DEV and other inclusive communities.

Made with love and Ruby on Rails. DEV Community © 2016 — 2023.

We’re a place where coders share, stay up-to-date and grow their careers.

Источник

Читайте также:  Java create empty array
Оцените статью