Skip to content

What I've Learned about Web Components

Describe what I've learned about web components while doing side project with web components.

Background

I wanted to organize what I’ve learned about web components while I’m doing side project with web components.

You can’t style deep inside your slot

References

How to make it easy to write html and css code with string literal

To solve problem with writing html and css in string literal without syntax highlighting and formatting, I made this util functions(html and css) using Tagged templates.

/**
 * Processes a template literal to combine strings and interpolated values into a single HTML string.
 *
 * @param {TemplateStringsArray} strings - An array of string literals.
 * @param {...string} values - Interpolated values within the template literal.
 * @returns {string} The combined HTML string.
 */
export function html(strings, ...values) {
  let htmlString = strings[0];

  for (let i = 0; i < values.length; i++) {
    htmlString += values[i] + strings[i + 1];
  }

  return htmlString;
}

/**
 * Processes a template literal to combine strings and interpolated values into a single CSS string.
 *
 * @param {TemplateStringsArray} strings - An array of string literals.
 * @param {...string} values - Interpolated values within the template literal.
 * @returns {string} The combined CSS string.
 */
export function css(strings, ...values) {
  const GlobalCSS = `<link rel="stylesheet" href="./global-styles.css" />`;

  return html`
    ${GlobalCSS}
    <style>
      ${html(strings, ...values)}
    </style>
  `;
}

use vscode extensions for syntax highlighting and formatting

I recommend this extension. This extension(Inline HTML) allows syntax highlighting and formatting in my vscode.

For CSS nesting at rules, syntax highlighting could be possibly broken. This extension helps you see the proper syntax highlighting in your editor.