Esta es la primera publicación en el Blog de ingeniería de Web.dev. En los próximos meses, esperamos compartir información útil de nuestro trabajo, ¡así que esté atento a las publicaciones con la etiqueta de Blog de ingeniería! Aquí cubriremos el proceso de construcción de nuestro sitio estático y el JavaScript (¡opcional!) Detrás de nuestros componentes web.
web.dev proporciona contents sobre la creación de experiencias web modernas y le permite medir el rendimiento de su sitio. Los usuarios inteligentes pueden haberse dado cuenta de que nuestra página de medidas es solo una interfaz para Lighthouse, which is also available in Chrome's DevTools. Logging into web.dev allows you to run regular Lighthouse audits on your site so you can see how your score changes over time. I'll be revisiting the Measurements page a bit later, as we think it's pretty special. 🎊
Introduction
Basically, web.dev is a static site that is generated from a collection of Markdown files. We have chosen to use Eleven porque es una herramienta pulida y extensible que facilita la conversion de Markdown en HTML.
También utilizamos paquetes de JavaScript modernos que solo servimos a browsers compatibles type = "module"
, what includes async
and await
. We also gladly use features that are compatible with perennial browsers, but not with a minority of older versions. Since we are a static site, JavaScript is just not necessary to read our content.
Una vez que se completa el proceso de compilación, que implica generar HTML estático y empaquetar nuestro JavaScript con Rollup, web.dev se puede alojar con un server estático simple para realizar pruebas. El sitio es almost completamente estático, pero tenemos algunas necesidades especiales que aún se benefician de un servidor Node.js personalizado. Estos incluyen redireccionamientos para dominios no válidos, así como código para analizar el idioma preferido de un Username para una próxima función de internacionalización.
A pesar de ser un producto de Google, web.dev no utiliza ninguna herramienta o proceso interno de Google. Puede consultar nuestro repositorio. Hacemos esto porque el equipo que crea y mantiene web.dev es responsable de abogar dentro de Google en nombre del ecosistema de desarrolladores web más amplio, por lo que tiene más sentido para nosotros tener las mismas herramientas que los desarrolladores web externos.
Static generation
Every page on web.dev is written in Markdown. All pages include main issue, que describe los metadata de cada publicación. Estos metadatos se incorporan al diseño de cada página, creando headers, etiquetas, etc. He aquí un ejemplo:
---
layout: post
title: What is network reliability and how do you measure it?
authors:
- jeffposnick
date: 2018-11-05
description: |
The modern web is enjoyed by a wide swath of people…
---The modern web is enjoyed by a wide swath of [people](https://www.youtube.com/watch?v=dQw4w9WgXcQ), using a range of different devices and types of network connections.
Your creations can reach users all across the world...
This preliminary material allows us to define arbitrary properties such as author (s), publication date, and tags. Eleven conveniently sets out the front issue as data in almost all plugins, templates or other contexts where we would like to do something clever. The data object also contains what Eleventy describes as the data cascade: A variety of data extracted from each individual page, the layout that the page uses, and the data found in the hierarchical folder structure.
Each unique design describes a different type of content and can inherit from other designs. At web.dev, we use this feature to properly frame different types of content (such as posts and code labs) while sharing a top-level HTML layout.
Collections
Eleventy proporciona una forma programática de crear colecciones arbitrarias de contenido. Esto nos ha permitido crear soporte de paginación y generar páginas virtuales (páginas que no tienen un archivo Markdown coincidente en el disco) para los autores de publicaciones. Por ejemplo, construimos las páginas de nuestros autores usando una plantilla que contiene una expresión para su enlace permanente (por lo que la plantilla se vuelve a representar para cada autor) y una colección de respaldo.
This results in, for example, a simple page that contains all of Addy's posts.
Limitations
Right now we cannot easily connect to the Eleventy building process because it is declarative, rather than imperative- Describes what you want, rather than how you want it. It is difficult to run Eleventy as part of a larger build tool as it can only be invoked through its command line interface.
Templates
web.dev uses the Nunjucks template system originally developed by Mozilla. Nunjucks has the typical features of templates such as loops and conditionals, but it also allows us to define shortcodes that generate more HTML or invoke other logic.
Like most teams that build static content sites, we started with small shortcodes and added shortcodes over time - around 20 so far. Most of these just generate more HTML (including our custom web components). Here is an example:
{% Aside %}
[See how Asides work in the web.dev codebase](/handbook/web-dev-components/#asides)
{% endAside %}
It will end up looking like this:
But you are actually creating HTML that looks like this:
<div class="w-aside w-aside--note">
<p><to href="/handbook/web-dev-components/#asides">See how Asides work in the web.dev codebase</to></p>
</div>
Si bien está fuera del scope de esta publicación, web.dev también usa códigos cortos como un tipo de lenguaje de metaprogramación. Los códigos cortos aceptan argumentos, uno de los cuales es el contenido contenido. No es necesario que los códigos cortos devuelvan nada, por lo que se pueden usar para generar un estado o activar algún otro comportamiento. 🤔💭
Scripting
As mentioned above, because web.dev is a static site, it can be served and used without JavaScript and with older browsers that don't support type = "module"
o nuestro otro código moderno. Esta es una parte increíblemente importante de nuestro enfoque para hacer que web.dev be accesible para todos.
However, our code for modern browsers consists of two main parts:
- Bootstrap code, including code for SPA global status, parsing, and routing
- Código y CSS para componentes web que mejoran progresivamente el sitio
The bootstrap code is pretty straightforward: web.dev can load new pages as a single page application (SPA), so we installed a global listener that listens for clicks locally. <a href="/en/.../">
elements. The SPA model helps us maintain global state over the current user session, otherwise each new page load would trigger calls to Firebase to access a user's login state.
También especificamos un par de puntos de entrada diferentes a nuestro sitio en función de la Url que haya accedido, y cargamos la correcta utilizando Dynamic import ()
. This reduces the number of bytes our users need before the site is enhanced with code.
Web Components
Web Components
are custom elements that encapsulate the runtime functionality provided in JavaScript and are identified by custom names like . El diseño se presta bien a sitios en gran medida estáticos como web.dev: su browser gestiona el ciclo de vida de un elemento a medida que se actualiza el HTML de un sitio, informando correctamente cualquier elemento cuando se adjunta o desconecta de la página. Y los navegadores anticuados simplemente ignoran los componentes web por completo y renderizan lo que queda en el DOM.
Each web component is a class with methods that include connectedCallback ()
, disconnectedCallback ()
and attributeChangedCallback ()
. The custom elements of web.dev mainly inherit from LitElement, which provides a simple basis for complex components.
While web.dev uses web components on many pages, nowhere is it more necessary than on the measurement page. Two items provide most of the functionality that you see on this page:
<web-url-chooser-container></web-url-chooser-container>
<web-lighthouse-scores-container></web-lighthouse-scores-container>
Estos elementos crean otros elementos que proporcionan más funcionalidad. Es importante destacar que estos elementos son solo parte de nuestro source code regular de Markdown, y nuestro equipo de contenido puede agregar funcionalidad extendida a any page, not just the nodejs Measure.
Our web components most commonly use Container component model, popularized by React, although this model now it's a bit old-fashioned. Each -container
element connects to our global state (provided by undo) and then renders a visual element, which in turn renders actual DOM nodes that have styling or other built-in functionality.

Our most complex web components exist to visualize global actions and states. For example, web.dev allows you to audit your favorite site and then navigate away from the Measure page. If you go back, you will see that the task is still in progress.
Our simple components purely enhance static content or create stunning visualizations (for example, each line chart is its own ), which has no relation to the global state.
Lets chat
The engineering team at web.dev (Steal, Ewa, Michaeland Sam) will soon continue with more technical deep dives.
Esperamos que escuchar cómo hacemos las cosas te haya dado algunas ideas para tus propios proyectos. ¡Contáctenos en Twitter si tiene preguntas o solicitudes de temas para este blog!