MCPcopy Index your code
hub / github.com/webpack/css-loader

github.com/webpack/css-loader @v7.1.4

repository ↗ · DeepWiki ↗ · release v7.1.4 ↗ · + Follow
79 symbols 199 edges 212 files 0 documented · 0%
README

[![npm][npm]][npm-url] [![node][node]][node-url] [![tests][tests]][tests-url] [![coverage][cover]][cover-url] [![discussion][discussion]][discussion-url] [![size][size]][size-url]

css-loader

The css-loader interprets @import and url() like import/require() and resolves them.

Getting Started

[!WARNING]

To use the latest version of css-loader, webpack@5 is required

To begin, you'll need to install css-loader:

npm install --save-dev css-loader

or

yarn add -D css-loader

or

pnpm add -D css-loader

Then, add the loader to your webpack configuration. For example:

file.js

import * as css from "file.css";

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
};

Finally, run webpack using the method you normally use (e.g., via CLI or an npm script).

If you need to extract CSS into a separate file (i.e. do not store CSS in a JS module), consider using the recommend example.

Options

url

Type:

type url =
  | boolean
  | {
      filter: (url: string, resourcePath: string) => boolean;
    };

Default: true

Enables or disables handling the CSS functions url and image-set.

  • If set to false, css-loader will not parse any paths specified in url or image-set.
  • You can also pass a function to control this behavior dynamically based on the asset path.

As of version 4.0.0, absolute paths are resolved based on the server root.

Examples resolutions:

url(image.png) => require('./image.png')
url('image.png') => require('./image.png')
url(./image.png) => require('./image.png')
url('./image.png') => require('./image.png')
url('http://dontwritehorriblecode.com/2112.png') => require('http://dontwritehorriblecode.com/2112.png')
image-set(url('image2x.png') 1x, url('image1x.png') 2x) => require('./image1x.png') and require('./image2x.png')

To import assets from a node_modules path (including resolve.modules) or an alias, prefix it with a ~:

url(~module/image.png) => require('module/image.png')
url('~module/image.png') => require('module/image.png')
url(~aliasDirectory/image.png) => require('otherDirectory/image.png')

boolean

Enable/disable url() resolving.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          url: true,
        },
      },
    ],
  },
};

object

Allows filtering of url() values.

Any filtered url() will not be resolved (left in the code as they were written).

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          url: {
            filter: (url, resourcePath) => {
              // resourcePath - path to css file

              // Don't handle `img.png` urls
              if (url.includes("img.png")) {
                return false;
              }

              // Don't handle images under root-relative /external_images/
              if (/^\/external_images\//.test(url)) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

import

Type:

type importFn =
  | boolean
  | {
      filter: (
        url: string,
        media: string,
        resourcePath: string,
        supports?: string,
        layer?: string,
      ) => boolean;
    };

Default: true

Allows you to enable or disable handling of @import at-rules.

Controls how @import statements are resolved.

Absolute URLs in @import will be moved in runtime code.

Examples resolutions:

@import 'style.css' => require('./style.css')
@import url(style.css) => require('./style.css')
@import url('style.css') => require('./style.css')
@import './style.css' => require('./style.css')
@import url(./style.css) => require('./style.css')
@import url('./style.css') => require('./style.css')
@import url('http://dontwritehorriblecode.com/style.css') => @import url('http://dontwritehorriblecode.com/style.css') in runtime

To import styles from a node_modules path (include resolve.modules) or an alias, prefix it with a ~:

@import url(~module/style.css) => require('module/style.css')
@import url('~module/style.css') => require('module/style.css')
@import url(~aliasDirectory/style.css) => require('otherDirectory/style.css')

boolean

Enable/disable @import resolving.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          import: true,
        },
      },
    ],
  },
};

object

filter

Type:

type filter = (url: string, media: string, resourcePath: string) => boolean;

Default: undefined

Allows filtering of @import.

Any filtered @import will not be resolved (left in the code as they were written).

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          import: {
            filter: (url, media, resourcePath) => {
              // resourcePath - path to css file

              // Don't handle `style.css` import
              if (url.includes("style.css")) {
                return false;
              }

              return true;
            },
          },
        },
      },
    ],
  },
};

modules

Type:

type modules =
  | boolean
  | "local"
  | "global"
  | "pure"
  | "icss"
  | {
      auto: boolean | regExp | ((resourcePath: string) => boolean);
      mode:
        | "local"
        | "global"
        | "pure"
        | "icss"
        | ((resourcePath) => "local" | "global" | "pure" | "icss");
      localIdentName: string;
      localIdentContext: string;
      localIdentHashSalt: string;
      localIdentHashFunction: string;
      localIdentHashDigest: string;
      localIdentRegExp: string | regExp;
      getLocalIdent: (
        context: LoaderContext,
        localIdentName: string,
        localName: string,
      ) => string;
      namedExport: boolean;
      exportGlobals: boolean;
      exportLocalsConvention:
        | "as-is"
        | "camel-case"
        | "camel-case-only"
        | "dashes"
        | "dashes-only"
        | ((name: string) => string);
      exportOnlyLocals: boolean;
      getJSON: ({
        resourcePath,
        imports,
        exports,
        replacements,
      }: {
        resourcePath: string;
        imports: object[];
        exports: object[];
        replacements: object[];
      }) => Promise<void> | void;
    };

Default: undefined

Allows you to enable or disable CSS Modules or ICSS and configure them:

  • undefined: Enables CSS modules for all files matching /\.module\.\w+$/i.test(filename) or /\.icss\.\w+$/i.test(filename) regexp.
  • true: Enables CSS modules for all files.
  • false: Disables CSS Modules for all files.
  • string: Disables CSS Modules for all files and set the mode option (see mode for details).
  • object: Enables CSS modules for all files unless the modules.auto option is provided. otherwise the modules.auto option will determine whether if it is CSS Modules or not (see auto for more details).

The modules option enables/disables the CSS Modules specification and configures its behavior.

Setting modules: false can improve performance because we avoid parsing CSS Modules features, this is useful for developers using use vanilla CSS or other technologies.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: true,
        },
      },
    ],
  },
};

Features

Scope
  • Using local value requires you to specify :global classes.
  • Using global value requires you to specify :local classes.
  • Using pure value requires selectors must contain at least one local class or ID.

You can find more information on scoping module here.

With CSS Modules, styles are scoped locally, preventing conflicts with global styles.

Use :local(.className) to declare a className in the local scope. The local identifiers are exported by the module.

  • With :local (without parentheses) local mode can be switched on for this selector.
  • The :global(.className) notation can be used to declare an explicit global selector.
  • With :global (without parentheses) global mode can be switched on for this selector.

The loader replaces local selectors with unique, scoped identifiers. The chosen unique identifiers are exported by the module.

:local(.className) {
  background: red;
}
:local .className {
  color: green;
}
:local(.className .subClass) {
  color: green;
}
:local .className .subClass :global(.global-class-name) {
  color: blue;
}

Output (example):

._23_aKvs-b8bW2Vg3fwHozO {
  background: red;
}
._23_aKvs-b8bW2Vg3fwHozO {
  color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 {
  color: green;
}
._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name {
  color: blue;
}

[!NOTE]

Identifiers are exported

exports.locals = {
  className: "_23_aKvs-b8bW2Vg3fwHozO",
  subClass: "_13LGdX8RMStbBE9w-t0gZ1",
};

CamelCase naming is recommended for local selectors, as it simplifies usage in imported JS modules.

Although you can use :local(#someId), but this is not recommended. Prefer classes instead of IDs for modular styling.

Composing

When declaring a local class name, you can compose it from one or more other local class names.

:local(.className) {
  background: red;
  color: yellow;
}

:local(.subClass) {
  composes: className;
  background: blue;
}

This does not alter the final CSS output, but the generated subClass will include both class names in its export.

exports.locals = {
  className: "_23_aKvs-b8bW2Vg3fwHozO",
  subClass: "_13LGdX8RMStbBE9w-t0gZ1 _23_aKvs-b8bW2Vg3fwHozO",
};
._23_aKvs-b8bW2Vg3fwHozO {
  background: red;
  color: yellow;
}

._13LGdX8RMStbBE9w-t0gZ1 {
  background: blue;
}
Importing

To import a local class names from another module.

[!NOTE]

It is highly recommended to include file extensions when importing a file, since it is possible to import a file with any extension and it is not known in advance which file to use.

:local(.continueButton) {
  composes: button from "library/button.css";
  background: red;
}
:local(.nameEdit) {
  composes: edit highlight from "./edit.css";
  background: red;
}

To import from multiple modules use multiple composes: rules.

:local(.className) {
  composes:
    edit highlight from "./edit.css",
    button from "module/button.css",
    classFromThisModule;
  background: red;
}

or

:local(.className) {
  composes: edit highlight from "./edit.css";
  composes: button from "module/button.css";
  composes: classFromThisModule;
  background: red;
}
Values

You can use @value to specific values to be reused throughout a document.

We recommend following a naming convention:

  • v- prefix for values
  • s- prefix for selectors
  • m- prefix for media at-rules.
@value v-primary: #BF4040;
@value s-black: black-selector;
@value m-large: (min-width: 960px);

.header {
  color: v-primary;
  padding: 0 10px;
}

.s-black {
  color: black;
}

@media m-large {
  .header {
    padding: 0 20px;
  }
}

boolean

Enable CSS Modules features.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: true,
        },
      },
    ],
  },
};

string

Enable CSS Modules features and setup mode.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          // Using `local` value has same effect like using `modules: true`
          modules: "global",
        },
      },
    ],
  },
};

object

Enable CSS Modules features and configure its behavior through options.

webpack.config.js

```js module.exports = { module: { rules: [ { test: /.css$/i, loader: "css-loader", options: { modules: { mode: "local", auto: true, exportGlobals: true, localIdentName: "[path][name]__[local]--[hash:base64:5]", localIdentContext: path.resolve(__dirname, "src"), localIdentHashSalt: "my-custom-hash", namedExport: true, exportLocalsConvention: "as-is", exportOnlyLocals: false, getJSON: ({ resourcePath, imports, exports, replacements }) =>

Core symbols most depended-on inside this repo

stringifyRequest
called by 6
src/utils.js
normalizePath
called by 6
src/utils.js
normalizeUrl
called by 5
src/utils.js
apply
called by 4
test/helpers/get-json.js
unescape
called by 4
src/utils.js
getValidLocalName
called by 4
src/utils.js
generateIdentifier
called by 3
test/helpers/get-json.js
removeCWD
called by 3
test/helpers/normalizeErrors.js

Shape

Function 75
Class 2
Method 2

Languages

TypeScript100%

Modules by API surface

src/utils.js42 symbols
test/helpers/get-json.js8 symbols
src/plugins/postcss-url-parser.js8 symbols
src/plugins/postcss-import-parser.js7 symbols
src/plugins/postcss-icss-parser.js3 symbols
test/validate-options.test.js2 symbols
test/modules-option.test.js1 symbols
test/helpers/url-loader.js1 symbols
test/helpers/string-loader.js1 symbols
test/helpers/readAssets.js1 symbols
test/helpers/preLoader.js1 symbols
test/helpers/normalizeErrors.js1 symbols

Dependencies from manifests, versioned

@babel/cli7.24.8 · 1×
@babel/core7.25.2 · 1×
@babel/preset-env7.25.3 · 1×
@commitlint/cli19.3.0 · 1×
@commitlint/config-conventional19.2.2 · 1×
@webpack-contrib/eslint-config-webpack3.0.0 · 1×
babel-jest30.0.0 · 1×
cross-env7.0.3 · 1×
cspell8.13.1 · 1×
del-cli5.1.0 · 1×
es-check7.2.1 · 1×
eslint8.54.0 · 1×

For agents

$ claude mcp add css-loader \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact