
Research
2025 Report: Destructive Malware in Open Source Packages
Destructive malware is rising across open source registries, using delays and kill switches to wipe code, break builds, and disrupt CI/CD.
css-loader
Advanced tools
npm install --save-dev css-loader
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' ]
}
]
}
}
toStringYou can also use the css-loader results directly as 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'
]
}
| Name | Type | Default | Description |
|---|---|---|---|
root | {String} | / | Path to resolve URLs, URLs starting with / will not be translated |
url | {Boolean} | true | Enable/Disable url() handling |
alias | {Object} | {} | Create aliases to import certain modules more easily |
import | {Boolean} | true | Enable/Disable @import handling |
modules | {Boolean} | false | Enable/Disable CSS Modules |
minimize | {Boolean|Object} | false | Enable/Disable minification |
sourceMap | {Boolean} | false | Enable/Disable Sourcemaps |
camelCase | {Boolean|String} | false | Export Classnames in CamelCase |
importLoaders | {Number} | 0 | Number of loaders applied before CSS loader |
localIdentName | {String} | [hash:base64] | Configure the generated ident |
rootFor URLs that start with a /, the default behavior is to not translate them.
url(/image.png) => url(/image.png)
If a root query parameter is set, however, it will be prepended to the URL
and then translated.
webpack.config.js
{
loader: 'css-loader',
options: { root: '.' }
}
url(/image.png) => require('./image.png')
Using 'Root-relative' urls is not recommended. You should only use it for legacy CSS files.
urlTo 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')
aliasRewrite your urls with alias, this is useful when it's hard to change url paths of your input files, for example, when you're using some css / sass files in another package (bootstrap, ratchet, font-awesome, etc.).
css-loader's alias follows the same syntax as webpack's resolve.alias, you can see the details at the [resolve docs] (https://webpack.js.org/configuration/resolve/#resolve-alias)
file.scss
@charset "UTF-8";
@import "bootstrap";
webpack.config.js
{
test: /\.scss$/,
use: [
{
loader: "style-loader"
},
{
loader: "css-loader",
options: {
alias: {
"../fonts/bootstrap": "bootstrap-sass/assets/fonts/bootstrap"
}
}
},
{
loader: "sass-loader",
options: {
includePaths: [
path.resolve("./node_modules/bootstrap-sass/assets/stylesheets")
]
}
}
]
}
Check out this working bootstrap example.
importTo 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 modulescomposes: xxx from 'path/to/file.css'feature.
modulesThe 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.).
ScopeBy 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 local scope. The local identifiers are exported by the module.
With :local (without brackets) local mode can be switched on for this selector. :global(.className) 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 choosen 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; }
:information_source: Identifiers are exported
exports.locals = {
className: '_23_aKvs-b8bW2Vg3fwHozO',
subClass: '_13LGdX8RMStbBE9w-t0gZ1'
}
CamelCase is recommended for local selectors. They are easier to use in the within the imported JS module.
url() URLs in block scoped (:local .abc) rules behave like requests in modules.
file.png => ./file.png
~module/file.png => module/file.png
You can use :local(#someId), but this is not recommended. Use classes instead of ids.
You can configure the generated ident with the localIdentName query parameter (default [hash:base64]).
webpack.config.js
{
test: /\.css$/,
use: [
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]'
}
}
]
}
You can also specify the absolute path to your custom getLocalIdent function to generate classname based on a different schema. This requires webpack >= 2.2.1 (it supports functions in the options object).
webpack.config.js
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: '[path][name]__[local]--[hash:base64:5]',
getLocalIdent: (context, localIdentName, localName, options) => {
return 'whatever_random_class_name'
}
}
}
:information_source: For prerendering with extract-text-webpack-plugin you should use
css-loader/localsinstead ofstyle-loader!css-loaderin the prerendering bundle. It doesn't embed CSS but only exports the identifier mappings.
ComposingWhen 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;
}
ImportingTo import a local classname from another module.
: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;
}
minimizeBy default the css-loader minimizes the css if specified by the module system.
In some cases the minification is destructive to the css, so you can provide your own options to the cssnano-based minifier if needed. See cssnano's documentation for more information on the available options.
You can also disable or enforce minification with the minimize query parameter.
webpack.config.js
{
loader: 'css-loader',
options: {
minimize: true || {/* CSSNano Options */}
}
}
sourceMapTo include source maps set the sourceMap option.
I. e. the extract-text-webpack-plugin can handle them.
They are not enabled by default because they expose a runtime overhead and increase in bundle size (JS source maps do not). In addition to that relative paths are buggy and you need to use an absolute public path which include the server URL.
webpack.config.js
{
loader: 'css-loader',
options: {
sourceMap: true
}
}
camelCaseBy default, the exported JSON keys mirror the class names. If you want to camelize class names (useful in JS), pass the query parameter camelCase to css-loader.
| Name | Type | Description |
|---|---|---|
true | {Boolean} | Class names will be camelized |
'dashes' | {String} | Only dashes in class names will be camelized |
'only' | {String} | Introduced in 0.27.1. Class names will be camelized, the original class name will be removed from the locals |
'dashesOnly' | {String} | Introduced in 0.27.1. 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
{
loader: 'css-loader',
options: {
camelCase: true
}
}
importLoadersThe query parameter importLoaders allows to configure how many loaders before css-loader should be applied to @imported resources.
webpack.config.js
{
test: /\.css$/,
use: [
'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1 // 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.
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.
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
},
{
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
loader: 'url-loader',
options: {
limit: 10000
}
}
]
}
}
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 extract-text-webpack-plugin to extract the CSS when running in production mode.
webpack.config.js
const env = process.env.NODE_ENV
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: env === 'production'
? ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [ 'css-loader' ]
})
: [ 'style-loader', 'css-loader' ]
},
]
},
plugins: env === 'production'
? [
new ExtractTextPlugin({
filename: '[name].css'
})
]
: []
}
Juho Vepsäläinen |
Joshua Wiens |
Kees Kluskens |
Sean Larkin |
Michael Ciniawsky |
Evilebot Tnawi |
Joscha Feth |
Injects CSS into the DOM using multiple <style> tags. It is often used in conjunction with css-loader.
Loads and compiles Sass/SCSS files. It extends css-loader's functionality to work with Sass/SCSS syntax.
Processes Less files and compiles them to CSS. Similar to sass-loader, it's specific to Less preprocessor language.
Processes CSS with PostCSS, a tool for transforming CSS with JavaScript plugins. It can be used after css-loader to apply various transformations and optimizations.
Extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It is used for CSS splitting, and is more performant than style-loader for production builds.
FAQs
css loader module for webpack
The npm package css-loader receives a total of 9,484,183 weekly downloads. As such, css-loader popularity was classified as popular.
We found that css-loader demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Research
Destructive malware is rising across open source registries, using delays and kill switches to wipe code, break builds, and disrupt CI/CD.

Security News
Socket CTO Ahmad Nassri shares practical AI coding techniques, tools, and team workflows, plus what still feels noisy and why shipping remains human-led.

Research
/Security News
A five-month operation turned 27 npm packages into durable hosting for browser-run lures that mimic document-sharing portals and Microsoft sign-in, targeting 25 organizations across manufacturing, industrial automation, plastics, and healthcare for credential theft.