mke21
mke21

Reputation: 165

shadowDOM style in webpack

I'm writing a custom element in plain javascript in a webpack package for the first time. I'm using this as an example: reusable custom select element in javascript

I use style-loader in this project as well.

In this example the styles are created in text within the object, here a simplified version of how I create the object and set the style:

class object extends HTMLElement{
   constructor(){
     super();
     shadow = this.attachShadow({mode: "open"});
     ...
     let div = document.createElement("div");
     div.classList.add("main");
     ...
     let style = document.createElement("style");
     style.textContent = ".main{background-color=red;}"
     ...
     shadow.appendChild(div);
  }
}

Apparently when the css get's longer, this method of setting style.textContent will become tedious.

My question is, can you separate the css code into another file? I read that style-loader does not work and my experiments confirmed that. I've also tried to import a css file and tried to insert that into the style object somehow. I couldn't get it to work. Anybody an idea?

Upvotes: 0

Views: 1229

Answers (1)

The very first question should always be; Do I really really need shadowDOM?

  • If not, all your issues are solved because you only have to deal with global CSS.

  • If you do.. there are many possibilities to learn:
    https://css-tricks.com/styling-a-web-component/

    • CSS variables
    • ::parts
    • lightDOM & SLOTs
    • Constructable StyleSheets
    • etc

Note, your code can be optimized:

 constructor(){
     let div = document.createElement("div");
     div.classList.add("main");

     let style = document.createElement("style");
     style.textContent = ".main{background-color=red;}"

     super() // sets and returns this-scope
        .attachShadow({mode: "open"}) // sets and returns this.shadowRoot
        .append(style,div); // read MDN for difference with appendChild
  }

The statement call super() first in Google & MDN documentation is wrong; it should say:

"call super() to initialize the 'this' scope"

Upvotes: 2

Related Questions