rollup-plugin-styles

repository·main·Indexed 42 days ago

https://github.com/anidetrix/rollup-plugin-styles

A universal Rollup plugin for processing styles, supporting PostCSS, Sass, Less, Stylus, and CSS Modules. Version 4.0.0 provides flexible modes to inject CSS into JS, extract styles to separate files, or emit them for further processing in the build pipeline.

Tokens
8.9K
Snippets
33
Records
42
Agent score
49%

What's inside rollup-plugin-styles

  1. How CSS emit mode works

    main

    In emit mode, none of the CSS is exported to your JavaScript files. Instead, the CSS is purely processed and passed along the Rollup build pipeline. This is useful when you want to preprocess CSS and then pass it to another plugin (e.g., rollup-plugin-lit-css).

    // rollup.config.js
    import styles from "rollup-plugin-styles";
    import litcss from "rollup-plugin-lit-css";
    
    export default {
      plugins: [
        styles({ mode: "emit" }),
        // Ensure litcss is listed AFTER styles
        litcss(),
      ],
    };
  2. How CSS injection mode works

    main

    The default mode is inject. In this mode, CSS is embedded inside the generated JavaScript and injected into the <head> of the document at runtime.

    By default, the CSS string is available as the default export. If CSS Modules are enabled, you must use the named css export.

    // Injects CSS, also available as `style` in this example
    import style from "./style.css";
    
    // Using named export of CSS string (required if CSS Modules are enabled)
    import { css } from "./style.css";
  3. How CSS extraction mode works

    main

    In extract mode, the plugin extracts the processed CSS into separate files instead of injecting them via JavaScript. You can specify a filename or a path relative to the output directory.

    styles({
      mode: "extract",
    });
    
    // Or extract to a specific file
    styles({
      mode: ["extract", "awesome-bundle.css"],
    });
  4. Basic usage of rollup-plugin-styles

    main

    To use the plugin, import it in your rollup.config.js and add it to the plugins array. You can then import CSS files directly in your JavaScript/TypeScript code.

    // rollup.config.js
    import styles from "rollup-plugin-styles";
    
    export default {
      output: {
        assetFileNames: "[name]-[hash][extname]",
      },
      plugins: [styles()],
    };
    // In your application code
    import "./style.css";
  5. Importing files with CSS/Stylus and Sass/Less

    main

    The plugin supports @import statements.

    For CSS/Stylus, you can import from node_modules or local files.

    For Sass/Less, you can prepend the path with ~ to resolve imports from node_modules. Additionally, the plugin respects Sass/Less partials (e.g., @import "custom" will look for _custom before custom).

    /* CSS/Stylus: Import from node_modules */
    @import "bulma/css/bulma";
    
    /* Sass/Less: Import from node_modules using ~ */
    @import "~bulma/css/bulma";
    
    /* Local import */
    @import "./custom";
  6. Understand the Payload and Extracted data structures

    main

    The Payload object is the primary data structure passed through the loader pipeline. It contains:

    • code: The transformed file content (string).
    • map: An optional sourcemap (string).
    • extracted: An optional Extracted object containing the results of style processing.

    The Extracted object includes:

    • id: The source file path.
    • css: The processed CSS string.
    • map: An optional sourcemap string.
    export interface Payload {
      code: string;
      map?: string;
      extracted?: Extracted;
    }
    
    export interface Extracted {
      id: string;
      css: string;
      map?: string;
    }
  7. Configure CSS Injection strategies

    main

    The inject option determines how the processed CSS is injected into the document.

    Injection Modes

    1. Custom Function: If inject is a function, it is called with (cssVarName, fileId). You are responsible for returning the string that should be included in the output module.
    2. Object Configuration: If inject is an object, the loader uses a runtime injector.
      • treeshakeable: If true, the loader generates a getter-based object. This ensures the CSS is only injected when a specific class name is actually accessed, allowing bundlers to tree-shake unused styles.
      • Other options are passed directly to the internal injector.

    Important Constraints

    • If you use inject.treeshakeable: true, you cannot use the inject.modules.inject property (if applicable) as the inject keyword is reserved for the tree-shaking mechanism.
  8. Customize asset naming with hash placeholders

    main

    When the hash option is set to a string, you can use specific placeholders to define the output filename pattern for CSS assets. Forward slashes / can be used to organize files into sub-directories.

    Available Placeholders

    • [extname]: The file extension including the leading dot (e.g., .png).
    • [ext]: The file extension without the leading dot (e.g., png).
    • [hash(:<num>)]: A content-based hash. You can optionally specify the length using :<num> (e.g., [hash(:8)]).
    • [name]: The original filename without its extension.

    Example patterns:

    • assets/[name]-[hash][extname] (Default with hashing enabled)
    • static/img/[name][ext] (Custom pattern without hashing)
    // Example configuration
    const options: UrlOptions = {
      hash: 'static/images/[name]-[hash:6][extname]'
    };
  9. How CSS Modules and Named Exports work

    main

    When CSS Modules are enabled, the loader processes the file and extracts class name mappings.

    Enabling Modules

    You can enable modules in two ways:

    1. Explicitly: Set modules: true or provide a configuration object.
    2. Automatically: Set autoModules to a RegExp (e.g., /\.module\.css$/) or a function. If autoModules is active, the loader treats the file as a module.

    Named Exports

    If namedExports is set to true, the loader generates individual JavaScript exports for each CSS class found in the module.

    • Default Export: The default export will be the object containing all class mappings (e.g., export default modules;).
    • Named Exports: Each class is exported as a variable (e.g., export var myClass = "myClass_hash";).
    • Custom Naming: You can provide a namedExports function to control how the exported variable names are generated from the CSS class names.
  10. Initialize rollup-plugin-styles

    main

    To use the plugin, call the default export with an optional Options object. The plugin integrates with Rollup's lifecycle to process style files (like CSS, PostCSS, etc.) and can either inject them into JavaScript or extract them into separate CSS files.

    import styles from 'rollup-plugin-styles';
    
    export default {
      plugins: [
        styles({
          // configuration options
        })
      ]
    };