Как подключить sass к react
Add Sass to your React App in 2021! Here is how.
Hi 👋🏼 my name is Austin. I am a Full Stack Developer and I enjoy adding Sass to my React applications.
There are a number of benefits to using Sass over vanilla CSS. In this series I will be introducing you to all the ways, Syntactically Awesome Style Sheets, aka “Sass” is better.
But first, in this post, we will get Sass set up in your React app.
If you are reading this, I am assuming you are using create-react-app, you have node installed, you use npm or yarn and you have a basic understanding of your package.json / installing dependencies.
Lets make a brand new React App called sass-blog. (Skip this step if you are adding Sass to an existing React App!)
Next lets install sass and save it to our devDependencies.
This installs the latest version of Sass ( Dart Sass ) and provides us with access to the executable as well as the library. Now we will see “sass” version “^1.32.8” in our package.json file under our devDependencies.
Next in App.js, import ‘./Sass/App.scss’ in place of ‘./App.css’.
Almost all set up! Lets head to our package.json file where we are going to add a script that will tell our app to compile our Sass folder to our Css folder.
Add the following script to your package.json under “scripts”
This is going to allow us to run the command “npm run sass”. It will “watch” all our our Sass files for changes and compile them to our Css folder real time! The “no source map” flag, keeps us from generating the file that shows how the files are mapped together (less clutter).
Finally open up your terminal. You will need two tabs, in one run “npm start” and the other run “npm run sass”.
Congratulations you have the power of Sass set up and you are ready to style your React App!
I hope this helped. If you have a better way to do what we just did, let me know in the comments below. In the upcoming series we will be looking at the different features of Sass and what makes it so awesome! Have a great day and happy coding!
How to add SASS/SCSS to a create-react-app Project
(Note: The latest version of create-react-app has SASS support built in and this guide is not necessary.)
This explains how to add the SASS/SCSS precompiler to an existing create-react-app project. This will work with the regular or Typescript variations of create-react-app, and should work regardless of the numerous webpack config syntax variations out there.
Eject
You’ll need to eject your project if you haven’t already. I’ve done this many times but it can be a big scary step so read here to find out what it means to eject your project. This is necessary in order to manually edit your webpack config files.
Install SASS
The SASS precompiler runs at build time not runtime, therefore we save it with the save-dev switch.
Edit Webpack Config
You’re going to open your dev config file, locate the existing css rule block, duplicate it, and use it as a reference to create a new scss rule block. Leave the existing css rule in there as-is so that your project will work with both SCSS and plain CSS files.
Find file config/webpack.config.dev.js. Look for the css rule block. It will look something like this but not exactly:
Copy and duplicate the whole block and add it right above (before) the existing css block. Edit the new “ test” value to make it scss:
Insert a sass-loader section in the middle of the new rule right after the css-loader section. You’re inserting the three lines in the middle below. The new scss rule will look something like this but not exactly:
It may seem strange to have “ css-loader” inside the scss rule but it’s necessary so that webpack will handle the compiled css properly after its been compiled by scss.
Edit Webpack Config for Prod
Do the same procedure “ Edit Webpack Config” again for file config/webpack.config.prod.js. The existing CSS block will look somewhat different in the prod file but the procedure is basically the same. Follow the existing patterns in the css rule and you’ll be fine.
Now you should have an scss rule and a css rule in each config file. Nothing special to do now other than create SCSS files instead of CSS. You can optionally leave your old CSS files in your project and they will be combined with your SCSS since you have rules for both!
Подключаем Sass к Create-React-App
Недавно, Facebook выпустили фантастический инструмент для создания React приложений на основе набора минимальных и упрямых идей, чтобы помочь начинающим начать изучение React, не беспокоясь за свойственный для него сложный инструментарий. С добавлением команды eject, которая позволяет раскрыть скрипты сборки, настройки и другие файлы работающие за кулисами, create-react-app стал чрезвычайно полезным инструментом, как для начинающих, так и для экспертов.
Для начала, установим и сохраним необходимые инструменты из npm, выполнив следующую команду в корне вашего проекта:
Добавление Sass к вашему create-react-app проекту потребует от вас выполнение команды eject. Так же из корня проекта:
В WebPack, loaders (загрузчики, лоадеры) позволяют разработчикам выполнять «предварительную обработку (pre-process)», перед тем как они потребуются или будут загружены. create-react-app использует множество загрузчиков для обработки различных задач сборки, таких как транспайлинг (transpiling) с помощью babel, автоматическая расстановка префиксов с помощью PostCSS. Для того чтобы подключить Sass к вашему проекту, нужно добавить загрузчик, который может обрабатывать Sass файлы.
Начало блока loaders должно выглядеть примерно вот так:
После начала массива loaders вы можете добавить свой загрузчик. Тот Sass загрузчик который мы установили может обрабатывать как Sass, так и Scss файлы.
Теперь когда Sass загрузчик находится на месте, вы можете использовать Sass файлы. Например, в компоненте App.js, который идёт по умолчанию с create-react-app, вы можете написать:
Обратите внимание на то, что вы также должны переименовать ваш файл App.css в App.sass.
Как подключить Sass к React?
Доброго времени суток, друзья. В данной статье мы подробно разберем, как можно подключить Sass к React. Поймем какую версию Node.js нужно выбрать для корректной работы пакета node-Sass. Важное уточнение, здесь мы не будем рассматривать установку Sass, используя конфиг Webpack, а рассмотрим установку для проекта сгенерированного create-react-app утилитой. Давайте приступим и начнем с определений.
Что такое Sass?
Sass это css препроцессор, позволяющий расширить возможности css путем добавления работы с переменными, вложенностью стилей, миксинами, инлайновыми импортами, изолировать нужные стили. Также Sass имеет много других удобных фишек для работы, которые отсутствуют в нативном css.
Подключаем Sass к React
Для того, чтобы подключить к React проекту предпроцессор Sass достаточно воспользоваться пакетом node-sass. Данный пакет позволяет без дополнительных установок добавить Sass в ваш React проект. Для его установки достаточно воспользоваться командой
В документации рассматривается вариант установки через китайское зеркало, для этого нужно установить глобальный конфиг зеркала с адресом репозитория, а после вызвать саму установку пакета
Выбираем версию node-sass
Важной особенностью данного пакета является его несовместимость со старыми версиями Node.js. Каждая последующая версия node-sass требует новой версии Node.js, без возможности обратной совместимости со старыми.
На официальной странице пакета имеется следующая таблица совместимостей версий.
Прежде чем начать установку убедитесь, что ваша версия Node соответствует устанавливаемой версии пакета. Для этого в консоли вызовите команду
Дале установите пакет, указав совместимую с ней версию Node, например, вашу локальную версию Node v14.14.0, тогда для корректной работы нужно установить версию 4.14 до 5.0 пакета.
Для установки конкретной версии воспользуемся командой
Пример работы с Sass
Для тестирования Sass в React добавим переменную, которой присвоим цвет и укажем ее вместо цвета фона в нашем приложении.
Заключение
Сегодня мы разобрали как можно подключить Sass к React (create-react-app) проекту, посмотрели нюансы, связанные с установкой node-sass и протестировали Sass на примере использования переменных в React приложении. Надеюсь, что данный материал был вам полезен. Учитесь, думайте, пишите код. Удачного кодинга, друзья!
Подписывайтесь на наш канал в Telegram и на YouTube для получения самой последней и актуальной информации.
how to include sass file in reactjs
I use browserify to transform my code now getting error while the sass files were getting imported
Can any one help me to sort this issue how to use and integrate
3 Answers 3
With the latest version of create-react-app you don’t have to eject your react app to add sass support.
Just add node-sass to your project:
YARN yarn add node-sass
And now you can import sass files in your react components. Check the official documentation here
Recently, the React team and a number of contributors released a fantastic tool for creating configuration-less React applications based on a set of minimal ideas to help beginners dive into building React applications without having to worry about tooling a beginner may find daunting.
There are two ways you can add SASS or SCSS to a create-react-app project.
Install With: NPM Scripts
This method is simpler and can work without ejecting your project. If you prefer not to eject, use this method. Click here to view the project’s official guide on how to install Sass or Scss using NPM Scripts.
Install With: Webpack
This method is not as simple, but more extensible and automated. Unfortunately, this method requires ejection. Ejecting a project, although useful in many advanced cases, means that futures updates to create-react-app will not be easy for you to get.
Before starting, install and save the necessary tools from your packager of choice by running one of the following commands in your project directory.
Adding sass or scss to your create-react-app project will first require you to eject, which can be done by executing the following command in your project’s base directory.
Once ejection has completed, locate the config folder which holds, among other things, two webpack configuration files. Each of these configuration files corresponds to a different environment — development or production. Enter the development configuration file webpack.config.dev.js and locate the loaders block within the modules block.
In webpack, loaders allow the developer to “pre-process” files as they are required/loaded. Create react app uses multiple loaders to handle various build tasks such as transpiling with babel, prefixing with PostCSS, or allowing the importing of assets. To add Sass or Scss to this project, you will be adding a loader that can process Sass and Scss files.
The beginning of the loaders block, before any modification, should look something like the following code (Exact code may change in future versions of CRA).
After the beginning of the loaders array, you can add your own loader for Sass and Scss. The “sass” loader featured in the loaders array in the code below is able to process both Sass and Scss files.
Important: In newer versions of create-react-app, if you see an exclude array in your webpack config, you need to add the following lines to