From 756560a076cf30ac935aacf7c024b0ef626a7ca8 Mon Sep 17 00:00:00 2001 From: OlegWock Date: Sun, 12 Sep 2021 18:07:19 +0300 Subject: [PATCH] feat: allow to pass options to `insert` function through `style.use()` 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 --- README.md | 40 +++++++++++++++++++++++++++++++ src/index.js | 3 ++- src/runtime/insertStyleElement.js | 2 +- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index e7e7bec2..d18ffc49 100644 --- a/README.md +++ b/README.md @@ -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` diff --git a/src/index.js b/src/index.js index 5f3c0711..1cd2bac6 100644 --- a/src/index.js +++ b/src/index.js @@ -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); } diff --git a/src/runtime/insertStyleElement.js b/src/runtime/insertStyleElement.js index 62199710..5295e18e 100644 --- a/src/runtime/insertStyleElement.js +++ b/src/runtime/insertStyleElement.js @@ -4,7 +4,7 @@ function insertStyleElement(options) { options.setAttributes(style, options.attributes); - options.insert(style); + options.insert(style, options.insertOptions); return style; }