Sass and css modules

How to Use SCSS With CSS Modules in Next.js

You should already have a working Next.js project. If you need to set up one, here’s the command to get started.

Step 1 — Installing Sass

Although Next.js has great built-in CSS support, it doesn’t work with Sass out of the box.

You need to install sass package and Next.js will take care of the rest.

If your project is already running from npm run dev , you might need to restart it.

Now you should be ready to start styling with Sass.

Step 2 — Setting up Global Styles

Let’s make a stylesheet that you can use to apply global styles to your entire project.

Create a file global.scss in src/styles and add your site-wide styles.

// src/styles/global.scss  *   box-sizing: border-box; >  body   color: #303335; > 

Now, open pages/_app.js and import the global.scss stylesheet there.

// src/pages/_app.js  import '../src/styles/global.scss'; 

If you don’t have a custom _app.js file, you can create one yourself. Here’s the default template that should do the trick.

import '../src/styles/global.scss';  function MyApp( Component, pageProps >)   return Component . pageProps> />; >  export default MyApp; 

You can read more about customizing this file in Next.js documentation.

Step 3 — Using CSS Modules

You can simply write SCSS in your CSS modules and Next.js will do its magic to make it work.

Something useful you can do is creating a file to define all your SCSS variables.

// src/styles/_var.scss  $color-blue: #105cc0; 

You can then import that file in other SCSS files, including CSS modules.

// src/components/Hello.module.scss @import '../styles/var';  .helloText   color: $color-blue;  font-weight: 700; > 

Make sure to use camel case when naming your classes. Use helloText and not hello-text .

To use CSS module styles in components, you have to reference the class name as an object property. And JavaScript doesn’t like dashes (-) in property names.

// src/component/Hello.jsx  import styles from './Hello.module.scss';  const Hello = ( message >) =>   return p className=styles.helloText>>Hello, message>p>; >;  export default Hello; 

(Optional) Step 4 — Setting up Import Aliases

When importing styles from other files in Sass, you can avoid typing long relative import paths with aliases.

// src/components/deeply/nested/Component.module.scss  // Regular import @import '../../../styles/var';  // Using an alias @import '@styles/var'; 

To achieve this, you need to configure webpack to resolve @styles as an actual path.

Open next.config.js and add the following config.

const path = require('node:path');  const nextConfig =   webpack(config)   config.resolve.alias =   . config.resolve.alias,  '@styles': path.resolve(__dirname, 'src/styles'),  >;  return config;  >, >;  module.exports = nextConfig; 

Since you are overriding the default config.resolve.alias , you need to spread the original aliases first. Next.js relies on some aliases internally, so you need to preserve them.

After that is done, you can go ahead and add your own aliases.

You can now use SCSS inside CSS Modules with import aliases in your Next.js project.

Источник

How to Use Sass with CSS Modules in Next.js

Colby Fayock

Colby Fayock

How to Use Sass with CSS Modules in Next.js

Next.js gives us CSS Modules by default, providing benefits like scoped styles and focused development in our app. How can we give our Next.js CSS superpowers with Sass?

nextjs-app

  • What are CSS Modules?
  • What is Sass?
  • What are we going to build?
  • Step 0: Creating a new Next.js app
  • Step 1: Installing Sass in a Next.js app
  • Step 2: Importing Sass files into a Next.js app
  • Step 3: Using Sass variables in a Next.js app
  • Step 4: Using Sass mixins with global imports in Next.js

If this is your first time creating a new Next.js app, have a look around! It comes with a basic homepage as well as two CSS files:

Here we’ll be focusing on the home file. If you look inside pages/index.js, there, you’ll see that we’re importing the home file, making those styles available.

Next.js has CSS Modules built in by default. This means that when we import our home styles file, the CSS classes are added to the styles object, and we apply each of those class names to the React elements from that object, such as:

That means that our styles are scoped to that single page.

To learn more about CSS Modules or the built-in support in Next.js, you can check out the following resources:

Step 1: Installing Sass in a Next.js app

While Next.js comes with some good built-in CSS support, it doesn’t come with Sass completely built in.

Luckily, to get Sass up and running inside of our Next.js app, all we need to do is install the Sass package from npm, which will let Next.js include those files in its pipeline.

To install Sass, run the following inside of your project:

And if we start back up our development server and reload the page, we’ll actually notice that nothing has happened yet, which is a good thing!

But next we’ll learn how to take advantage of our CSS superpowers.

Step 2: Importing Sass files into a Next.js app

Now that Sass is installed, we’re ready to use it.

In order you use any Sass-specific features though, we’ll need to use Sass files with either the .sass or .scss extension. For this walkthrough, we’re going to use the SCSS syntax and the .scss extension.

To get started, inside of pages/index.js , change the import of the styles object at the top of the page to:

import styles from '../styles/Home.module.scss'

And once the page reloads, as we probably expect, the page is actually broken.

nextjs-error-import

To fix this, rename the file:

The difference is we’re changing the file extension from .css to .scss .

Once the page reloads, we’ll see that our Next.js site is loading and is back ready for action!

nextjs-app-title

Note: We’re not going to cover the global styles file here – you can do the same thing by renaming the global styles file and updating the import inside of /pages/_app.js

Next, we’ll learn how to use Sass features for our Next.js app.

Step 3: Using Sass variables in a Next.js app

Now that we’re using Sass in our project, we can start using some of the basic features like variables.

To show how this works, we’re going to update the blue inside of our app to my favorite color, purple!

At the top of /styles/Home.module.css , add the following:

The color #0070f3 is what Next.js uses by default in the app.

Next, update each location that uses that color in our home CSS file to our new variables, such as changing:

If we refresh the page, nothing should change.

nextjs-app-1

But now because we’re using a variable to define that color, we can easily change it.

At the top of the page, change the $color-primary variable to purple or whatever your favorite color is:

And when the page reloads, we can see that our colors are now purple!

nextjs-app-purple

Variables are just the start to the superpowers Sass gives our CSS, but we can see that they allow us to easily manage our colors or other values throughout our application.

Step 4: Using Sass mixins with global imports in Next.js

One of the other many features of Sass is mixins. They give us the ability to create function-like definitions, allowing us to configure rules that we can repeat and use throughout our app.

In our example, we’re going to create a new mixin that allows us to create responsive styles using a media query throughout our app. While we can already do that with a media query alone, using a mixin allows us to use a single definition, keeping that consistent and allowing us to manage that responsive definition from one place.

Because this mixin is something we want to use throughout our entire application, we can also use another feature of Sass, which is the ability to import files.

To get started, create a new file under the /styles directory:

We’re using an underscore in front of our filename to denote that it’s a partial.

Next, inside of our /styles/Home.module.scss file, let’s import that new file:

Once the page reloads, we’ll notice nothing changed.

If we lookout the bottom of Home.module.scss , we’ll see that we’re using a media query to make the .grid class responsive. We’re going to use that as a basis for our mixin.

Inside of _mixins.scss , add the following:

Note: while we probably can come up with a better name for this mixin than desktop, we’ll use that as the basis of our example.

The @content means that any time we use our desktop mixin, it will include the nested content in that location.

To test this out, back in our Home.module.css file, let’s update our .grid snippet:

If we open our app back up and shrink the browser window, we can see that we still have our responsive styles!

nextjs-responsive-styles

We can even take this a step further. Sass allows you to nest styles. For instance, instead of writing:

We can include that img definition right inside of the original .footer definition:

That img definition will compile to .footer img , just the same as if it was written in standard CSS.

So with that in mind, we can use the same concept and move our desktop mixin into our original .grid class:

And if you notice, because we’re inside of the .grid class already, we can remove that from inside of the mixin, as it will already be applied.

This allows for much easier organization of our responsive styles.

Finally, if we look back at our app, we’ll notice that still, nothing has changed, which means we’re successfully using our Sass mixin.

nextjs-responsive-styles-1

What else can we do with Sass and Next.js?

We’re only scratching the surface here with Sass. Because our CSS modules now have the power of Sass, we have a ton of capabilities that don’t come by default with CSS.

Color Functions

Sass has a ton of functions built in that allow us to manipulate colors, mixing and matching shades much more easily.

Two that I use often are darken and lighten, that allow you to take a color and change the shade.

Custom Functions

While mixins seem like functions, we can define true functions in Sass that allow us to perform complex operations and produce values based on an input.

Other Value Types

While most of the time with CSS we’re using strings or numbers, we saw that a simple extension of that is the ability to use variables.

In addition to variables, Sass gives us more value types like Maps, which function sort of like an object, and Lists, which are kind of like arrays.

More

There are a ton of features available in Sass and lots of articles that cover the most used features. Take some time to explore the documentation and find what’s out there!

Источник

Читайте также:  Linking folders in html
Оцените статью