Single File Component LitElement loader for Webpack
Checkout the working repository for a more comprehensive example: https://github.com/PolymerX/lit-loader-example
Because we love separation of concerns also without separation of files! This loader will produce a Web Component using the LitElement starting from a Single File Component, like Vue.
The loader does a simple job: take your .lit
file and build up as single js
file. And you can easily use PostCSS on your styles.
$ yarn add --dev lit-loader
Add the loader to your Webpack conf webpack.config.js
:
...
module: {
rules: [
{
test: /\.lit$/,
loader: 'lit-loader'
}
]
}
...
CounterElement.lit
<style lang="postcss"> <!-- This will enable PostCSS compilation -->
span {
width: 20px;
display: inline-block;
text-align: center;
font-weight: bold;
}
</style>
<template>
<div>
<p>
Clicked: <span>${this.clicks}</span> times.
Value is <span>${this.value}</span>.
<button @click="${this._onIncrement}" title="Add 1">+</button>
<button @click="${this._onDecrement}" title="Minus 1">-</button>
</p>
</div>
</template>
<script>
export default class CounterElement {
static get properties() { return {
clicks: Number,
value: Number
}};
constructor() {
super();
this.clicks = 0;
this.value = 0;
}
_onIncrement() {
this.value++;
this.clicks++;
this.dispatchEvent(new CustomEvent('counter-incremented'));
}
_onDecrement() {
this.value--;
this.clicks++;
this.dispatchEvent(new CustomEvent('counter-decremented'));
}
}
window.customElements.define('counter-element', CounterElement);
</script>
index.js
import {LitElement, html} from 'lit-element';
...
import './CounterElement.lit';
export default class MyApp extends LitElement {
...
_render(props) {
return html`
<div>
<counter-element></counter-element>
</div>
`
}
...
}
Just chain the babel-loader
AFTER the lit-loader
like so:
module: {
rules: [
{
test: /\.lit$/,
use: ['babel-loader', 'lit-loader']
}
]
}
You need to add a PostCSS configuration file (postcss.config.js
) if you want to use it.
I think this should be considered experimental and I will try to improve it as much as I can. I really would love to accept some PR's to improve the project. 🤘
MIT © LasaleFamine