Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
127 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65932857/shadowdom-style-in-webpack

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...