Skip to content

Instantly share code, notes, and snippets.

@jpolete
Last active July 10, 2024 15:08
Show Gist options
  • Save jpolete/dbdb34a2685f43ed0b4cb312fe07f997 to your computer and use it in GitHub Desktop.
Save jpolete/dbdb34a2685f43ed0b4cb312fe07f997 to your computer and use it in GitHub Desktop.

Web Component Development

Follow these instructions to set up a dev environment for web component development using Lit. These instructions use Storybook for an accompanying component library.

Before You Start

IMPORTANT: Before you begin, make sure you install the latest versions of Node (20.15.0 at time of writing) and PNPM (9.4.0 at time of writing). This also assumes you have Visual Studio Code installed.


Project Setup

Starting with Storybook 8.0, you can create a Vite / Web Components (Lit) / Storybook project with these commands.

# Create Vite project using Lit template
$ pnpm create vite@latest my-webcomponents --template lit

# If using TypeScript...
# pnpm create vite@latest my-webcomponents --template lit-ts

# Move into the project folder
$ cd my-webcomponents

# Install StoryBook
$ pnpm dlx storybook@latest init

At this point Storybook will probably start. You can stop the server with ctrl + c.

# Initialize git repo
$ git init

# Add all files and commit
$ git add .  
$ git commit -m 'Initial commit'

# Open in VS Code
$ code .

Configure Build

Add a vite.config.js file with the following. Now running pnpm run build will build your project to the dist directory.

// vite.config.js

export default {
  build: {
    lib: {
      entry: 'src/my-element.js',
      formats: ['es'],
    }
  }
}

Create Your First Component

Create a new SampleComponent.js file in the src/stories folder. See Lit documentation for details on building components.

// src/stories/SampleComponent.js

import { LitElement, html, css } from "lit"

export class SampleComponent extends LitElement {
  static properties = {
    color: { type: String },
    text: { type: String }
  }

  constructor() {
    super()
    this.color = '#333'
    this.text = 'Sample Web Component'
  }

  static styles = css`
    :host {
      font-family: sans-serif;
      font-size: .9rem;
      display: inline-block;
      border: solid 1px #ccc;
      border-radius: .25rem;
      padding: .75rem .75rem .5rem;
      margin: 0;
    }
  `
  render () {
    return html`<span style='color: ${this.color}'>${this.text}</span>`
  }
}

window.customElements.define('mc-samplecomponent', SampleComponent)

export const buildSampleComponent = ({ color, text }) => {
  return html`<mc-samplecomponent color='${color}' text='${text}'></mc-samplecomponent>`
}

Now create a SampleComponent.stories.js in the same folder. This stories file will add your component to Storybook so that you can view and interact with it.

// src/stories/SampleComponent.stories.js

import { buildSampleComponent } from './SampleComponent'

export default {
  tags: ['autodocs'],
  component: 'mc-samplecomponent',
  render: buildSampleComponent
}

export const Simple = {
  args: {
    color: '#333',
    text: 'Hello, World!'
  }
}

If Storybook isn't already running, run pnpm run storybook. Storybook should open. You'll see your SampleComponent along with some prebuilt Storybook examples.

Expand Stories > SampleComponent > Docs. You should see your sample component and be able to view the code and adjust the color and text dynamically.

Building for Production

So far components are viewable only in Storybook. To use components in a real project, we need to configure the build.

Delete the contents of src/my-element.js and replace it with a single import of our component.

// src/my-element.js

/* eslint-disable no-unused-vars */
import { SampleComponent } from "./stories/SampleComponent"

Build the project.

$ pnpm run build

By default the build output is in dist folder.

As you develop components, add an import for each component to this entry point file.

Tip: This file can be renamed, just be sure to update the entry property in vite.config.js

Using Components in Production

Build the project, then include the JavaScript file from the dist directory in your project.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Project</title>
    <script src="build-file-from-dist-folder.js"></script>
</head>

<body>
    <mc-samplecomponent></mc-samplecomponent>
</body>

</html>

(Optional) Standard Coding Style and Formatting

To enforce a consistent coding style, install StandardJS to the development dependencies.

$ pnpm install -D standard

Add the following line to the scripts section of package.json.

...

  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "storybook": "storybook dev -p 6006",
    "build-storybook": "storybook build",
+    "standardjs": "standard --fix"
  },
  
...

Fix all code style violations in the project.

$ pnpm run standardjs

VS Code Extension

VS Code has a Standard JS extension that can automatically underline code style violations in the editor and even auto-fix on save so you don't have to remember to run standard from the command line.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment