Skip to content

Commit

Permalink
feat: allow to pass options to insert function through style.use()
Browse files Browse the repository at this point in the history
Allow to pass additional parameter to `style.use(anything)` which will be passed to `insert` function. This allows to insert each tag in different places and especially useful for Shadow DOM

Resolves #328
  • Loading branch information
OlegWock committed Sep 12, 2021
1 parent b21d81a commit 756560a
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,46 @@ module.exports = {

Insert styles at top of `head` tag.

You can pass any parameters to `style.use(anythingHere)` and this value will be passed to `insert` function.

**webpack.config.js**

```js
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: [
{
loader: "style-loader",
options: {
insert: function insertIntoTarget(element, options) {
var parent = options.target || document.querySelector("head");
parent.appendChild(element);
},
},
},
"css-loader",
],
},
],
},
};
```

Insert styles to the provided element or to the `head` tag if target isn't provided. Now you can inject styles into Shadow DOM (or any other element).

**component.js**

```js
import style from "./file.css";

style.use({
target: document.querySelector('#myShadowDom').shadowRoot,
})
```

### `styleTagTransform`

Type: `String | Function`
Expand Down
3 changes: 2 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,8 @@ ${getInsertOptionCode(insertType, options)}
options.domAPI = ${getdomAPI(isAuto)};
options.insertStyleElement = insertStyleElement;
exported.use = function() {
exported.use = function(insertOptions) {
options.insertOptions = insertOptions || {};
if (!(refs++)) {
update = API(content, options);
}
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/insertStyleElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ function insertStyleElement(options) {

options.setAttributes(style, options.attributes);

options.insert(style);
options.insert(style, options.insertOptions);

return style;
}
Expand Down

0 comments on commit 756560a

Please sign in to comment.