logo
  • Guide
  • Config
  • Plugin
  • API
  • Examples
  • Community
  • Modern.js 2.x Docs
  • English
    • 简体中文
    • English
    • Start
      Introduction
      Quick Start
      Upgrading
      Glossary
      Tech Stack
      Core Concept
      Page Entry
      Build Engine
      Web Server
      Basic Features
      Routes
      Routing
      Config Routes
      Data Solution
      Data Fetching
      Data Writing
      Data Caching
      Rendering
      Server-Side Rendering
      Streaming SSR
      Rendering Cache
      Static Site Generation
      Render Preprocessing
      Styling
      Styling
      Use CSS Modules
      Using CSS-in-JS
      Using Tailwind CSS
      HTML Template
      Import Static Assets
      Import JSON Files
      Import SVG Assets
      Import Wasm Assets
      Debug
      Data Mocking
      Network Proxy
      Using Rsdoctor
      Using Storybook
      Testing
      Playwright
      Vitest
      Jest
      Cypress
      Path Alias
      Environment Variables
      Output Files
      Deploy Application
      Advanced Features
      Using Rspack
      Using BFF
      Basic Usage
      Runtime Framework
      Extend BFF Server
      Extend Request SDK
      File Upload
      Cross-Project Invocation
      Optimize Page Performance
      Code Splitting
      Inline Static Assets
      Bundle Size Optimization
      React Compiler
      Improve Build Performance
      Browser Compatibility
      Low-Level Tools
      Source Code Build Mode
      Server Monitor
      Monitors
      Logs Events
      Metrics Events
      Internationalization
      Basic Concepts
      Quick Start
      Configuration
      Locale Detection
      Resource Loading
      Routing Integration
      API Reference
      Advanced Usage
      Best Practices
      Custom Web Server
      Topic Detail
      Module Federation
      Introduction
      Getting Started
      Application-Level Modules
      Server-Side Rendering
      Deployment
      Integrating Internationalization
      FAQ
      Dependencies FAQ
      CLI FAQ
      Build FAQ
      HMR FAQ
      Deprecated
      📝 Edit this page
      Previous pageStylingNext pageUsing CSS-in-JS

      #Use CSS Modules

      CSS Modules allows us to write CSS code in a modular way, and these styles can be imported and used in JavaScript files. Using CSS Modules can automatically generate unique class names, isolate styles between different modules, and avoid class name conflicts.

      Modern.js supports CSS Modules by default, you don't need to add additional configuration. Our convention is to use the [name].module.css filename to enable CSS Modules.

      The following style files are considered CSS Modules:

      • *.module.scss
      • *.module.less
      • *.module.css

      #Example

      • Write style:
      /* button.module.css */
      .error {
        background: red;
      }
      • Using styles:
      // Button.tsx
      import React, { Component } from 'react';
      // import style file
      import styles from './button.module.css';
      
      export default () => {
        return <button className={styles.error}>Error Button</button>;
      };

      #Enable CSS Modules for all CSS files

      By default, only files ending in *.module.css are treated CSS Modules.

      If you want to treat all CSS files in the source directory as CSS Modules, you can enable the output.disableCssModuleExtension config, for example:

      export default {
        output: {
          disableCssModuleExtension: true,
        },
      };

      When set, the following two files are treated as CSS Modules:

      import styles1 from './foo.module.css';
      import styles2 from './bar.css';
      Tip

      We do not recommend enabling this config, because after enabling disableCssModuleExtension, CSS Modules files and ordinary CSS files cannot be clearly distinguished, which is not conducive to long-term maintenance.

      #Enable CSS Modules for the specified style file

      By default, only files ending in *.module.css are treated CSS Modules.

      If you want to enable CSS Modules only for specified style files, you can configure output.cssModules, for example:

      export default {
        output: {
          cssModules: {
            auto: resource => {
              return resource.includes('.module.') || resource.includes('shared/');
            },
          },
        },
      };

      #Add Type Declaration

      When you import CSS Modules in TypeScript code, TypeScript may prompt that the module is missing a type definition:

      TS2307: Cannot find module './index.module.css' or its corresponding type declarations.

      To fix this, you need to add a type declaration file for the CSS Modules, please create a src/global.d.ts file, and add the corresponding type declaration:

      src/global.d.ts
      declare module '*.module.css' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.module.scss' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.module.sass' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.module.less' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.module.styl' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }

      If you enabled the disableCssModuleExtension config, you also need to add the following types:

      src/global.d.ts
      declare module '*.css' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.scss' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.sass' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.less' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }
      
      declare module '*.styl' {
        const classes: { readonly [key: string]: string };
        export default classes;
      }

      After adding the type declaration, if the type error still exists, you can try to restart the current IDE, or adjust the directory where global.d.ts is located, making sure the TypeScript can correctly identify the type definition.

      #Generate exact type definitions

      Although the above method can provide the type of CSS Modules, it cannot accurately prompt which classNames are exported by a certain CSS file.

      Modern.js supports generating accurate type declarations for CSS Modules, you only need to enable the output.enableCssModuleTSDeclaration config, and then execute the build, Modern.js will generate type declaration files for all CSS Modules.

      export default {
        output: {
          enableCssModuleTSDeclaration: true,
        },
      };

      #Example

      For example, there are two files src/index.ts and src/index.module.scss under a certain folder:

      src/index.ts
      import styles from './index.module.scss';
      
      export default () => {
        <div>
          <div className={styles.pageHeader}>Page Header</div>
        </div>;
      };
      src/index.module.scss
      .page-header {
        color: black;
      }

      After executing the build, the src/index.module.scss.d.ts type declaration file will be automatically generated:

      src/index.module.scss.d.ts
      // This file is automatically generated.
      // Please do not change this file!
      interface CssExports {
        'page-header': string;
        pageHeader: string;
      }
      export const cssExports: CssExports;
      export default cssExports;

      Then open the src/index.ts file again, you will see that the styles object already has a exact type.

      #Related configuration

      In the above example, src/index.module.scss.d.ts is generated by compilation, you can choose to commit them to the Git repository, or you can choose to ignore them in the .gitignore file:

      # Ignore auto generated CSS declarations
      *.module.css.d.ts
      *.module.sass.d.ts
      *.module.scss.d.ts
      *.module.less.d.ts
      *.module.styl.d.ts

      In addition, if the generated code causes ESLint to report errors, you can also add the above configuration to the .eslintignore file.