Join our webinar on Wednesday, June 26, at 1pm EDTHow Chia Mitigates Risk in the Crypto Industry.Register
Socket
Socket
Sign inDemoInstall

style-loader

Package Overview
Dependencies
292
Maintainers
8
Versions
76
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    style-loader

style loader module for webpack


Version published
Weekly downloads
14M
increased by0.12%
Maintainers
8
Created
Weekly downloads
 

Package description

What is style-loader?

The style-loader npm package is used to inject CSS into the DOM using multiple strategies. It is often used in combination with css-loader in webpack configurations to handle styles within JavaScript modules.

What are style-loader's main functionalities?

Inject styles into the DOM

This code sample demonstrates how to use style-loader in combination with css-loader to import a CSS file and inject the styles into the DOM.

import style from 'style-loader!css-loader!./style.css';

Useable styles

This code sample shows how to use the useable feature of style-loader to manually control when styles are injected into and removed from the DOM.

import style from 'style-loader/useable!css-loader!./style.css';
style.use(); // Injects styles
tyle.unuse(); // Removes styles

Lazy loading styles

This code sample illustrates how to lazy load styles with style-loader, which can be useful for code splitting scenarios.

import loadStyle from 'style-loader!css-loader!./style.css';
loadStyle().then(style => {
  // Use style here
});

Other packages similar to style-loader

Changelog

Source

1.0.2 (2019-12-17)

Bug Fixes

  • support ES module syntax (#435) (dcbfadb)

Readme

Source

Style Loader

npm node deps tests coverage chat size

style-loader

Inject CSS into the DOM.

Getting Started

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

npm install --save-dev style-loader

It's recommended to combine style-loader with the css-loader

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

style.css

body {
  background: green;
}

component.js

import './style.css';

webpack.config.js

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

Options

NameTypeDefaultDescription
injectType{String}styleTagAllows to setup how styles will be injected into the DOM
attributes{Object}{}Adds custom attributes to tag
insert{String|Function}headInserts tag at the given position into the DOM
base{Number}trueSets module ID base (DLLPlugin)

injectType

Type: String Default: styleTag

Allows to setup how styles will be injected into the DOM.

Possible values:

  • styleTag
  • singletonStyleTag
  • lazyStyleTag
  • lazySingletonStyleTag
  • linkTag
styleTag

Automatically injects styles into the DOM using multiple <style></style>. It is default behaviour.

component.js

import './styles.css';

Example with c Locals (CSS Modules):

component-with-css-modules.js

import styles from './styles.css';

const divElement = document.createElement('div');
divElement.className = styles['my-class'];

All locals (class names) stored in imported object.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          // The `injectType`  option can be avoided because it is default behaviour
          { loader: 'style-loader', options: { injectType: 'styleTag' } },
          'css-loader',
        ],
      },
    ],
  },
};

The loader inject styles like:

<style>
  .foo {
    color: red;
  }
</style>
<style>
  .bar {
    color: blue;
  }
</style>
singletonStyleTag

Automatically injects styles into the DOM using one <style></style>.

⚠ Source maps do not work.

component.js

import './styles.css';

component-with-css-modules.js

import styles from './styles.css';

const divElement = document.createElement('div');
divElement.className = styles['my-class'];

All locals (class names) stored in imported object.

webpack.config.js

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

The loader inject styles like:

<style>
  .foo {
    color: red;
  }
  .bar {
    color: blue;
  }
</style>
lazyStyleTag

Injects styles into the DOM using multiple <style></style> on demand. We recommend following .lazy.css naming convention for lazy styles and the .css for basic style-loader usage (similar to other file types, i.e. .lazy.less and .less). When you lazyStyleTag value the style-loader injects the styles lazily making them useable on-demand via style.use() / style.unuse().

⚠️ Behavior is undefined when unuse is called more often than use. Don't do that.

component.js

import styles from './styles.lazy.css';

styles.use();
// For removing styles you can use
// styles.unuse();

component-with-css-modules.js

import styles from './styles.lazy.css';

styles.use();

const divElement = document.createElement('div');
divElement.className = styles.locals['my-class'];

All locals (class names) stored in locals property of imported object.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        exclude: /\.lazy\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.lazy\.css$/i,
        use: [
          { loader: 'style-loader', options: { injectType: 'lazyStyleTag' } },
          'css-loader',
        ],
      },
    ],
  },
};

The loader inject styles like:

<style>
  .foo {
    color: red;
  }
</style>
<style>
  .bar {
    color: blue;
  }
</style>
lazySingletonStyleTag

Injects styles into the DOM using one <style></style> on demand. We recommend following .lazy.css naming convention for lazy styles and the .css for basic style-loader usage (similar to other file types, i.e. .lazy.less and .less). When you lazySingletonStyleTag value the style-loader injects the styles lazily making them useable on-demand via style.use() / style.unuse().

⚠️ Source maps do not work.

⚠️ Behavior is undefined when unuse is called more often than use. Don't do that.

component.js

import styles from './styles.css';

styles.use();
// For removing styles you can use
// styles.unuse();

component-with-css-modules.js

import styles from './styles.lazy.css';

styles.use();

const divElement = document.createElement('div');
divElement.className = styles.locals['my-class'];

All locals (class names) stored in locals property of imported object.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        exclude: /\.lazy\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.lazy\.css$/i,
        use: [
          { loader: 'style-loader', options: { injectType: 'lazyStyleTag' } },
          'css-loader',
        ],
      },
    ],
  },
};

The loader generate this:

<style>
  .foo {
    color: red;
  }
  .bar {
    color: blue;
  }
</style>
linkTag

Injects styles into the DOM using multiple <link rel="stylesheet" href="path/to/file.css"> .

ℹ️ The loader will dynamically insert the <link href="path/to/file.css" rel="stylesheet"> tag at runtime via JavaScript. You should use MiniCssExtractPlugin if you want to include a static <link href="path/to/file.css" rel="stylesheet">.

import './styles.css';
import './other-styles.css';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.link\.css$/i,
        use: [
          { loader: 'style-loader', options: { injectType: 'linkTag' } },
          { loader: 'file-loader' },
        ],
      },
    ],
  },
};

The loader generate this:

<link rel="stylesheet" href="path/to/style.css" />
<link rel="stylesheet" href="path/to/other-styles.css" />

attributes

Type: Object Default: {}

If defined, the style-loader will attach given attributes with their values on <style> / <link> element.

component.js

import style from './file.css';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          { loader: 'style-loader', options: { attributes: { id: 'id' } } },
          { loader: 'css-loader' },
        ],
      },
    ],
  },
};
<style id="id"></style>

insert

Type: String|Function Default: head

By default, the style-loader appends <style>/<link> elements to the end of the style target, which is the <head> tag of the page unless specified by insert. This will cause CSS created by the loader to take priority over CSS already present in the target. You can use other values if the standard behavior is not suitable for you, but we do not recommend doing this. If you target an iframe make sure you have sufficient access rights, the styles will be injected into the content document head.

String

Allows to setup custom query selector where styles inject into the DOM.

webpack.config.js

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

A new <style>/<link> elements will be inserted into at bottom of body tag.

Function

Allows to override default behavior and insert styles at any position.

⚠ Do not forget that this code will be used in the browser and not all browsers support latest ECMA features like let, const, arrow function expression and etc, we recommend use only ECMA 5 features, but it is depends what browsers you want to support ⚠ Do not forget that some DOM methods may not be available in older browsers, we recommended use only DOM core level 2 properties, but it is depends what browsers you want to support

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              insert: function insertAtTop(element) {
                var parent = document.querySelector('head');
                // eslint-disable-next-line no-underscore-dangle
                var lastInsertedElement =
                  window._lastElementInsertedByStyleLoader;

                if (!lastInsertedElement) {
                  parent.insertBefore(element, parent.firstChild);
                } else if (lastInsertedElement.nextSibling) {
                  parent.insertBefore(element, lastInsertedElement.nextSibling);
                } else {
                  parent.appendChild(element);
                }

                // eslint-disable-next-line no-underscore-dangle
                window._lastElementInsertedByStyleLoader = element;
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

Insert styles at top of head tag.

base

This setting is primarily used as a workaround for css clashes when using one or more DllPlugin's. base allows you to prevent either the app's css (or DllPlugin2's css) from overwriting DllPlugin1's css by specifying a css module id base which is greater than the range used by DllPlugin1 e.g.:

webpack.dll1.config.js

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

webpack.dll2.config.js

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

webpack.app.config.js

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

Examples

Source maps

The loader automatically inject source maps when previous loader emit them. Therefore, to generate source maps, set the sourceMap option to true for the previous loader.

webpack.config.js

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

Nonce

There are two ways to work with nonce:

  • using the attributes option
  • using the __webpack_nonce__ variable

⚠ the attributes option takes precedence over the __webpack_nonce__ variable

attributes

component.js

import './style.css';

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              attributes: {
                nonce: '12345678',
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

The loader generate:

<style nonce="12345678">
  .foo {
    color: red;
  }
</style>
__webpack_nonce__

create-nonce.js

__webpack_nonce__ = '12345678';

component.js

import './create-nonce.js';
import './style.css';

Alternative example for require:

component.js

__webpack_nonce__ = '12345678';

require('./style.css');

webpack.config.js

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

The loader generate:

<style nonce="12345678">
  .foo {
    color: red;
  }
</style>
Insert styles at top

Inserts styles at top of head tag.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              insert: function insertAtTop(element) {
                var parent = document.querySelector('head');
                var lastInsertedElement =
                  window._lastElementInsertedByStyleLoader;

                if (!lastInsertedElement) {
                  parent.insertBefore(element, parent.firstChild);
                } else if (lastInsertedElement.nextSibling) {
                  parent.insertBefore(element, lastInsertedElement.nextSibling);
                } else {
                  parent.appendChild(element);
                }

                window._lastElementInsertedByStyleLoader = element;
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};
Insert styles before target element

Inserts styles before #id element.

webpack.config.js

module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              insert: function insertBeforeAt(element) {
                const parent = document.querySelector('head');
                const target = document.querySelector('#id');

                const lastInsertedElement =
                  window._lastElementInsertedByStyleLoader;

                if (!lastInsertedElement) {
                  parent.insertBefore(element, target);
                } else if (lastInsertedElement.nextSibling) {
                  parent.insertBefore(element, lastInsertedElement.nextSibling);
                } else {
                  parent.appendChild(element);
                }

                window._lastElementInsertedByStyleLoader = element;
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};

Contributing

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

CONTRIBUTING

License

MIT

Keywords

FAQs

Last updated on 17 Dec 2019

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc