Monday, May 30, 2022
HomeWordPress DevelopmentSetup Tailwind CSS in a React mission configured from scratch with Webpack...

Setup Tailwind CSS in a React mission configured from scratch with Webpack | a step-by-step information


Tailwind CSS is a utility first CSS framework that enables builders to design customized internet parts with out switching to a CSS file. On this information I’ll stroll you step-by-step by means of the method of organising Tailwind CSS in a React mission configured from scratch (with out utilizing create-react-app). We’ll set up and configure Tailwind CSS and PostCSS, combine them with CSS and Webpack and eventually add Tailwind Types in our React codebase. (a lot enjoyable)

Consideration!
This text is a fourth half within the collection of organising a React setting from scratch. All through this collection we have now setup React from scratch, put in ESLint, Prettier and husky, configured testing setting with Jest and React Testing Library and On this half we are going to base on that progress and add Tailwind CSS for styling.

You will discover the beginning code from this GitHub repo

Conditions

  • I count on that you’ve got a React mission configured from scratch for reference you can begin from the Repo offered above, however you possibly can nonetheless observe alongside in case you want this text for some other causes

  • VS code and Node put in in your machine.

let’s have an summary about instruments we will probably be utilizing.

Why Tailwind CSS?
Tailwind CSS is self-described as a utility first CSS framework. Somewhat than specializing in the performance of the merchandise being styled, Tailwind is centered round the way it must be displayed. With

Quickly construct trendy web sites with out ever leaving your HTML.

With Tailwind you possibly can type instantly out of your html or jsx utilizing their predefined lessons to allow you write CSS in a extra elegant and quicker method. This doesn’t suggest you must all the time use Tailwind as it may be an overkill for small initiatives and requires a good understanding of CSS. Be taught extra about Tailwind CSS HERE.

PostCSS
PostCSS is a device for reworking kinds with JavaScript plugins. and these plugins can enhance your kinds in many alternative methods. as an example the way in which we have now ESLint for JavaScript PostCSS lets you use plugins that may detect errors in your CSS code, or use subsequent technology CSS syntax (kinda like Babel for CSS) and rather more. Tailwind CSS is one in every of these plugins subsequently to make use of Tailwind we’d like PostCSS put in.
Be taught extra about PostCSS HERE

We’ll come again to those instruments in additional particulars later. Let’s get began.

Observe the next steps

1. Putting in Tailwind dependencies
Run the next command to Set up Tailwind CSS (as a dev dependencies).

npm set up tailwindcss autoprefixer --save-dev

// utilizing yarn

yarn add tailwindcss autoprefixer --dev

- `tailwindcss`: is a core package deal that installs Tailwind CSS
- `autoprefixer`: It's a PostCSS plugin that Tailwind CSs makes use of to routinely provides [vendor prefixes](https://developer.mozilla.org/en-US/docs/Glossary/Vendor_Prefix) to write down kinds supported by all browsers
Enter fullscreen mode

Exit fullscreen mode

2. Configuring Tailwind CSS
within the root folder create a file named tailwind.config.cjs which is able to maintain your configurations and customizations for Tailwind,
we identify it .cjs as we we will probably be utilizing require syntax in ES module

within the tailwind.config.cjsadd the next code

module.exports = {
    content material: ['./src/**/*.{js,jsx}', './public/index.html'],
    theme: {
        prolong: {
            colours: {
                main: '#1B73E8',
            },
        },
    },
    plugins: [],
};

Enter fullscreen mode

Exit fullscreen mode

What does the code imply?

  • We’re exporting this configurations utilizing module.exports

  • The content material subject is essential because it specifies file varieties that we’ll add Tailwind code in. In our instance we’re telling Tailwind to look into all information within the src folder with .jsand jsx extensions and the index.html within the public folder.

  • Within the theme folder we are going to put our customizations by extending default configurations. in our instance we’re setting the colour main to '#1B73E8' code so anytime we write main as a coloration Tailwind will insert it is worth.

  • The plugins subject is the place we put our plugins that we wish to use with Tailwind we aren’t utilizing plugins so the array is empty

Be aware that there extra configurations and you’ll customise it as you need. Be taught extra about tailwind configurations HERE

3. Set up PostCSS dependecies
Run the next command to Set up PostCSS (as a dev dependency).

npm set up postcss --save-dev

// utilizing yarn

yarn add postcss  --dev
Enter fullscreen mode

Exit fullscreen mode

4. Configuring PostCSS
within the root folder create a file named postcss.config.js which is able to maintain your configurations for PostCSS, and add the next code

const tailwindcss = require('tailwindcss');
const autoprefixer = require('autoprefixer');

module.exports = {
    plugins: [tailwindcss('./tailwind.config.cjs'), autoprefixer],
};
Enter fullscreen mode

Exit fullscreen mode

What does the code imply?

  • We’re importing Tailwind css and autoprefixer packages we put in earlier utilizing require you should use import if you’re utilizing ES modules
  • within the configurations exports we’re mentioning plugins that PostCSS will use whereas going by means of our CSS information. in our case we’re specifying tailwind and autoprefixer.
    for tailwind we specified the trail for our tailwind configuration file (tailwind.config.cjs). Be taught extra about PostCSS configurations HERE

5. Inject Tailwind within the CSS file
We Put in and configured Tailwind CSS and PostCSS in our codebase however how can we add Tailwind CSS in our React parts. as talked about above with Tailwind makes use of predefined lessons that corresponds to precise CSS properties. technically we nonetheless have to have css information even when we aren’t instantly writing CSS.

  • within the src folder the place we have now App.jsx (created in earlier articles) create a file named app.css which will probably be our primary CSS file.
  • within the app.css add the next code
@tailwind base;
@tailwind parts;
@tailwind utilities;
Enter fullscreen mode

Exit fullscreen mode

this can inject tailwind kinds in our css file utilizing tailwind directives. study extra about Tailwind directives HERE

  • Lastly import that CSS file within the entry file on your React mission. on this instance I’ll put it within the App.jsx file.

your app.jsx ought to seem like this

import React from 'react';
import './app.css';

operate App() {
    return <h1>Hiya world! I am utilizing React</h1>;
}

export default App;
Enter fullscreen mode

Exit fullscreen mode

6. Assist CSS with Webpack
Within the first article configured our react mission with Webpack for bundling all information right into a single file.
The factor with Webpack is that it would not help information out of the field each time we add new kinds of information we have to make Webpack acknowledge them utilizing it is loaders and we did the identical assume for .js and jsx information within the first article.

we simply added a .css file subsequently we have to set up loaders for CSS

Run the next command to Set up Webpack CSS loaders (as a dev dependencies).

npm set up type-loader css-loader postcss-loader

// utilizing Yarn

yarn add type-loader css-loader postcss-loader --dev
Enter fullscreen mode

Exit fullscreen mode

style-loader: utilized by webpack to inject CSS into the DOM.
css-loader: utilized by webpack to interprets and resolve imports in CSS
postcss-loader: utilized by webpack to course of PostCSS as we put in PostCSS earlier.

After putting in these loader we have to add them in our webpack.config.js by including a brand new rule within the modules object

{
  check: /.css$/i,
  use: ['style-loader', 'css-loader', 'postcss-loader'],
},
Enter fullscreen mode

Exit fullscreen mode

  • Right here we’re telling Webpack that when it encounter a file with .css extension it ought to use the loaders we put in to bundle them.

lastly your full webpack.config.js ought to seem like the next

const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
    entry: 'index.jsx',
    mode: 'growth',
    output: {
        path: path.resolve(__dirname, './dist'),
        filename: 'index_bundle.js',
    },
    goal: 'internet',
    devServer: {
        port: '5000',
        static: {
            listing: path.be a part of(__dirname, 'public'),
        },
        open: true,
        sizzling: true,
        liveReload: true,
    },
    resolve: {
        extensions: ['.js', '.jsx', '.json'],
    },
    module: {
        guidelines: [
            jsx)$/,
                exclude: /node_modules/,
                use: 'babel-loader',
            ,
            {
                test: /.css$/i,
                use: ['style-loader', 'css-loader', 'postcss-loader'],
            },
        ],
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.join(__dirname, 'public', 'index.html'),
        }),
    ],
};

Enter fullscreen mode

Exit fullscreen mode

7. Fashion your React parts with Tailwind
After these configurations you must have the ability to write tailwind code in any of your React parts with no points.
within the app.jsx add the next code

import React from 'react';
import './app.css';

operate App() {
    return <h1 className="text-primary text-4xl font-bold">Hiya world! I am utilizing React</h1>;
}

export default App;

Enter fullscreen mode

Exit fullscreen mode

we simply added tailwind class to alter our textual content the main coloration we configured in tailwind.config.cjs, enhance font measurement made textual content daring

after operating the app with npm begin the web page ought to seem like the next

tailwind with react

There you have got it! that is the way you configure Tailwind CSS in a react mission configured from scratch with Webpack. yow will discover code for this text on this GitHub Repo

What about assessments?
Presently in case you attempt to run assessments (npm check) they may fail as imported a CSS file and by default Jest would not perceive CSS information subsequently we might want to mock them and this would be the matter for the following article…

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments