Skip to content

Commit c9beb0f

Browse files
docs: example for nonce usage (#410)
1 parent b6d39f5 commit c9beb0f

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed

README.md

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,108 @@ module.exports = {
574574
};
575575
```
576576

577+
### Nonce
578+
579+
There are two ways to work with `nonce`:
580+
581+
- using the `attirbutes` option
582+
- using the `__webpack_nonce__` variable
583+
584+
> ⚠ the `__webpack_nonce__` variable takes precedence over the `attibutes` option, so if define the `__webpack_nonce__` variable the `attributes` option will not be used
585+
586+
### `attirbutes`
587+
588+
**component.js**
589+
590+
```js
591+
import './style.css';
592+
```
593+
594+
**webpack.config.js**
595+
596+
```js
597+
module.exports = {
598+
module: {
599+
rules: [
600+
{
601+
test: /\.css$/i,
602+
use: [
603+
{
604+
loader: 'style-loader',
605+
options: {
606+
attributes: {
607+
nonce: '12345678',
608+
},
609+
},
610+
},
611+
'css-loader',
612+
],
613+
},
614+
],
615+
},
616+
};
617+
```
618+
619+
The loader generate:
620+
621+
```html
622+
<style nonce="12345678">
623+
.foo {
624+
color: red;
625+
}
626+
</style>
627+
```
628+
629+
### `webpack_nonce`
630+
631+
**create-nonce.js**
632+
633+
```js
634+
__webpack_nonce__ = '12345678';
635+
```
636+
637+
**component.js**
638+
639+
```js
640+
import './create-nonce.js';
641+
import './style.css';
642+
```
643+
644+
Alternative example for `require`:
645+
646+
**component.js**
647+
648+
```js
649+
__webpack_nonce__ = '12345678';
650+
651+
require('./style.css');
652+
```
653+
654+
**webpack.config.js**
655+
656+
```js
657+
module.exports = {
658+
module: {
659+
rules: [
660+
{
661+
test: /\.css$/i,
662+
use: ['style-loader', 'css-loader'],
663+
},
664+
],
665+
},
666+
};
667+
```
668+
669+
The loader generate:
670+
671+
```html
672+
<style nonce="12345678">
673+
.foo {
674+
color: red;
675+
}
676+
</style>
677+
```
678+
577679
## Contributing
578680

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

0 commit comments

Comments
 (0)