Guide Creating A Web Component - ProjectEvergreen/create-evergreen-app GitHub Wiki
If you're interested in helping us with writing documentation for this, please feel free to comment in this issue and say hi! 👋
Create a new evergreen-app.
npx create-evergreen-app my-app
cd my-app
Make a new file within the src/components
folder called MyComponent.js
Note If you're using visual studio code, a quick shortcut to scaffold a new component is to install and use the vscode-evergreen extension. Once installed, simply type: evc
then press tab, within a new file, within the editor window, to quickly create a component.
First, at the top, we need to add our dependency, which is the LitElement base class for creating web components
import { html, LitElement } from '@polymer/lit-element';
Next we need to add our class name which extends that base class.
import { html, LitElement } from '@polymer/lit-element';
class MyComponent extends LitElement {
}
Now we need to define the custom element name that our component will be called with at the bottom. Our element will be called <my-component></my-component>
import { html, LitElement } from '@polymer/lit-element';
class MyComponent extends LitElement {
}
customElements.define('my-component', MyComponent);
Finally our example component needs a render
method to return the html to the page it's embedded on.
import { html, LitElement } from '@polymer/lit-element';
class MyComponent extends LitElement {
render() {
return html`
<div>
Hello world!
</div>
`;
}
}
customElements.define('my-component', MyComponent);
Now to use our new component we can import it and then render it. Let's add it to our src/app/app.js
file:
At the top, below the other imports, add:
import '../components/MyComponent';
Now within the render
method, change it so the final app.js
file looks like this:
import { html, LitElement } from '@polymer/lit-element';
import css from './app.css';
import '../components/MyComponent';
class AppComponent extends LitElement {
render() {
return html`
<style>
${css}
</style>
<div>
<my-component></my-component>
</div>
`;
}
}
customElements.define('eve-app', AppComponent);
The app.js
is the root component of our example project. It's the first file imported into the javascript that gets bundled in our application.
We can now run our project and see our rendered component:
npm run develop
You should now be able to see your new component, rendered within the example application, at: http://localhost:1981/