How to Use SCSS with Tailwind CSS in Next.js

Cedrick CaceresAugust 7, 2024
CSSSass

Step 1: Create a New Next.js Project

Start by creating a Next.js project in your desired directory and opening the terminal within. In the terminal, you can follow the following code:

npx create-next-app@latest your-app-name

After that, it will start to install your project. You'll be prompted to install some dependencies or packages that your project may require. In particular, you will be asked regarding Tailwind CSS:  Would you like to use Tailwind CSS? Choose Yes by simply pressing the right arrow of your keyboard.


After waiting a few minutes, the project will be installed. You can then navigate to that project directory by typing the following in the terminal:

cd your-app-name

You can then run the command:

npm run dev 

Do not close the terminal yet. Hover your mouse arrow to localhost and hold CTRL and left click. This will redirect you to the browser with the Next.js page default.

Step 2: Installing Sass

Open the terminal again and type:

npm install sass

This will install the sass package SCSS (Sass) in your Next.js project.

Step 3: Create Resources Folder for Better Organization

When the sass package is installed, you can now open your project by launching it in your desired code editor, such as Visual Studio Code, Sublime Text, or any other text editor you prefer. Navigate to your project's directory, and you’ll see the default file structure generated by Next.js.


If you installed your Next.js project with a src/ directory, the structure of your project will have the src directory at the root level, containing the main codebase for your application. Create a directory inside the src folder and name it with resource. Create a styles.scss file inside and import tailwind directives:

@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

In your root component, typically layout.js or _app.js, you can import your global SCSS file to ensure that Tailwind CSS and any custom styles are applied across your entire application.


For App Router in src/app/layout.js:

// src/app/layout.js 
import '../resource/styles.scss'; // Adjust path if necessary 

export default function RootLayout({ children }) { 
  return ( 
  <html lang="en"> 
    <body>{children}</body> 
  </html> 
  ); 
}

For Pages Router in src/pages/_app.js:

import '../styles/styles.scss'; // Adjust path if necessary 

function MyApp({ Component, pageProps }) { 
  return <Component {...pageProps} />; 
} 
export default MyApp;

And that's it! You can now see the design of your Next.js project by creating and styling components using Tailwind CSS and SCSS. Simply build your components or pages, and the styles will be applied as you’ve configured them. 

0 likes

Comments