CSS Loader

Overview

npm node deps tests coverage chat size

css-loader

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

Getting Started

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

npm install --save-dev css-loader

Then add the plugin to your webpack config. For example:

file.js

import css from "file.css";

webpack.config.js

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

Only for webpack v4:

Good loaders for requiring your assets are the file-loader and the url-loader which you should specify in your config (see below).

And run webpack via your preferred method.

toString

You can also use the css-loader results directly as a string, such as in Angular's component style.

webpack.config.js

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

or

const css = require("./test.css").toString();

console.log(css); // {String}

If there are SourceMaps, they will also be included in the result string.

If, for one reason or another, you need to extract CSS as a plain string resource (i.e. not wrapped in a JS module) you might want to check out the extract-loader. It's useful when you, for instance, need to post process the CSS as a string.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          "handlebars-loader", // handlebars loader expects raw resource string
          "extract-loader",
          "css-loader",
        ],
      },
    ],
  },
};

Options

Name Type Default Description
url {Boolean|Function} true Enables/Disables url/image-set functions handling
import {Boolean|Function} true Enables/Disables @import at-rules handling
modules {Boolean|String|Object} {auto: true} Enables/Disables CSS Modules and their configuration
sourceMap {Boolean} compiler.devtool Enables/Disables generation of source maps
importLoaders {Number} 0 Enables/Disables or setups number of loaders applied before CSS loader
esModule {Boolean} true Use ES modules syntax

url

Type: Boolean|Function Default: true

Enables/Disables url/image-set functions handling. Control url() resolving. Absolute paths and root-relative URLs now resolving(Version 4.0.0 and above).

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 (include resolve.modules) and for 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,
        },
      },
    ],
  },
};

Function

Allow to filter url(). All 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: (url, resourcePath) => {
            // resourcePath - path to css file

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

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

import

Type: Boolean|Function Default: true

Enables/Disables @import at-rules handling. Control @import resolving. 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) and for 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,
        },
      },
    ],
  },
};

Function

Allow to filter @import. All 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: (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: Boolean|String|Object Default: based on filename, true for all files matching /\.module\.\w+$/i.test(filename) regular expression, more information you can read here

Enables/Disables CSS Modules and their configuration.

The modules option enables/disables the CSS Modules specification and setup basic behaviour.

Using false value increase performance because we avoid parsing CSS Modules features, it will be useful for developers who use vanilla css or use 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 here.

Styles can be locally scoped to avoid globally scoping styles.

The syntax :local(.className) can be used to declare className in the local scope. The local identifiers are exported by the module.

With :local (without brackets) 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 brackets) global mode can be switched on for this selector.

The loader replaces local selectors with unique 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;
}
._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;
}

ℹ️ Identifiers are exported

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

CamelCase is recommended for local selectors. They are easier to use within the imported JS module.

You can use :local(#someId), but this is not recommended. Use classes instead of ids.

Composing

When declaring a local classname you can compose a local class from another local classname.

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

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

This doesn't result in any change to the CSS itself but exports multiple classnames.

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 classname from another module.

i We strongly recommend that you specify the extension 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 hightlight 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 use prefix v- for values, s- for selectors and m- 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 setup options for them.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            compileType: "module",
            mode: "local",
            auto: true,
            exportGlobals: true,
            localIdentName: "[path][name]__[local]--[hash:base64:5]",
            localIdentContext: path.resolve(__dirname, "src"),
            localIdentHashPrefix: "my-custom-hash",
            namedExport: true,
            exportLocalsConvention: "camelCase",
            exportOnlyLocals: false,
          },
        },
      },
    ],
  },
};
compileType

Type: 'module' | 'icss' Default: 'module'

Controls the level of compilation applied to the input styles.

The module handles class and id scoping and @value values. The icss will only compile the low level Interoperable CSS format for declaring :import and :export dependencies between CSS and other languages.

ICSS underpins CSS Module support, and provides a low level syntax for other tools to implement CSS-module variations of their own.

webpack.config.js

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

Type: Boolean|RegExp|Function Default: 'true'

Allows auto enable CSS modules based on filename.

Boolean

Possible values:

  • true - enables CSS modules or interoperable CSS format, sets the modules.compileType option to module value for all files which satisfy /\.module(s)?\.\w+$/i.test(filename) condition or sets the modules.compileType option to icss value for all files which satisfy /\.icss\.\w+$/i.test(filename) condition
  • false - disables CSS modules or interoperable CSS format based on filename

webpack.config.js

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

Enable css modules for files based on the filename satisfying your regex check.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            auto: /\.custom-module\.\w+$/i,
          },
        },
      },
    ],
  },
};
Function

Enable css modules for files based on the filename satisfying your filter function check.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            auto: (resourcePath) => resourcePath.endsWith(".custom-module.css"),
          },
        },
      },
    ],
  },
};
mode

Type: String|Function Default: 'local'

Setup mode option. You can omit the value when you want local mode.

String

Possible values - local, global, and pure.

webpack.config.js

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

Allows set different values for the mode option based on a filename

Possible return values - local, global, and pure.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            // Callback must return "local", "global", or "pure" values
            mode: (resourcePath) => {
              if (/pure.css$/i.test(resourcePath)) {
                return "pure";
              }

              if (/global.css$/i.test(resourcePath)) {
                return "global";
              }

              return "local";
            },
          },
        },
      },
    ],
  },
};
localIdentName

Type: String Default: '[hash:base64]'

Allows to configure the generated local ident name. See loader-utils's documentation for more information on options.

Recommendations:

  • use '[path][name]__[local]' for development
  • use '[hash:base64]' for production

The [local] placeholder contains original class.

Note: all reserved (<>:"/\|?*) and control filesystem characters (excluding characters in the [local] placeholder) will be converted to -.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentName: "[path][name]__[local]--[hash:base64:5]",
          },
        },
      },
    ],
  },
};
localIdentContext

Type: String Default: compiler.context

Allows to redefine basic loader context for local ident name.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentContext: path.resolve(__dirname, "src"),
          },
        },
      },
    ],
  },
};
localIdentHashPrefix

Type: String Default: undefined

Allows to add custom hash to generate more unique classes.

webpack.config.js

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

Type: String|RegExp Default: undefined

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            localIdentRegExp: /page-(.*)\.css/i,
          },
        },
      },
    ],
  },
};
getLocalIdent

Type: Function Default: undefined

Allows to specify a function to generate the classname. By default we use built-in function to generate a classname. If the custom function returns null or undefined, we fallback to the built-in function to generate the classname.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        loader: "css-loader",
        options: {
          modules: {
            getLocalIdent: (context, localIdentName, localName, options) => {
              return "whatever_random_class_name";
            },
          },
        },
      },
    ],
  },
};
namedExport

Type: Boolean Default: false

Enables/disables ES modules named export for locals.

Names of locals are converted to camelcase, i.e. the exportLocalsConvention option has camelCaseOnly value by default.

It is not allowed to use JavaScript reserved words in css class names.

styles.css

.foo-baz {
  color: red;
}
.bar {
  color: blue;
}

index.js

import { fooBaz, bar } from "./styles.css";

console.log(fooBaz, bar);

You can enable a ES module named export using:

webpack.config.js

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

Type: Boolean Default: false

Allow css-loader to export names from global class or id, so you can use that as local name.

webpack.config.js

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

Type: String Default: based on the modules.namedExport option value, if true - camelCaseOnly, otherwise asIs

Style of exported class names.

By default, the exported JSON keys mirror the class names (i.e asIs value).

Only camelCaseOnly value allowed if you set the namedExport value to true.

Name Type Description
'asIs' {String} Class names will be exported as is.
'camelCase' {String} Class names will be camelized, the original class name will not to be removed from the locals
'camelCaseOnly' {String} Class names will be camelized, the original class name will be removed from the locals
'dashes' {String} Only dashes in class names will be camelized
'dashesOnly' {String} Dashes in class names will be camelized, the original class name will be removed from the locals

file.css

.class-name {
}

file.js

import { className } from "file.css";

webpack.config.js

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

Type: Boolean Default: false

Export only locals.

Useful when you use css modules for pre-rendering (for example SSR). For pre-rendering with mini-css-extract-plugin you should use this option instead of style-loader!css-loader in the pre-rendering bundle. It doesn't embed CSS but only exports the identifier mappings.

webpack.config.js

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

sourceMap

Type: Boolean Default: depends on the compiler.devtool value

By default generation of source maps depends on the devtool option. All values enable source map generation except eval and false value.

webpack.config.js

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

importLoaders

Type: Number Default: 0

Enables/Disables or setups number of loaders applied before CSS loader.

The option importLoaders allows you to configure how many loaders before css-loader should be applied to @imported resources.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              importLoaders: 2,
              // 0 => no loaders (default);
              // 1 => postcss-loader;
              // 2 => postcss-loader, sass-loader
            },
          },
          "postcss-loader",
          "sass-loader",
        ],
      },
    ],
  },
};

This may change in the future when the module system (i. e. webpack) supports loader matching by origin.

esModule

Type: Boolean Default: true

By default, css-loader generates JS modules that use the ES modules syntax. There are some cases in which using ES modules is beneficial, like in the case of module concatenation and tree shaking.

You can enable a CommonJS modules syntax using:

webpack.config.js

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

Examples

Disable url resolving using the /* webpackIgnore: true */ comment

With the help of the /* webpackIgnore: true */comment, it is possible to disable sources handling for rules and for individual declarations.

/* webpackIgnore: true */
@import url(./basic.css);
@import /* webpackIgnore: true */ url(./imported.css);

.class {
  /* Disabled url handling for the all urls in the 'background' declaration */
  color: red;
  /* webpackIgnore: true */
  background: url("./url/img.png"), url("./url/img.png");
}

.class {
  /* Disabled url handling for the first url in the 'background' declaration */
  color: red;
  background: 
    /* webpackIgnore: true */ url("./url/img.png"), url("./url/img.png");
}

.class {
  /* Disabled url handling for the second url in the 'background' declaration */
  color: red;
  background: url("./url/img.png"),
    /* webpackIgnore: true */ url("./url/img.png");
}

/* prettier-ignore */
.class {
  /* Disabled url handling for the second url in the 'background' declaration */
  color: red;
  background: url("./url/img.png"),
    /* webpackIgnore: true */ 
    url("./url/img.png");
}

/* prettier-ignore */
.class {
  /* Disabled url handling for third and sixth urls in the 'background-image' declaration */
  background-image: image-set(
    url(./url/img.png) 2x,
    url(./url/img.png) 3x,
    /* webpackIgnore:  true */ url(./url/img.png) 4x,
    url(./url/img.png) 5x,
    url(./url/img.png) 6x,
    /* webpackIgnore:  true */
    url(./url/img.png) 7x
  );
}

Assets

The following webpack.config.js can load CSS files, embed small PNG/JPG/GIF/SVG images as well as fonts as Data URLs and copy larger files to the output directory.

For webpack v5:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        // More information here https://webpack.js.org/guides/asset-modules/
        type: "asset",
      },
    ],
  },
};

For webpack v4:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        loader: "url-loader",
        options: {
          limit: 8192,
        },
      },
    ],
  },
};

Extract

For production builds it's recommended to extract the CSS from your bundle being able to use parallel loading of CSS/JS resources later on.

  • This can be achieved by using the mini-css-extract-plugin to extract the CSS when running in production mode.

  • As an alternative, if seeking better development performance and css outputs that mimic production. extract-css-chunks-webpack-plugin offers a hot module reload friendly, extended version of mini-css-extract-plugin. HMR real CSS files in dev, works like mini-css in non-dev

Pure CSS, CSS modules and PostCSS

When you have pure CSS (without CSS modules), CSS modules and PostCSS in your project you can use this setup:

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        // For pure CSS - /\.css$/i,
        // For Sass/SCSS - /\.((c|sa|sc)ss)$/i,
        // For Less - /\.((c|le)ss)$/i,
        test: /\.((c|sa|sc)ss)$/i,
        use: [
          "style-loader",
          {
            loader: "css-loader",
            options: {
              // Run `postcss-loader` on each CSS `@import`, do not forget that `sass-loader` compile non CSS `@import`'s into a single file
              // If you need run `sass-loader` and `postcss-loader` on each CSS `@import` please set it to `2`
              importLoaders: 1,
            },
          },
          {
            loader: "postcss-loader",
            options: { plugins: () => [postcssPresetEnv({ stage: 0 })] },
          },
          // Can be `less-loader`
          {
            loader: "sass-loader",
          },
        ],
      },
      // For webpack v5
      {
        test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
        // More information here https://webpack.js.org/guides/asset-modules/
        type: "asset",
      },
      // For webpack v4
      // {
      //  test: /\.(png|jpe?g|gif|svg|eot|ttf|woff|woff2)$/i,
      //  loader: "url-loader",
      //  options: {
      //    limit: 8192,
      //  },
      // },
    ],
  },
};

Resolve unresolved URLs using an alias

index.css

.class {
  background: url(/assets/unresolved/img.png);
}

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
  resolve: {
    alias: {
      "/assets/unresolved/img.png": path.resolve(
        __dirname,
        "assets/real-path-to-img/img.png"
      ),
    },
  },
};

Separating Interoperable CSS-only and CSS Module features

The following setup is an example of allowing Interoperable CSS features only (such as :import and :export) without using further CSS Module functionality by setting compileType option for all files that do not match *.module.scss naming convention. This is for reference as having ICSS features applied to all files was default css-loader behavior before v4. Meanwhile all files matching *.module.scss are treated as CSS Modules in this example.

An example case is assumed where a project requires canvas drawing variables to be synchronized with CSS - canvas drawing uses the same color (set by color name in JavaScript) as HTML background (set by class name in CSS).

webpack.config.js

module.exports = {
  module: {
    rules: [
      // ...
      // --------
      // SCSS ALL EXCEPT MODULES
      {
        test: /\.scss$/,
        exclude: /\.module\.scss$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: {
                compileType: 'icss'
              }
            }
          },
          {
            loader: 'sass-loader'
          },
        ],
      },
      // --------
      // SCSS MODULES
      {
        test: /\.module\.scss$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              modules: {
                compileType: 'module'
              }
            }
          },
          {
            loader: 'sass-loader'
          },
        ],
      },
      // --------
      // ...
  },
};

variables.scss

File treated as ICSS-only.

$colorBackground: red;
:export {
  colorBackgroundCanvas: $colorBackground;
}

Component.module.scss

File treated as CSS Module.

@import "variables.scss";
.componentClass {
  background-color: $colorBackground;
}

Component.jsx

Using both CSS Module functionality as well as SCSS variables directly in JavaScript.

import svars from "variables.scss";
import styles from "Component.module.scss";

// Render DOM with CSS modules class name
// <div className={styles.componentClass}>
//   <canvas ref={mountsCanvas}/>
// </div>

// Somewhere in JavaScript canvas drawing code use the variable directly
// const ctx = mountsCanvas.current.getContext('2d',{alpha: false});
ctx.fillStyle = `${svars.colorBackgroundCanvas}`;

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

Comments
  • Can't resolve 'fs' when bundle with webpack

    Can't resolve 'fs' when bundle with webpack

    Do you want to request a feature or report a bug? Bug

    What is the current behavior? Webpack finish bundle without errors with css-loader 0.26.4. After update to 0.27.0 webpacking finished with error:

    ERROR in ./~/convert-source-map/index.js
    Module not found: Error: Can't resolve 'fs' in 'C:\Projects\project_name\node_modules\convert-source-map'
     @ ./~/convert-source-map/index.js 2:9-22
     @ ./~/css-loader/lib/css-base.js
    

    If the current behavior is a bug, please provide the steps to reproduce.

    1. Update css-loader from 0.26.4 to 0.27.0 version
    2. Run webpack to build

    What is the expected behavior? Works without error

    Please mention other relevant information such as your webpack version, Node.js version and Operating System. Windows 8.1 Node.js 7.7.2 Webpack 2.2.1

    opened by Alex-Sokolov 98
  • 0.15.0+ makes Webpack load slowly

    0.15.0+ makes Webpack load slowly

    Ever since the 0.15.0 update, I've had to revert back to 0.14.5, because Webpack loads very slowly (12 secs vs almost 60 secs). Is there a breaking change I should be aware of? Maybe something regarding PostCSS?

    type: Refactor semver: Major priority: 4 (important) 
    opened by ljconde 73
  • .../styles.css Unexpected character '@'

    .../styles.css Unexpected character '@'

    Hi all! I get something strange error, maybe i did wrote wrong config file. But if the file is styles.css present @charset "UTF-8", the parser generates an error.

    Example index.js

    require('./styles.css')
    

    Example style.css

    @charset "UTF-8"
    body {
     ...
    }
    
    type: Bug 
    opened by CrazyUmka 67
  • fix: allow values in selectors to work correctly

    fix: allow values in selectors to work correctly

    This PR contains a:

    • [x] bugfix
    • [x] new feature
    • [ ] code refactor
    • [ ] test update
    • [ ] typo fix
    • [ ] metadata update

    Motivation / Use-Case

    depends on:

    • https://github.com/css-modules/postcss-modules-values/pull/2#issuecomment-464125471
    • https://github.com/css-modules/postcss-modules-scope/pull/4

    This works to enable behavior that is specced by css-modules, but has been only partially implemented until now; TL; DR; selectors are a valid place for imported values to be interpolated.

    Breaking Changes

    Maybe! Still thinking through that

    Additional Info

    opened by jquense 57
  • [2.0.0] ValidationError: CSS Loader Invalid Options - options should NOT have additional properties

    [2.0.0] ValidationError: CSS Loader Invalid Options - options should NOT have additional properties

    • Operating System: Linux workstation 4.15.0-42-generic #45-Ubuntu SMP Thu Nov 15 19:32:57 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
    • Node Version: 11.4.0
    • NPM Version: 6.4.1
    • webpack Version: latest 4.27.1
    • css-loader Version: latest - 2.0.0

    Expected Behavior

    I can use the css-loader, I have not changed anything.

    Actual Behavior

    ERROR in ./node_modules/material-design-icons/iconfont/material-icons.css
    Module build failed (from ./node_modules/css-loader/dist/cjs.js):
    ModuleBuildError: Module build failed (from ./node_modules/css-loader/dist/cjs.js):
    ValidationError: CSS Loader Invalid Options
    
    options should NOT have additional properties
    
        at validateOptions (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/schema-utils/src/validateOptions.js:32:11)
        at Object.loader (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/css-loader/dist/index.js:44:28)
        at runLoaders (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/webpack/lib/NormalModule.js:301:20)
        at /media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/loader-runner/lib/LoaderRunner.js:364:11
        at /media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/loader-runner/lib/LoaderRunner.js:230:18
        at runSyncOrAsync (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/loader-runner/lib/LoaderRunner.js:143:3)
        at iterateNormalLoaders (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/loader-runner/lib/LoaderRunner.js:229:2)
        at iterateNormalLoaders (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/loader-runner/lib/LoaderRunner.js:218:10)
        at /media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/loader-runner/lib/LoaderRunner.js:233:3
        at context.callback (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/loader-runner/lib/LoaderRunner.js:111:13)
        at Object.render [as callback] (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/sass-loader/lib/loader.js:76:9)
        at Object.done [as callback] (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/neo-async/async.js:8077:18)
        at options.success (/media/linux-nvme/home/patrikx3/Projects/patrikx3/corifeus/corifeus-web-material/node_modules/node-sass/lib/index.js:308:32)
     @ ./node_modules/material-design-icons/iconfont/material-icons.css
    

    Code

      // webpack.config.js
      // If your bitchin' code blocks are over 20 lines, please paste a link to a gist
      // (https://gist.github.com).
    
            rules: [
                {
                    test: /\.less$/,
                    use: [{
                        loader: 'style-loader' ,
                    }, {
                        loader: 'css-loader',
                    }, {
                        loader: 'less-loader',
                    }],
                },
    
    
    

    How Do We Reproduce?

    It happens with css-loader 2.0.0

    flag: Needs more info 
    opened by p3x-robot 55
  • Error can't find module when using less-loader and

    Error can't find module when using less-loader and "module" options

    Hello, when i use "background: url(./icon.png)" in my less file i got error Module not found: Error: Cannot resolve module 'icon.png'.

    Here part of webpack.config.js file

    module: {
                loaders: [
                    {
                        test: /\.less$/,
                        loader: ExtractTextPlugin.extract('style', 'css?module&localIdentName=[hash:base64:5]!postcss!less')
                    },
                    {
                        test: /\.(jpg|png)$/,
                        loader: 'url-loader?limit=100000'
                    },
                    {
                        test: /\.svg$/,
                        loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
                    }
                ]
    },
    

    If remove module options or less-loader all works well.

    opened by zxcabs 49
  • css-loader parse fail on @font-face

    css-loader parse fail on @font-face

    I get this error when webpack tries to run:

    ERROR in ./bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot
    Module parse failed: 
    ./bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot Line 1: Unexpected token ILLEGAL
    You may need an appropriate loader to handle this file type.
    (Source code omitted for this binary file)
     @ ./~/css-loader?importLoaders=1!./bower_components/bootstrap/dist/css/bootstrap.css 2:4480-4532 2:4551-4603
    

    Here's my configuration

     module: {
        loaders: [
          // Pass *.jsx files through jsx-loader transform
          { test: /\.js$/, loaders: ['react-hot','jsx?harmony'] },
    
          { test: /\.css$/, loader: "style-loader!css-loader?importLoaders=1" }
        ]
      }
    

    Is it something in my config that's wrong or missing something?

    opened by mattybow 48
  • Weird source map paths when used together with sass-loader

    Weird source map paths when used together with sass-loader

    Do you want to request a feature or report a bug? Bug report

    What is the current behavior? Wrong source map/resource paths using css-loader together with sass-loader as shown below:

    Examples of source map paths using the plugin The actual app.scss path is ./src/styles/app.scss

    ex1

    However the source map path for the file becomes ./src/styles/src/styles/app.scss and the absolute resource path: C:/Users/m51n/source/repos/source-map-path/src/styles/src/styles/app.scss (does not exist)

    ex2

    If the current behavior is a bug, please provide the steps to reproduce. I've created a sample project here-- using the source map example from the sass-loader docs and code from the extract-text-webpack-plugin docs here

    With the sample project above I used devtool: "inline-source-map".

    What is the expected behavior? Expected source map path returned by the plugin in this case would be ./src/styles/app.scss and absolute resource path as it exist on disk: C:/Users/m51n/source/repos/source-map-path/src/styles/app.scss

    Related issues for reference https://github.com/webpack-contrib/sass-loader/issues/484

    Please mention other relevant information such as your webpack version, Node.js version and Operating System.

    webpack v3.10.0 node v9.2.0 os: windows 10

    type: Bug severity: 3 (broken) semver: Patch priority: 4 (important) 
    opened by woldner 44
  • refactor: drop `css` modules

    refactor: drop `css` modules

    Briefly

    Bug fixes

    • Add file from error to dependencies graph if something throw error (if you have broken css code on first watch run, before it requires restart watching, now it is no longer necessary)
    • Escaped characters now works correctly

    Features

    • Reuse ast from postcss-loader (if used), it is decrease build time
    • API for modify generated code (i.e. allows to import and export what you want, also allows to modify generated code)
    • Validate options

    Breaking changes

    • Removed modules option, use postcss-modules plugin with postcss-loader
    • Removed localIdentName option
    • Removed camelCase option
    semver: Major 
    opened by alexander-akait 40
  • Unknown word error when loading plain CSS (not Sass or Less)

    Unknown word error when loading plain CSS (not Sass or Less)

    I'm trying out webpack for the first time.. Trying to use the style-loader and css-loader.

    Plain old css (not sass and not less) could not be loaded.

    ERROR in ./~/css-loader!./~/style-loader!./~/css-loader!./src/styles/site.css
    Module build failed: CssSyntaxError: C:\css-loader!C:\Users\Foo\Desktop\try-webpack\node_modules\style-loader\index.js!C:\Users\Foo\Desktop\try-webpack\node_modules\css-loader\index.js!C:\Users\Foo\Desktop\try-webpack\src\styles\site.css:5:1: Unknown word
        at Input.error (C:\Users\Foo\Desktop\try-webpack\node_modules\postcss\lib\input.js:61:22)
        at Parser.unknownWord (C:\Users\Foo\Desktop\try-webpack\node_modules\postcss\lib\parser.js:457:26)
        at Parser.word (C:\Users\Foo\Desktop\try-webpack\node_modules\postcss\lib\parser.js:174:14)
        at Parser.loop (C:\Users\Foo\Desktop\try-webpack\node_modules\postcss\lib\parser.js:60:26)
        at parse (C:\Users\Foo\Desktop\try-webpack\node_modules\postcss\lib\parse.js:26:12)
        at new LazyResult (C:\Users\Foo\Desktop\try-webpack\node_modules\postcss\lib\lazy-result.js:61:24)
        at Processor.process (C:\Users\Foo\Desktop\try-webpack\node_modules\postcss\lib\processor.js:34:16)
        at processCss (C:\Users\Foo\Desktop\try-webpack\node_modules\css-loader\lib\processCss.js:188:11)
        at Object.module.exports (C:\Users\Foo\Desktop\try-webpack\node_modules\css-loader\lib\loader.js:24:2)
     @ ./~/style-loader!./~/css-loader!./src/styles/site.css 4:14-162
    

    My webpack.config.js file is just this:

    var path = require('path');
    
    module.exports = {
    
        entry: "./src/scripts/index.js",
        output: {        
            path: path.join(__dirname, "public", "build"),
            filename: "app.js"
        },
        module: {
            loaders: [
                { test: /\.css$/, loader: "style-loader!css-loader" }
            ]
        }
    };
    

    If I remove the module part in the above thing, the error is gone.

    I also tried { test: /\.css$/, loader: "style!css" } and {test: /\.css/, loader: "style!css" }and various possible permutations with removing characters. There are no comments in the css file or the webpack.config.js file.

    Specifying the loaders sequence in the import statement works (shown below):

    var css = require("style!css!../styles/site.css");

    Am I missing something here? I really can't see it.

    Regards

    opened by decoder318 40
  • fix: source map `sources` and `file` paths

    fix: source map `sources` and `file` paths

    What kind of change does this PR introduce? half bugfix / half feature

    Did you add tests for your changes? Not yet, but they will be similar to existing tests. Waiting for feedback/comments.

    If relevant, did you update the README? Yes

    Summary The sources and file entries in sourcemaps are URLs relative to the file contains the source map (.css or .map) per version 3 of the source map specification.

    For many loaders concerned with stylesheets, they currently try to treat them as file system paths, which has been a significant factor in errors that appear in these paths, especially when paths are being resolved without first checking if they are already absolute. These file system paths often end being relative to something other than the file containing the map.

    "Under the hood" this loader uses PostCSS, which actually doesn't know about webpack's current request and remaining request. It only cares about file system paths. Part of the fix involves setting both the from (unmodified) and the to argument to being loader.resourcePath.

    Using file system paths in maps is possible, but it is best left to the plugin responsible for writing the source map to the css file or the map file. The style-loader will have some additional considerations that are unique to it.

    Once css-loader and sass-loader are fixed, postcss-loader and others will eventually need PRs as well.

    Because the fix is a breaking change, but people may want to use it immediately (such as testing it with other loaders needing similar fixes), it has been implemented as a new option.

    Does this PR introduce a breaking change? No, but the intent is a future major version could make the opt-in fix the default behavior.

    Other information This contributes to the fixes for

    • https://github.com/webpack-contrib/css-loader/issues/652
    • https://github.com/webpack-contrib/sass-loader/issues/529
    type: Bug severity: 3 (broken) status: Needs triage semver: Patch pr_action: Discuss priority: 4 (important) 
    opened by npetruzzelli 38
  • Update README.md

    Update README.md

    It is not true, that to use css-loader webpack 5 is needed.

    This PR contains a:

    • [ ] bugfix
    • [ ] new feature
    • [ ] code refactor
    • [ ] test update
    • [x] typo fix
    • [ ] metadata update

    Motivation / Use-Case

    I was just brushing up on my webpack skills, and noticed this error.

    Breaking Changes

    Additional Info

    opened by hencca 2
  • build: drop node v12

    build: drop node v12

    This PR contains a:

    • [ ] bugfix
    • [ ] new feature
    • [ ] code refactor
    • [ ] test update
    • [ ] typo fix
    • [x] metadata update

    Motivation / Use-Case

    Breaking Changes

    Additional Info

    opened by snitin315 1
  • chore: ignore yarn.lock

    chore: ignore yarn.lock

    This PR contains a:

    • [ ] bugfix
    • [ ] new feature
    • [ ] code refactor
    • [ ] test update
    • [ ] typo fix
    • [x] metadata update

    Motivation / Use-Case

    Ignore yarn.lock to prevent accidentally committing this file.

    Breaking Changes

    No

    Additional Info

    No

    opened by ersachin3112 1
  • css module keyframes not working properly when using special characters

    css module keyframes not working properly when using special characters

    Bug report

    CSS modules are not being processed properly when there are special characters in the animation name. For example:

    @-webkit-keyframes \@bounce {
      0%, 100% {
        transform: translateY(-25%);
        -webkit-animation-timing-function: cubic-bezier(0.8,0,1,1);
                animation-timing-function: cubic-bezier(0.8,0,1,1);
      }
    
      50% {
        transform: none;
        -webkit-animation-timing-function: cubic-bezier(0,0,0.2,1);
                animation-timing-function: cubic-bezier(0,0,0.2,1);
      }
    }
    
    @keyframes \@bounce {
      0%, 100% {
        transform: translateY(-25%);
        -webkit-animation-timing-function: cubic-bezier(0.8,0,1,1);
                animation-timing-function: cubic-bezier(0.8,0,1,1);
      }
    
      50% {
        transform: none;
        -webkit-animation-timing-function: cubic-bezier(0,0,0.2,1);
                animation-timing-function: cubic-bezier(0,0,0.2,1);
      }
    }
    
    .container {
      -webkit-animation: \@bounce 1s infinite;
      animation: \@bounce 1s infinite;
    }
    

    Actual Behavior

    Keyframes do not work when applied with a special character

    Expected Behavior

    Keyframes defined with special characters should be respected within css modules. With respect to my repro, localhost:3000/ and localhost:3000/home2 should both produce the same visual result

    How Do We Reproduce?

    Steps to reproduce:

    1. Pull down the following repo: https://github.com/william-will-angi/css-loader-repro/tree/master/css-loader-repro
    2. npm i and npm run dev
    3. Navigate to localhost:3000/ and notice there is no animation
    4. Navigate to localhost:3000/home2/ and notice the animation is there

    In this app, both pages have the same styles, with the exception of localhost:3000/ having their keyframes & class names prefixed with the special character @.

    Please paste the results of npx webpack-cli info here, and mention other relevant information

    Results:

      System:
        OS: macOS 10.15.7
        CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
        Memory: 36.91 MB / 16.00 GB
      Binaries:
        Node: 16.14.1 - ~/.nvm/versions/node/v16.14.1/bin/node
        Yarn: 1.22.18 - ~/.yvm/shim/yarn
        npm: 8.5.0 - ~/.nvm/versions/node/v16.14.1/bin/npm
      Browsers:
        Brave Browser: 98.1.35.104
        Chrome: 99.0.4844.74
        Firefox: 94.0.1
        Safari: 15.4
    
    
    opened by william-will-angi 4
  • Fix url option signature

    Fix url option signature

    This PR contains a:

    • [x] bugfix
    • [ ] new feature
    • [ ] code refactor
    • [ ] test update
    • [ ] typo fix
    • [ ] metadata update

    Motivation / Use-Case

    The current signature results in this error:

    ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.
     - options.url has an unknown property 'url'. These properties are valid:
       object { filter? }
    

    Breaking Changes

    Additional Info

    opened by felds 2
Releases(v6.7.3)
Owner
webpack-contrib
Community supported 3rd party packages for webpack
webpack-contrib
Reseter.css - A Futuristic CSS Reset / CSS Normalizer

Reseter.css A CSS Reset/Normalizer Reseter.css is an awesome CSS reset for a website. It is a great tool for any web designer. Reseter.css resets all

Krish Dev DB 1.1k Jan 2, 2023
Spectre.css - A Lightweight, Responsive and Modern CSS Framework

Spectre.css Spectre.css is a lightweight, responsive and modern CSS framework. Lightweight (~10KB gzipped) starting point for your projects Flexbox-ba

Yan Zhu 11.1k Jan 8, 2023
Low-level CSS Toolkit – the original Functional/Utility/Atomic CSS library

Basscss Low-level CSS toolkit – the original Functional CSS library https://basscss.com Lightning-Fast Modular CSS with No Side Effects Basscss is a l

Basscss 5.8k Dec 31, 2022
Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation

Aphrodite Framework-agnostic CSS-in-JS with support for server-side rendering, browser prefixing, and minimum CSS generation. Support for colocating y

Khan Academy 5.3k Jan 1, 2023
CSS Boilerplate / Starter Kit: Collection of best-practice CSS selectors

Natural Selection Natural Selection is a CSS framework without any styling at all. It is just a collection of selectors that can be used to define glo

FrontAid CMS 104 Dec 8, 2022
Source code for Chrome/Edge/Firefox/Opera extension Magic CSS (Live editor for CSS, Less & Sass)

Live editor for CSS, Less & Sass (Magic CSS) Extension Live editor for CSS, Less & Sass (Magic CSS) for Google Chrome, Microsoft Edge, Mozilla Firefox

null 210 Dec 13, 2022
Easily create css variables without the need for a css file!

Tailwind CSS Variables This plugin allows you to configure CSS variables in the tailwind.config.js Similar to the tailwindcss configurations you are u

Mert Aşan 111 Dec 22, 2022
Cooltipz.css - A highly customisable, minimal, pure CSS tooltip library

Cooltipz.css - Cool tooltips Cool customisable tooltips made from pure CSS Lightweight • Accessible • Customisable • Simple Cooltipz.css is a pure CSS

Jack Domleo 110 Dec 24, 2022
micro-library for CSS Flexbox and CSS Grid

SpeedGrid micro-library for CSS Flexbox and CSS Grid Overview SpeedGrid dynamically generates inline CSS by specifying the class name. Easy maintenanc

Toshihide Miyake 7 Mar 26, 2022
Data-tip.css - Wow, such tooltip, with pure css!

Notice: hint.css has been much better since I complained about it months ago, so try out its new features instead of this one! data-tip.css Wow, such

EGOIST 117 May 26, 2021
Tiny CSS framework with almost no classes and some pure CSS effects

no.css INTERACTIVE DEMO I am tired of adding classes to style my HTML. I just want to include a .css file and I expect it to style the HTML for me. no

null 96 Dec 10, 2022
The most popular HTML, CSS, and JavaScript framework for developing responsive, mobile first projects on the web.

Bootstrap Sleek, intuitive, and powerful front-end framework for faster and easier web development. Explore Bootstrap docs » Report bug · Request feat

Bootstrap 161k Jan 1, 2023
Modern CSS framework based on Flexbox

Bulma Bulma is a modern CSS framework based on Flexbox. Quick install Bulma is constantly in development! Try it out now: NPM npm install bulma or Yar

Jeremy Thomas 46.6k Dec 31, 2022
A utility-first CSS framework for rapid UI development.

A utility-first CSS framework for rapidly building custom user interfaces. Documentation For full documentation, visit tailwindcss.com. Community For

Tailwind Labs 63.5k Dec 30, 2022
Materialize, a CSS Framework based on Material Design

MaterializeCSS Materialize, a CSS Framework based on material design. -- Browse the docs -- Table of Contents Quickstart Documentation Supported Brows

Alvin Wang 38.8k Jan 2, 2023
Material Design Components in HTML/CSS/JS

Material Design Lite An implementation of Material Design components in vanilla CSS, JS, and HTML. Material Design Lite (MDL) lets you add a Material

Google 32.1k Jan 4, 2023
A set of small, responsive CSS modules that you can use in every web project.

Pure A set of small, responsive CSS modules that you can use in every web project. http://purecss.io/ This project is looking for maintainers to suppo

Pure CSS 22.7k Jan 3, 2023
Functional css for humans

TACHYONS Functional CSS for humans. Quickly build and design new UI without writing CSS. Principles Everything should be 100% responsive Everything sh

null 11.3k Jan 4, 2023
The CSS design system that powers GitHub

Primer CSS The CSS implementation of GitHub's Primer Design System Migrating ?? If you currently use the primer or primer--prefixed npm packages, plea

Primer 11.6k Jan 3, 2023