Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tailwind css with css modules in next.js

How to config next.js to support Simultaneous tailwind css with css modules? I want tailwindcss wrap whole project:

// /tailwind.scss
:global {
  @import "tailwindcss/base";
  @import "tailwindcss/components";
  @import "tailwindcss/utilities";
}

// /test-module.css
.example {
  font-size: 36px;
}

// /pages/_app.jsx
import '../talwind.scss';
...

And in a sample component:

// /components/my-component.jsx
import css from '../test-module.css';

const Test = () => (
  <div className={`bg-red-500` ${css.example}}>Test Tailwind with CSS</div>
);


like image 349
Masih Jahangiri Avatar asked Oct 26 '19 18:10

Masih Jahangiri


People also ask

Does Next JS support CSS modules?

Next.js supports CSS Modules using the [name].module.css file naming convention. CSS Modules locally scope CSS by automatically creating a unique class name. This allows you to use the same CSS class name in different files without worrying about collisions.

Can you combine CSS with Tailwind?

Using modifiers with custom CSS. Any custom styles you add to Tailwind with @layer will automatically support Tailwind's modifier syntax for handling things like hover states, responsive breakpoints, dark mode, and more. Learn more about how these modifiers work in the Hover, Focus, and Other States documentation.

Which CSS framework is best for next JS?

Tailwind CSS is one of the most famous CSS frameworks out there and is especially used with React. js and Next. js. It is a utility-first CSS framework packed with classes like flex flex-start pt-4 items-center that can be composed to build any design, directly in your markup.


1 Answers

A solution is split webpack style loader. A loader for global css another for css modules loader so webpack loader is looks like below:

{
  test: /\.s?[ac]ss$/,
  exclude: /\.global.css$/,
  use: [
    {
      loader: MiniCssExtractPlugin.loader,
      options: {
        hmr: !isProduction,
        reloadAll: true,
      },
    },
    // 'css-loader',
    {
      loader: 'css-loader',
      options: {
        importLoaders: 1,
        modules: {
          localIdentName: '[name]__[local]___[hash:base64:5]',
        },
      },
    },
    'postcss-loader',
    { loader: 'sass-loader', options: { sourceMap: true } },
  ],
},
{
  test: /\.global.css$/,
  use: [
    {
      loader: MiniCssExtractPlugin.loader,
      options: {
        hmr: !isProduction,
        reloadAll: true,
      },
    },
    'css-loader',
    'postcss-loader',
  ],
},
like image 141
Masih Jahangiri Avatar answered Sep 18 '22 22:09

Masih Jahangiri