7-style-loader 中文文档教程
7-style-loader
这是 style-loader 的分支版本,针对七个模块进行了修改
新功能:
- Extend the ability of attributes, you can use "[moduleName]" and "[moduleVersion]" template string in style tag attribute now.
Getting Started
首先,您需要安装 style-loader
:
npm install --save-dev style-loader
建议结合使用 style-loader
和 css-loader
然后将加载程序添加到您的 webpack
配置中。 例如:
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
Name | Type | Default | Description |
---|---|---|---|
injectType | {String} | styleTag | Allows to setup how styles will be injected into the DOM |
attributes | {Object} | {} | Adds custom attributes to tag |
insert | {String|Function} | head | Inserts tag at the given position into the DOM |
base | {Number} | true | Sets module ID base (DLLPlugin) |
esModule | {Boolean} | false | Use ES modules syntax |
injectType
类型:String
默认值:styleTag
允许设置将样式注入 DOM 的方式。
可能的值:
styleTag
singletonStyleTag
lazyStyleTag
lazySingletonStyleTag
linkTag
styleTag
使用多个 自动将样式注入 DOM。 这是默认行为。
component.js
import './styles.css';
局部变量示例(CSS 模块):
component-with-css-modules.js
import styles from './styles.css';
const divElement = document.createElement('div');
divElement.className = styles['my-class'];
所有局部变量(类名)都存储在导入的对象中。
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',
],
},
],
},
};
加载器注入样式如下:
<style>
.foo {
color: red;
}
</style>
<style>
.bar {
color: blue;
}
</style>
singletonStyleTag
使用一个 自动将样式注入 DOM。
⚠ 源地图不起作用。
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'];
导入对象中存储的所有局部变量(类名)。
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: 'style-loader',
options: { injectType: 'singletonStyleTag' },
},
'css-loader',
],
},
],
},
};
加载器注入样式如下:
<style>
.foo {
color: red;
}
.bar {
color: blue;
}
</style>
lazyStyleTag
根据需要使用多个 将样式注入 DOM。 我们建议遵循
.lazy.css
惰性样式的命名约定和 .css
的基本 style-loader
用法(类似于其他文件类型,即 .lazy.less
和 .less
)。 当您 lazyStyleTag
值时,style-loader
延迟注入样式,使它们可以通过 style.use()
/ style 按需使用.unuse()。
⚠️ 当
unuse
比use
更频繁地被调用时,行为是未定义的。 不要那样做。
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'];
导入对象的locals
属性中存储的所有局部变量(类名)。
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',
],
},
],
},
};
加载器注入样式如下:
<style>
.foo {
color: red;
}
</style>
<style>
.bar {
color: blue;
}
</style>
lazySingletonStyleTag
根据需要使用一个 将样式注入 DOM。 我们建议遵循
.lazy.css
惰性样式的命名约定和 .css
的基本 style-loader
用法(类似于其他文件类型,即 .lazy.less
和 .less
)。 当您 lazySingletonStyleTag
值时,style-loader
延迟注入样式,使它们可以通过 style.use()
/ style 按需使用.unuse()。
⚠️ 源地图不起作用。
⚠️ 当
unuse
比use
更频繁地被调用时,行为是未定义的。 不要那样做。
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'];
导入对象的locals
属性中存储的所有局部变量(类名)。
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: 'lazySingletonStyleTag' },
},
'css-loader',
],
},
],
},
};
加载器生成这个:
<style>
.foo {
color: red;
}
.bar {
color: blue;
}
</style>
linkTag
Injects styles into DOM using multiple 。
ℹ️ 加载器将在运行时通过 JavaScript 动态插入
标签。 你应该使用 MiniCssExtractPlugin 如果你想包含一个静态
。
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' },
],
},
],
},
};
加载器生成这个:
<link rel="stylesheet" href="path/to/style.css" />
<link rel="stylesheet" href="path/to/other-styles.css" />
attributes
类型:Object
默认值:{}
如果已定义,style-loader
会将给定的属性及其值附加到 /
< link>
元素。
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',
// according to "name" and "version" field in module.json
"data-module-name": '[moduleName]',
"data-module-version": '[moduleVersion]'
}
}
},
{ loader: 'css-loader' },
],
},
],
},
};
<style id="id"></style>
insert
类型:String|Function
默认值:head
默认情况下,style-loader
将 /
元素附加到样式目标的结尾,它是页面的
标记,除非由
insert
指定。
这将导致加载器创建的 CSS 优先于目标中已经存在的 CSS。
如果标准行为不适合您,您可以使用其他值,但我们不建议这样做。
如果您以 iframe 为目标,请确保您有足够的访问权限,样式将被注入进入内容文档头部。
String
允许设置自定义查询选择器,将样式注入 DOM。
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: 'style-loader',
options: {
insert: 'body',
},
},
'css-loader',
],
},
],
},
};
一个新的 /
元素将被插入到
body< 的底部/代码> 标签。
Function
允许覆盖默认行为并在任何位置插入样式。
⚠ 不要忘记此代码将在浏览器中使用,并非所有浏览器都支持最新的 ECMA 功能,如
let
、const
、arrow function expression
等等,我们建议仅使用 ECMA 5 功能,但这取决于您要支持的浏览器 ⚠ 不要忘记,某些 DOM 方法可能在旧版浏览器中不可用,我们建议仅使用 DOM 核心 2 级属性 ,但这取决于您要支持的浏览器
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',
],
},
],
},
};
在 head
标签的顶部插入样式。
base
当使用一个或多个 DllPlugin 的。 base
允许您防止 app 的 css(或 DllPlugin2 的 css)覆盖 DllPlugin1' s css 通过指定一个大于 DllPlugin1 使用的范围的 css 模块 id base 例如:
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',
],
},
],
},
};
esModule
类型:Boolean
默认值:false
默认情况下,style-loader
生成使用 CommonJS 模块语法的 JS 模块。 在某些情况下使用 ES 模块是有益的,例如 模块连接 和 < a href="https://webpack.js.org/guides/tree-shaking/">摇树。
您可以使用以下方式启用 ES 模块语法:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: 'css-loader',
options: {
esModule: true,
},
},
],
},
};
Examples
Source maps
加载程序会在前一个加载程序发出源映射时自动注入它们。 因此,要生成源映射,请将前一个加载程序的 sourceMap
选项设置为 true
。
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
'style-loader',
{ loader: 'css-loader', options: { sourceMap: true } },
],
},
],
},
};
Nonce
有两种方法可以使用nonce
:
- using the
attributes
option - using the
__webpack_nonce__
variable
⚠
attributes
选项优先于__webpack_nonce__
变量
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',
],
},
],
},
};
加载器生成:
<style nonce="12345678">
.foo {
color: red;
}
</style>
__webpack_nonce__
create-nonce.js
__webpack_nonce__ = '12345678';
component.js
import './create-nonce.js';
import './style.css';
require
的替代示例:
component.js
__webpack_nonce__ = '12345678';
require('./style.css');
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
};
加载程序生成:
<style nonce="12345678">
.foo {
color: red;
}
</style>
Insert styles at top
在 head
标签。
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
在 #id
元素之前插入样式。
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
如果您还没有阅读我们的贡献指南,请花点时间阅读。
License
7-style-loader
This is a forked version of style-loader, modified for seven-modules
New Feature:
- Extend the ability of attributes, you can use "[moduleName]" and "[moduleVersion]" template string in style tag attribute now.
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
Name | Type | Default | Description |
---|---|---|---|
injectType | {String} | styleTag | Allows to setup how styles will be injected into the DOM |
attributes | {Object} | {} | Adds custom attributes to tag |
insert | {String|Function} | head | Inserts tag at the given position into the DOM |
base | {Number} | true | Sets module ID base (DLLPlugin) |
esModule | {Boolean} | false | Use ES modules syntax |
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 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 thanuse
. 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 thanuse
. 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: 'lazySingletonStyleTag' },
},
'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',
// according to "name" and "version" field in module.json
"data-module-name": '[moduleName]',
"data-module-version": '[moduleVersion]'
}
}
},
{ 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',
],
},
],
},
};
esModule
Type: Boolean
Default: false
By default, style-loader
generates JS modules that use the CommonJS 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 ES module syntax using:
webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
loader: 'css-loader',
options: {
esModule: true,
},
},
],
},
};
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.