Correct way to apply global styles into Shadow DOM

前端 未结 2 758
梦如初夏
梦如初夏 2020-12-14 23:19

This questions is similar to some other on StackOverflow, but I couldn\'t find any answer describing applicable to my situation and non-deprecated method (and I\'m starting

2条回答
  •  被撕碎了的回忆
    2020-12-14 23:54

    I managed to do it using javascript modules but I doubt it's the cleanest solution. You can create a GlobalStyles.js file that will contain the css styling that is common throughout various components. Changing the language mode on your editor to 'html' will provide syntax highlighting for the css.

    const GlobalStyles = {
        main: `
            
        `,
    
        button: `
            
        `
    }
    
    export default GlobalStyles;
    

    Afterwards, you can import it into another js file that contains the code to the shadow dom of your custom element.

    import GlobalStyles from './GlobalStyles.js';
    
    const template = document.createElement('template');
    template.innerHTML = `
    
       ${GlobalStyles.button}
    
       
    
    
    
       
      `; export class CustomList extends HTMLElement { constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot.appendChild(document.importNode(template.content, true)); } }

      The drawback with this approach is it only works if you are working purely with js files.

    提交回复
    热议问题