css-loader
css loader module for webpack
Last updated 15 days ago by evilebottnawi .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install css-loader 
SYNC missed versions from official npm registry.

npm node deps tests coverage chat

CSS Loader

Install

npm install --save-dev css-loader

Usage

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

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

file.js

import css from 'file.css';

webpack.config.js

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

toString

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

webpack.config.js

{
   test: /\.css$/,
   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

{
   test: /\.css$/,
   use: [
     'handlebars-loader', // handlebars loader expects raw resource string
     'extract-loader',
     'css-loader'
   ]
}

Options

Name Type Default Description
url {Boolean} true Enable/Disable url() handling
import {Boolean} true Enable/Disable @import handling
modules {Boolean} false Enable/Disable CSS Modules
localIdentName {String} [hash:base64] Configure the generated ident
sourceMap {Boolean} false Enable/Disable Sourcemaps
camelCase {Boolean\|String} false Export Classnames in CamelCase
importLoaders {Number} 0 Number of loaders applied before CSS loader

url

To disable url() resolving by css-loader set the option to false.

To be compatible with existing css files (if not in CSS Module mode).

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

import

To disable @import resolving by css-loader set the option to false

@import url('https://fonts.googleapis.com/css?family=Roboto');

⚠️ Use with caution, since this disables resolving for all @imports, including css modules composes: xxx from 'path/to/file.css' feature.

modules

The query parameter modules enables the CSS Modules spec.

This enables local scoped CSS by default. (You can switch it off with :global(...) or :global for selectors and/or rules.).

Scope

By default CSS exports all classnames into a global selector scope. Styles can be locally scoped to avoid globally scoping styles.

The syntax :local(.className) can be used to declare className in the