Experimenting with x-postpress
Monday, 14 January 2019
While building using the custom elements v1 standard is achievable in a normal workflow, high quality libraries providing a wrapper on top of the standard seem like a more productive choice for my usage—especially any that offer a unified way to support Internet Explorer 11. After investigating a few, I decided to give LitElement a closer look. The guide says that it “is a simple base class for creating fast, lightweight web components that work in any web page with any framework.” I want that, and it’s coming from the Polymer project, so it seems like a good choice.
The small Web Component I built to try it out has its main functionality in the render method. It has the primary job of returning a template composed of styles, slotted content, and the articles loaded using the until directive from lit-html.
return html` ${styles} <slot name="articles"></slot> ${until( articles({ apiUrl: this.apiUrl, siteUrl: this.siteUrl }), loading )} `
All of the content becomes encapsulated within the x-postpress element, with the styles inside of the shadow root exposed through CSS custom properties.
When used by the consumer, WordPress posts are fetched from the REST API. Try it out by adding the following script tag:
<script type="module" src="https://unpkg.com/x-postpress@2.1.11"></script>
Then declare the x-postpress element with the apiHost attribute set to the appropriate WordPress installation. There are other attributes that can be set to control the requested results. In the example below, the per_page attribute specifies that only one article for each “page” in the payload should be returned.
<x-postpress apiHost="https://content.example.com" per_page="1" > </x-postpress>
The repository also includes a few basic unit and integration tests. These start on Travis CI after a pull request is issued on GitHub. While the Chrome and Firefox tests are executed inside of a Docker image (Mocha for unit and Puppeteer for integration), unit tests are also sent to Sauce Labs for Windows and macOS browser testing.
I can see the potential in having all of the tests run there as they support a wide variety of platforms and configurations. Additionally, thorough mobile testing is hard (especially at any scale), so it is nice to see they offer help for open source projects.
The most exciting part of the whole thing in my opinion is its shareability. Whether loading the element in a script tag, or including it in a project as part of a build step—getting the results into the browser is easier than ever (based on my past experience anyway). For a live example, try it out at CodeSandbox.