close
  • English
  • CSS

    Rslib provides out-of-the-box support for CSS, including CSS Modules, CSS preprocessors, PostCSS, CSS inlining, Lightning CSS, and CSS compression.

    Rslib also provides several configurations to customize CSS file processing.

    Import CSS

    You can import CSS files directly in JavaScript files.

    src/index.js
    import './index.css';

    You should note that the default value of Rslib's output.target is 'node'. If you need to handle CSS styles, you need to set it to 'web'.

    rslib.config.ts
    export default {
      output: {
        target: 'web',
      },
    };

    When format is 'cjs' or 'esm', Rslib will apply different processing methods to CSS based on the bundle configuration.

    Bundle mode

    In bundle mode (default behavior), Rslib will bundle the CSS into a separate file and will not preserve the import statement referencing the CSS in the output JavaScript file.

    This is a common practice for community library development, which is friendlier to Server-Side Rendering (SSR) and avoids parsing errors caused by loading CSS files in the Node.js environment. Furthermore, for upstream applications using the library, on-demand style importing can be achieved through relevant plugins or configurations, such as Rsbuild's source.transformImport.

    If you want to preserve the import statement referencing the CSS, you can use the following methods:

    1. Use banner: Configure banner.js to add import './index.css'; to the top of the output JavaScript file.
    rslib.config.ts
    export default {
      lib: [
        {
          banner: {
            js: "import './index.css';",
          },
        },
      ],
    };

    For more complex scenarios, such as when code splitting generates multiple chunk files, you can use Rspack's BannerPlugin to precisely control which modules need to add a banner, avoiding adding it to all chunks.

    rslib.config.ts
    export default {
      lib: [
        {
          tools: {
            rspack: {
              plugins: [
                new rspack.BannerPlugin({
                  banner: "import './index.css';",
                  raw: true,
                  test: /^index\.js$/,
                }),
              ],
            },
          },
        },
      ],
    };
    1. Inline styles: Enable output.injectStyles to inject CSS directly into the JavaScript runtime.

    2. Use bundleless mode: Set bundle to false to preserve the source code file structure and reference relationships.

    Bundleless mode

    In bundleless mode (bundle set to false), Rslib will preserve the source code file structure and reference relationships. This means that the import statement referencing the CSS will be preserved in the output JavaScript file. This method is friendlier to build tools and facilitates Tree Shaking and on-demand importing of styles.

    Here is an example usage, assuming the source code is as follows:

    src/index.ts
    src/index.css
    import './index.css';
    export const component = () => {};

    Based on the output structure configuration in the config file, the output will be as follows:

    bundle
    bundleless
    dist/index.mjs
    dist/index.css
    const component = () => {};
    export { component };

    CSS Modules

    Rslib supports CSS Modules by default without 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.css
    • *.module.less
    • *.module.sass
    • *.module.scss
    • *.module.styl
    • *.module.stylus

    Read the CSS Modules chapter to understand the complete usage of CSS Modules.

    Assuming the source code is as follows:

    src/index.ts
    src/index.module.css
    import styles from './index.module.css';
    
    console.log(styles.title);

    The output will be as follows:

    bundle
    bundleless
    dist/index.mjs
    dist/index.css
    const index_module = {
      title: 'title-aQjbKQ',
    };
    console.log(index_module.title);

    CSS preprocessors

    Rslib supports popular CSS preprocessors through plugins, including Sass, Less, and Stylus. See how to use them:

    Taking the Sass plugin as an example, you can install the plugin via the following command:

    npm
    yarn
    pnpm
    bun
    deno
    npm add @rsbuild/plugin-sass -D

    Then register the plugin in the rslib.config.ts file:

    rslib.config.ts
    import { pluginSass } from '@rsbuild/plugin-sass';
    
    export default {
      plugins: [pluginSass()],
    };

    After registering the plugin, you can import *.scss, *.sass, *.module.scss, or *.module.sass files in your code without adding other configurations.

    PostCSS

    Rslib supports transforming CSS code through PostCSS. You can configure PostCSS in the following ways:

    Configuration file

    Rslib uses postcss-load-config to load the PostCSS configuration file in the root directory of the current project, such as postcss.config.cjs:

    postcss.config.cjs
    module.exports = {
      plugins: {
        'postcss-px-to-viewport': {
          viewportWidth: 375,
        },
      },
    };

    postcss-load-config supports multiple file formats, including but not limited to the following file names:

    • postcss.config.js
    • postcss.config.mjs
    • postcss.config.cjs
    • postcss.config.ts
    • ...

    tools.postcss

    You can also configure the postcss-loader through tools.postcss option, which supports modifying the built-in configuration through a function, for example:

    rslib.config.ts
    export default {
      tools: {
        postcss: (opts) => {
          const viewportPlugin = require('postcss-px-to-viewport')({
            viewportWidth: 375,
          });
          opts.postcssOptions.plugins.push(viewportPlugin);
        },
      },
    };

    Configuration priority

    • When you configure both the postcss.config.js file and the tools.postcss option, both will take effect, and the tools.postcss option will take precedence.
    • If there is no postcss.config.js file in the project and the tools.postcss option is not configured, Rslib will not register postcss-loader.

    Tailwind CSS

    Tailwind CSS v4

    Using the Rsbuild plugin

    We recommend using the @rsbuild/plugin-tailwindcss plugin to integrate Tailwind CSS v4 in Rslib.

    1. Install @rsbuild/plugin-tailwindcss and tailwindcss packages:
    npm
    yarn
    pnpm
    bun
    deno
    npm add @rsbuild/plugin-tailwindcss tailwindcss -D
    1. Register the plugin in the rslib.config.ts file:
    rslib.config.ts
    import { pluginTailwindcss } from '@rsbuild/plugin-tailwindcss';
    
    export default {
      plugins: [pluginTailwindcss()],
    };
    1. Add an @import to your CSS entry file that imports Tailwind CSS.
    src/index.css
    @import 'tailwindcss';
    Tip

    Tailwind CSS v4 cannot be used with CSS preprocessors like Sass, Less, or Stylus. You need to place the @import 'tailwindcss'; statement at the beginning of your .css file, see Tailwind CSS - Compatibility for more details.

    1. Use Tailwind's utility classes in any component or HTML, for example:
    <h1 class="text-3xl font-bold underline">Hello world!</h1>

    For more usage, please refer to the @rsbuild/plugin-tailwindcss documentation.

    Using the PostCSS plugin

    Rslib has built-in support for PostCSS, so projects that already have a PostCSS setup can install tailwindcss and @tailwindcss/postcss to integrate Tailwind CSS:

    npm
    yarn
    pnpm
    bun
    deno
    npm add tailwindcss @tailwindcss/postcss -D

    You can register the Tailwind CSS PostCSS plugin through a PostCSS configuration file or tools.postcss.

    postcss.config.mjs
    export default {
      plugins: {
        '@tailwindcss/postcss': {},
      },
    };

    Tailwind CSS v3

    Refer to Use Tailwind CSS v3.

    Inline CSS files

    By default (when bundle is true), Rslib will extract CSS into a separate .css file and output it to the dist directory.

    To inline styles into your JS file, set output.injectStyles to true to disable CSS extraction logic. When the JS file is requested by the browser, JS dynamically inserts the <style> tag into the HTML to load the CSS styles.

    rslib.config.ts
    export default {
      output: {
        injectStyles: true,
      },
    };

    This will increase the size of your JS Bundle, so it is usually not recommended to disable the CSS extraction.

    Import from node_modules

    Rslib supports importing CSS files from node_modules.

    • Import in a JS file:
    src/index.js
    /* Import normalize.css */
    /* https://github.com/necolas/normalize.css */
    import 'normalize.css';
    • Import in a CSS file:
    src/index.css
    @import 'normalize.css';
    
    body {
      /* */
    }
    • In Sass and Less files, it is also allowed to add the ~ prefix to resolve style files in node_modules. However, this is a deprecated feature and it is recommended to remove the ~ prefix from the code.
    src/index.scss
    @import '~normalize.css';

    Query parameters

    Info

    Query parameters only take effect when bundle is set to true.

    inline

    Rslib supports importing compiled CSS files as strings in JavaScript by using the ?inline query parameter.

    import inlineCss from './style.css?inline';
    
    console.log(inlineCss); // Compiled CSS content

    Using import "*.css?inline" has the following behaviors:

    • Get the compiled text content of the CSS file, processed by Lightning CSS, PostCSS and CSS preprocessors
    • The content will be inlined into the final JavaScript bundle
    • No separate CSS file will be generated
    Tip

    Sass, Less, and Stylus plugins also support the ?inline query parameter.

    raw

    Rslib supports importing raw CSS files as strings in JavaScript by using the ?raw query parameter.

    src/index.js
    import rawCss from './style.css?raw';
    
    console.log(rawCss); // Output the raw content of the CSS file

    Using import "*.css?raw" has the following behaviors:

    • Get the raw text content of the CSS file, without any preprocessing or compilation
    • The content of the CSS file will be inlined into the final JavaScript bundle
    • No separate CSS file will be generated
    Tip

    Sass, Less, and Stylus plugins also support the ?raw query parameter.

    Lightning CSS

    Tip

    Lightning CSS is a high-performance CSS parser, transformer and minifier written in Rust. It supports parsing and transforming many modern CSS features into syntax supported by target browsers, and delivers better compression ratios.

    Rslib uses Rspack's built-in lightningcss-loader to transform CSS code. It automatically reads the syntax configuration in the project and converts CSS code to syntax supported by target browsers.

    For more information, see Lightning CSS.

    CSS minification

    Rslib disables CSS minification by default (output.minify.css is false by default).

    If you need to enable CSS minification, you can set output.minify.css to true via the output.minify option. Rslib will enable Rspack's built-in LightningCssMinimizerRspackPlugin to minify CSS assets.

    Note

    Note that the output.minify option you configure will completely override Rslib's default configuration. See the output.minify documentation for more details.

    Additionally, you can use @rsbuild/plugin-css-minimizer to customize the CSS minimizer, switching to cssnano or another CSS minimizer.