+201223538180

Web site Developer I Advertising and marketing I Social Media Advertising and marketing I Content material Creators I Branding Creators I Administration I System SolutionAn 11ty, Vite And JAM Sandwich — Smashing Journal

Web site Developer I Advertising and marketing I Social Media Advertising and marketing I Content material Creators I Branding Creators I Administration I System SolutionAn 11ty, Vite And JAM Sandwich — Smashing Journal

Web site Developer I Advertising and marketing I Social Media Advertising and marketing I Content material Creators I Branding Creators I Administration I System Resolution

Fast abstract ↬

Again in January 2020, Ben Holmes got down to do what nearly each net developer does annually: rebuild his private web site. On this article, he shares his story of how he got down to construct his personal construct pipeline from absolute floor zero and created Slinkity.

I don’t learn about you, however I’ve been overwhelmed by all the net growth instruments we’ve got today. Whether or not you want Markdown, plain HTML, React, Vue, Svelte, Pug templates, Handlebars, Vibranium — you may most likely combine it up with some CMS knowledge and get a pleasant static web site cocktail.

I’m not going to inform you which UI growth instruments to succeed in for as a result of they’re all nice — relying on the wants of your mission. This submit is about discovering the proper static web site generator for any event; one thing that lets us use JS-less templates like markdown to start out, and usher in “islands” of component-driven interactivity as wanted.

I’m distilling a yr’s value of learnings right into a single submit right here. Not solely are we gonna speak code (aka duct-taping 11ty and Vite collectively), however we’re additionally going to discover why this strategy is so common to Jamstackian issues. We’ll contact on:

  • Two approaches to static web site technology, and why we should always bridge the hole;
  • The place templating languages like Pug and Nunjucks nonetheless show helpful;
  • When element frameworks like React or Svelte ought to come into play;
  • How the brand new, hot-reloading world of Vite helps us convey JS interactivity to our HTML with nearly zero configs;
  • How this enhances 11ty’s knowledge cascade, bringing CMS knowledge to any element framework or HTML template you possibly can need.

So with out additional ado, right here’s my story of horrible construct scripts, bundler breakthroughs, and spaghetti-code-duct-tape that (ultimately) gave me the SSG I all the time wished: an 11ty, Vite and Jam sandwich referred to as Slinkity!

A Nice Divide In Static Website Technology

Earlier than diving in, I need to talk about what I’ll name two “camps” in static web site technology.

Within the first camp, we’ve got the “easy” static web site generator. These instruments don’t convey JavaScript bundles, single-page apps, and some other buzzwords we’ve come to anticipate. They only nail the Jamstack fundamentals: pull in knowledge from whichever JSON blob of CMS you favor, and slide that knowledge into plain HTML templates + CSS. Instruments like Jekyll, Hugo, and 11ty dominate this camp, letting you flip a listing of markdown and liquid information right into a fully-functional web site. Key advantages:

  • Shallow studying curve
    If you realize HTML, you’re good to go!
  • Quick construct occasions
    We’re not processing something advanced, so every route builds in a snap.
  • Immediate time to interactive
    There’s no (or little or no) JavaScript to parse on the shopper.

Now within the second camp, we’ve got the “dynamic” static web site generator. These introduce element frameworks like React, Vue, and Svelte to convey interactivity to your Jamstack. These fulfill the identical core promise of mixing CMS knowledge along with your web site’s routes at construct time. Key advantages:

  • Constructed for interactivity
    Want an animated picture carousel? Multi-step type? Simply add a componentized nugget of HTML, CSS, and JS.
  • State administration
    One thing like React Context of Svelte shops permit seamless knowledge sharing between routes. As an example, the cart in your e-commerce web site.

There are distinct execs to both strategy. However what in the event you select an SSG from the primary camp like Jekyll, solely to appreciate six months into your mission that you just want some component-y interactivity? Otherwise you select one thing like NextJS for these highly effective parts, solely to battle with the educational curve of React, or pointless KB of JavaScript on a static weblog submit?

Few tasks squarely match into one camp or the opposite in my view. They exist on a spectrum, continually favoring new function units as a mission’s want evolve. So how can we discover a resolution that lets us begin with the easy instruments of the primary camp, and step by step add options from the second after we want them?

Properly, let’s stroll via my studying journey for a bit.

Observe: For those who’re already bought on static templating with 11ty to construct your static websites, be at liberty to hop right down to the juicy code walkthrough. 😉

Extra after soar! Proceed studying beneath ↓

Going From Elements To Templates And Net APIs

Again in January 2020, I got down to do what nearly each net developer does annually: rebuild my private web site. However this time was gonna be completely different. I challenged myself to construct a web site with my arms tied behind my again, no frameworks or construct pipelines allowed!

This was no easy activity as a React devotee. However with my head held excessive, I got down to construct my very own construct pipeline from absolute floor zero. There’s quite a lot of poorly-written code I may share from v1 of my private web site… however I’ll allow you to click on this README in the event you’re so courageous. 😉 As an alternative, I need to give attention to the higher-level takeaways I discovered ravenous myself of my JS responsible pleasures.

Templates Go A Lot Additional Than You May Suppose

I got here at this mission a recovering JavaScript junky. There are a couple of static-site-related wants I cherished utilizing component-based frameworks to fill:

  1. We need to break down my web site into reusable UI parts that may settle for JS objects as parameters (aka “props”).
  2. We have to fetch some info at construct time to slap right into a manufacturing web site.
  3. We have to generate a bunch of URL routes from both a listing of information or a fats JSON object of content material.

Listing taken from this submit on my private weblog.

However you’ll have seen… none of those actually want clientside JavaScript. Element frameworks like React are primarily constructed to deal with state administration considerations, just like the Fb net app inspiring React within the first place. For those who’re simply breaking down your web site into bite-sized parts or design system parts, templates like Pug work fairly properly too!

Take this navigation bar as an example. In Pug, we are able to outline a “mixin” that receives knowledge as props:

// nav-mixins.pug
mixin NavBar(hyperlinks)
    // pug's model of a for loop
    every hyperlink in hyperlinks
        a(href=hyperlink.href) hyperlink.textual content

Then, we are able to apply that mixin anyplace on our web site.

// index.pug
// kinda like an ESM "import"
embody nav-mixins.pug
html
  physique
    +NavBar(navLinksPassedByJS)
    foremost
      h1 Welcome to my pug playground 🐶

If we “render” this file with some knowledge, we’ll get a lovely index.html to serve as much as our customers.

const html = pug.render('/index.pug', { navLinksPassedByJS: [
    { href: "https://smashingmagazine.com/", text: 'Home' },
    { href: '/adopt', text: 'Adopt a Pug' }
] })
// use the NodeJS filesystem helpers to jot down a file to our construct
await writeFile('construct/index.html', html)

Positive, this doesn’t give niceties like scoped CSS to your mixins, or stateful JavaScript the place you need it. But it surely has some very highly effective advantages over one thing like React:

  1. We don’t want fancy bundlers we don’t perceive.
    We simply wrote that pug.render name by hand, and we have already got the primary route of a web site ready-to-deploy.
  2. We don’t ship any JavaScript to the end-user.
    Utilizing React typically means sending an enormous ole runtime for individuals’s browsers to run. By calling a operate like pug.render at construct time, we maintain all of the JS on our aspect whereas sending a clear .html file on the finish.

That is why I believe templates are a terrific “base” for static websites. Nonetheless, with the ability to attain for element frameworks the place we actually profit from them can be good. Extra on that later. 🙃

You Don’t Want A Framework To Construct Single Web page Apps

Whereas I used to be at it, I additionally wished some horny web page transitions on my web site. However how can we pull off one thing like this and not using a framework?

Crossfade with vertical wipe transition
Crossfade with vertical wipe transition. (Massive preview)

Properly, we are able to’t do that if each web page is its personal .html file. The entire browser refreshes after we soar from one HTML file to the opposite, so we are able to’t have that good cross-fade impact (since we’d briefly present each pages on prime of one another).

We’d like a approach to “fetch” the HTML and CSS for wherever we’re navigating to, and animate it into view utilizing JavaScript. This appears like a job for single-page apps!
I used a easy browser API medley for this:

  1. Intercept all of your hyperlink clicks utilizing an occasion listener.
  2. fetch API: Fetch all of the sources for no matter web page you need to go to, and seize the bit I need to animate into view: the content material outdoors the navbar (which I need to stay stationary through the animation).
  3. net animations API: Animate the brand new content material into view as a keyframe.
  4. historical past API: Change the route displaying in your browser’s URL bar utilizing window.historical past.pushState({}, 'new-route'). In any other case, it seems such as you by no means left the earlier web page!

For readability, right here’s a visible illustration of that single web page app idea utilizing a easy find-and-replace:

Step-by-step clientside routing process: 1. Medium rare hamburger is returned, 2. We request a well done burger using the fetch API, 3. We massage the response, 4. We pluck out the 'patty' element and apply it to our current page.
Step-by-step clientside routing course of: 1. Medium uncommon hamburger is returned, 2. We request a properly achieved burger utilizing the fetch API, 3. We therapeutic massage the response, 4. We pluck out the ‘patty’ ingredient and apply it to our present web page. (Massive preview)

Supply article

You’ll be able to go to the supply code from my private web site as properly!

Positive, some pairing of React et al and your animation library of selection can do that. However for a use case so simple as a fade transition… net APIs are fairly dang highly effective on their very own. And if you’d like extra strong web page transitions on static templates like Pug or plain HTML, libraries like Swup will serve you properly.

What 11ty Introduced To The Desk

I used to be feeling fairly good about my little SSG at this level. Positive it couldn’t fetch any CMS knowledge at build-time, and didn’t help completely different layouts by web page or by listing, and didn’t optimize my photos, and didn’t have incremental builds.

Okay, I would want some assist.

Given all my learnings from v1, I assumed I earned my proper to drop the “no third-party construct pipelines” rule and attain for present instruments. Seems, 11ty has a treasure trove of options I want!

For those who’ve tried out bare-bones SSGs like Jekyll or Hugo, it’s best to have a fairly good thought of how 11ty works. Solely distinction? 11ty makes use of JavaScript through-and-through.

11ty helps principally each template library on the market, so it was completely happy to render all my Pug pages to .html routes. It’s format chaining choice helped with my foe-single-page-app setup too. I simply wanted a single script for all my routes, and a “world” format to import that script:

// _includes/base-layout.html
<html>
<physique>
  <!--load each web page's content material between some physique tags-->
  {{ content material }}
  <!--and apply the script tag just under this-->
  <script src="https://smashingmagazine.com/2021/10/building-ssg-11ty-vite-jam-sandwich/main.js"></script>
</physique>
</html>

// random-blog-post.pug
---
format: base-layout
---

article
  h2 Welcome to my weblog
  p Have you ever heard the story of Darth Plagueis the Sensible?

So long as that foremost.js does all that hyperlink intercepting we explored, we’ve got web page transitions!

Oh, And The Knowledge Cascade

So 11ty helped clear up all my spaghetti code from v1. But it surely introduced one other necessary piece: a clear API to load knowledge into my layouts. That is the bread and butter of the Jamstack strategy. As an alternative of fetching knowledge within the browser with JavaScript + DOM manipulation, you may:

  1. Fetch knowledge at build-time utilizing Node. This may very well be a name to some exterior API, a neighborhood JSON or YAML import, and even the content material of different routes in your web site (think about updating a table-of-contents at any time when new routes are added 🙃).
  2. Slot that knowledge into your routes. Recall that .render operate we wrote earlier:
const html = pug.render('/index.pug', { navLinksPassedByJS: [
    { href: "https://smashingmagazine.com/", text: 'Home' },
    { href: '/adopt', text: 'Adopt a Pug' }
] })

…however as an alternative of calling pug.render with our knowledge each time, we let 11ty do that behind-the-scenes.

Positive, I didn’t have quite a lot of knowledge for my private web site. But it surely felt nice to whip up a .yaml file for all my private tasks:

# _data/works.yaml
- title: Bits of Good Homepage
  hash: bog-homepage
  hyperlinks:
    - href: https://bitsofgood.org
      textual content: Discover the reside web site
    - href: https://github.com/GTBitsOfGood/bog-web
      textual content: Scour the Svelt-ified codebase
  timeframe: Might 2019 - current
  tags:
    - JAMstack
    - SvelteJS
- title: Dolphin Audio Visualizer
...

And entry that knowledge throughout any template:

// dwelling.pug
.project-carousel
  every work in works
    h3 #{title}
    p #{timeframe}
    every tag in tags
    ...

Coming from the world of “clientside rendering” with create-react-app, this was a fairly large revelation. No extra sending API keys or huge JSON blobs to the browser. 😁

I additionally added some goodies for JavaScript fetching and animation enhancements over model 1 of my web site. For those who’re curious, right here’s the place my README stood at this level.

I Was Completely happy At This Level However One thing Was Lacking

I went surprisingly far by abandoning JS-based parts and embracing templates (with animated web page transitions in addition). However I do know this gained’t fulfill my wants eternally. Keep in mind that nice divide I kicked us off with? Properly, there’s clearly nonetheless that ravine between my construct setup (firmly in camp #1) and the haven of JS-ified interactivity (the Subsequent, SvelteKit, and extra of camp #2). Say I need to add:

  • a pop-up modal with an open/shut toggle,
  • a component-based design system like Materials UI, full with scoped styling,
  • a posh multi-step type, possibly pushed by a state machine.

For those who’re a plain-JS-purist, you most likely have framework-less solutions to all these use circumstances. 😉 However there’s a cause JQuery isn’t the norm anymore! There’s one thing interesting about creating discrete, easy-to-read parts of HTML, scoped types, and items of JavaScript “state” variables. React, Vue, Svelte, and so forth. provide so many niceties for debugging and testing that straight DOM manipulation can’t fairly match.

So right here’s my million greenback query: can we use straight HTML templates to start out, and step by step add React / Vue / Svelte parts the place we wish them?

The reply… is sure. Let’s strive it.

11ty + Vite: A Match Made In Heaven ❤️

Right here’s the dream that I’m imagining right here. Wherever I need to insert one thing interactive, I need to depart a bit of flag in my template to “put X React element right here.” This may very well be the shortcode syntax that 11ty helps:

# Tremendous fascinating programming tutorial

Writing paragraphs has been enjoyable, however that is no approach to be taught. Time for an interactive code instance!

{% react './parts/FancyLiveDemo.jsx' %}

However keep in mind, the one-piece 11ty (purposely) avoids: a approach to bundle all of your JavaScript. Coming from the OG guild of bundling, your mind most likely jumps to constructing Webpack, Rollup, or Babel processes right here. Construct an enormous ole entry level file, and output some stunning optimized code proper?

Properly sure, however this will get fairly concerned. If we’re utilizing React parts, as an example, we’ll most likely want some loaders for JSX, a elaborate Babel course of to remodel every thing, an interpreter for SASS and CSS module imports, one thing to assist with reside reloading, and so forth.

If solely there have been a device that would simply see our .jsx information and know precisely what to do with them.

Enter: Vite

Vite’s been the speak of the city as of late. It’s meant to be the all-in-one device for constructing absolutely anything in JavaScript. Right here’s an instance so that you can strive at dwelling. Let’s make an empty listing someplace on our machine and set up some dependencies:

npm init -y # Make a brand new bundle.json with defaults set
npm i vite react react-dom # Seize Vite + some dependencies to make use of React

Now, we are able to make an index.html file to function our app’s “entry level.” We’ll maintain it fairly easy:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Appropriate" content material="IE=edge">
  <meta identify="viewport" content material="width=device-width, initial-scale=1.0">
  <title>Doc</title>
</head>
<physique>
  <h1>Howdy Vite! (wait is it pronounced "veet" or "vight"...)</h1>
  <div id="root"></div>
</physique>
</html>

The one fascinating bit is that div id="root" within the center. This would be the root of our React element in a second!

If you’d like, you may hearth up the Vite server to see our plain HTML file in your browser. Simply run vite (or npx vite if the command didn’t get configured in your terminal), and also you’ll see this useful output:

vite vX.X.X dev server operating at:

> Native: http://localhost:3000/
> Community: use `--host` to reveal

prepared in Xms.

Very similar to Browsersync or different common dev servers, the identify of every .html file corresponds to a route on our server. So if we renamed index.html to about.html, we might go to http://localhost:3000/about/ (sure, you’ll want a trailing slash!)

Now let’s do one thing fascinating. Alongside that index.html file, add a fundamental React element of some type. We’ll use React’s useState right here to reveal interactivity:

// TimesWeMispronouncedVite.jsx
import React from 'react'

export default operate TimesWeMispronouncedVite() {
  const [count, setCount] = React.useState(0)
  return (
    <div>
      <p>I've mentioned Vite fallacious {rely} occasions in the present day</p>
      <button onClick={() => setCount(rely + 1)}>Add one</button>
    </div>
  )
}

Now, let’s load that element onto our web page. That is all we’ve got so as to add to our index.html:

<!DOCTYPE html>
...
<physique>
  <h1>Howdy Vite! (wait is it pronounced "veet" or "vight"...)</h1>
  <div id="root"></div>
  <!--Do not forget kind="module"! This lets us use ES import syntax within the browser-->
  <script kind="module">
    // path to our element. Observe we nonetheless use .jsx right here!
    import Element from './TimesWeMispronouncedVite.jsx';
    import React from 'react';
    import ReactDOM from 'react-dom';
    const componentRoot = doc.getElementById('root');
    ReactDOM.render(React.createElement(Element), componentRoot);
  </script>
</physique>
</html>

Yep, that’s it. No want to remodel our .jsx file to a browser-ready .js file ourselves! Wherever Vite sees a .jsx import, it’ll auto-convert that file to one thing browsers can perceive. There isn’t even a dist or construct folder when working in growth; Vite processes every thing on the fly — full with sizzling module reloading each time we save our modifications. 🤯

Okay, so we’ve got an extremely succesful construct device. How can we convey this to our 11ty templates?

Operating Vite Alongside 11ty

Earlier than we soar into the good things, let’s talk about operating 11ty and Vite side-by-side. Go forward and set up 11ty as a dev dependency into the identical mission listing from final part:

npm i -D @11ty/eleventy # sure, it truly is 11ty twice

Now let’s perform a little pre-flight examine to see if 11ty’s working. To keep away from any confusion, I’d counsel you:

  1. Delete that index.html file from earlier;
  2. Transfer that TimesWeMispronouncedVite.jsx inside a brand new listing. Say, parts/;
  3. Create a src folder for our web site to reside in;
  4. Add a template to that src listing for 11ty to course of.

For instance, a blog-post.md file with the next contents:

# Howdy world! It’s markdown right here

Your mission construction ought to look one thing like this:

src/
  blog-post.md
parts/
  TimesWeMispronouncedVite.jsx

Now, run 11ty out of your terminal like so:

npx eleventy --input=src

If all goes properly, it’s best to see an construct output like this:

_site/
  blog-post/
    index.html

The place _site is our default output listing, and blog-post/index.html is our markdown file superbly transformed for shopping.

Usually, we’d run npx eleventy --serve to spin up a dev server and go to that /blog-post web page. However we’re utilizing Vite for our dev server now! The purpose right here is to:

  1. Have eleventy construct our markdown, Pug, nunjucks, and extra to the _site listing.
  2. Level Vite at that very same _site listing so it may well course of the React parts, fancy type imports, and different issues that 11ty didn’t choose up.

So a two-step construct course of, with 11ty handing off the Vite. Right here’s the CLI command you’ll want to start out 11ty and Vite in “watch” mode concurrently:

(npx eleventy --input=src --watch) & npx vite _site

You can even run these instructions in two separate terminals for simpler debugging. 😄

With a bit of luck, it’s best to have the ability to go to http://localhost:3000/blog-post/ (once more, don’t neglect the trailing slash!) to see that processed Markdown file.

Partial Hydration With Shortcodes

Let’s do a quick rundown on shortcodes. Time to revisit that syntax from earlier:

{% react '/parts/TimesWeMispronouncedVite.jsx' %}

For these unfamiliar with shortcodes: they’re about the identical as a operate name, the place the operate returns a string of HTML to slip into your web page. The “anatomy” of our shortcode is:

  • {% … %}
    Wrapper denoting the beginning and finish of the shortcode.
  • react
    The identify of our shortcode operate we’ll configure in a second.
  • '/parts/TimesWeMispronouncedVite.jsx'
    The primary (and solely) argument to our shortcode operate. You’ll be able to have as many arguments as you’d like.

Let’s wire up our first shortcode! Add a .eleventy.js file to the bottom of your mission, and add this config entry for our react shortcode:

// .eleventy.js, on the base of the mission
module.exports = operate(eleventyConfig) {
  eleventyConfig.addShortcode('react', operate(componentPath) {
   // return any legitimate HTML to insert
   return `<div id="root">That is the place we'll import ${componentPath}</div>`
  })

  return {
    dir: {
      // so we do not have to jot down `--input=src` in our terminal each time!
      enter: 'src',
    }
  }
}

Now, let’s boost our blog-post.md with our new shortcode. Paste this content material into our markdown file:

# Tremendous fascinating programming tutorial

Writing paragraphs has been enjoyable, however that is no approach to be taught. Time for an interactive code instance!

{% react '/parts/TimesWeMispronouncedVite.jsx' %}

And in the event you run a fast npx eleventy, it’s best to see this output in your _site listing beneath /blog-post/index.html:

<h1>Tremendous fascinating programming tutorial</h1>

<p>Writing paragraphs has been enjoyable, however that is no approach to be taught. Time for an interactive code instance!</p>

<div id="root">That is the place we'll import /parts/TimesWeMispronouncedVite.jsx</div>

Writing Our Element Shortcode

Now let’s do one thing helpful with that shortcode. Keep in mind that script tag we wrote whereas attempting out Vite? Properly, we are able to do the identical factor in our shortcode! This time we’ll use the componentPath argument to generate the import, however maintain the remainder just about the identical:

// .eleventy.js
module.exports = operate(eleventyConfig) {
  let idCounter = 0;
  // copy all our /parts to the output listing
  // so Vite can discover them. Essential step!
  eleventyConfig.addPassthroughCopy('parts')

  eleventyConfig.addShortcode('react', operate (componentPath) {
      // we'll use idCounter to generate distinctive IDs for every "root" div
      // this lets us use a number of parts / shortcodes on the identical web page 👍
      idCounter += 1;
      const componentRootId = `component-root-${idCounter}`
      return `
  <div id="${componentRootId}"></div>
  <script kind="module">
    // use JSON.stringify to
    // 1) wrap our componentPath in quotes
    // 2) strip any invalid characters. In all probability a non-issue, however good to be cautious!
    import Element from ${JSON.stringify(componentPath)};
    import React from 'react';
    import ReactDOM from 'react-dom';
    const componentRoot = doc.getElementById('${componentRootId}');
    ReactDOM.render(React.createElement(Element), componentRoot);
  </script>
      `
    })
  
  eleventyConfig.on('beforeBuild', operate () {
    // reset the counter for every new construct
    // in any other case, it will rely up larger and better on each reside reload
    idCounter = 0;
  })

  return {
    dir: {
      enter: 'src',
    }
  }
}

Now, a name to our shortcode (ex. {% react '/parts/TimesWeMispronouncedVite.jsx' %}) ought to output one thing like this:

<div id="component-root-1"></div>
<script kind="module">
    import Element from './parts/FancyLiveDemo.jsx';
    import React from 'react';
    import ReactDOM from 'react-dom';
    const componentRoot = doc.getElementById('component-root-1');
    ReactDOM.render(React.createElement(Element), componentRoot);
</script>

Visiting our dev server utilizing (npx eleventy --watch) & vite _site, we should always discover a superbly clickable counter ingredient. ✨

Buzzword Alert — Partial Hydration And Islands Structure

We simply demonstrated “islands structure” in its easiest type. That is the concept our interactive element timber don’t should devour all the web site. As an alternative, we are able to spin up mini-trees, or “islands,” all through our app relying on the place we really want that interactivity. Have a fundamental touchdown web page of hyperlinks with none state to handle? Nice! No want for interactive parts. However do you could have a multi-step type that would profit from X React library? No drawback. Use strategies like that react shortcode to spin up a Kind.jsx island.

This goes hand-in-hand with the concept of “partial hydration.” You’ve doubtless heard the time period “hydration” in the event you work with component-y SSGs like NextJS or Gatsby. In brief, it’s a approach to:

  1. Render your parts to static HTML first.
    This provides the person one thing to view after they initially go to your web site.
  2. “Hydrate” this HTML with interactivity.
    That is the place we hook up our state hooks and renderers to, properly, make button clicks really set off one thing.

This 1-2 punch makes JS-driven frameworks viable for static websites. So long as the person has one thing to view earlier than your JavaScript is finished parsing, you’ll get a good rating on these lighthouse metrics.

Properly, till you don’t. 😢 It may be costly to “hydrate” a complete web site because you’ll want a JavaScript bundle able to course of each final DOM ingredient. However our scrappy shortcode method doesn’t cowl all the web page! As an alternative, we “partially” hydrate the content material that’s there, inserting parts solely the place needed.

Don’t Fear, There’s A Plugin For All This — Slinkity

Let’s recap what we found right here:

  1. Vite is an extremely succesful bundler that may course of most file sorts (jsx, vue, and svelte to call a couple of) with out further config.
  2. Shortcodes are a simple approach to insert chunks of HTML into our templates, component-style.
  3. We are able to use shortcodes to render dynamic, interactive JS bundles wherever we wish utilizing partial hydration.

So what about optimized manufacturing builds? Correctly loading scoped types? Heck, utilizing .jsx to create total pages? Properly, I’ve bundled all of this (and a complete lot extra!) right into a mission referred to as Slinkity. I’m excited to see the heat group reception to the mission, and I’d love for you, pricey reader, to present it a spin your self!

🚀 Attempt the fast begin information

Astro’s Fairly Nice Too

Readers with their eyes on cutting-edge tech most likely thought of Astro a minimum of as soon as by now. 😉 And I can’t blame you! It’s constructed with a fairly related purpose in thoughts: begin with plain HTML, and insert stateful parts wherever you want them. Heck, they’ll even allow you to begin writing React parts inside Vue or Svelte parts inside HTML template information! It’s like MDX Xtreme version. 🤯

There’s one fairly main value to their strategy although: that you must rewrite your app from scratch. This implies a brand new template format primarily based on JSX (which you may not be snug with), a complete new knowledge pipeline that’s lacking a few niceties proper now, and normal bugginess as they work out the kinks.

However spinning up an 11ty + Vite cocktail with a device like Slinkity? Properly, if you have already got an 11ty web site, Vite ought to bolt into place with none rewrites, and shortcodes ought to cowl most of the identical use circumstances as .astro information. I’ll admit it’s far from excellent proper now. However hey, it’s been helpful to this point, and I believe it’s a fairly robust various if you wish to keep away from site-wide rewrites!

Wrapping Up

This Slinkity experiment has served my wants fairly properly to this point (and a couple of of y’all’s too!). Be at liberty to make use of no matter stack works to your JAM. I’m simply excited to share the outcomes of my yr of construct device debauchery, and I’m so pumped to see how we are able to bridge the good Jamstack divide.

Additional Studying

Wish to dive deeper into partial hydration, or ESM, or SSGs on the whole? Verify these out:

  • Islands Structure
    This weblog submit from Jason Format actually kicked off a dialogue of “islands” and “partial hydration” in net growth. It’s chock-full of helpful diagrams and the philosophy behind the concept.
  • Simplify your static with a custom-made static web site generator
    One other SmashingMag article that walks you thru crafting Node-based web site builders from scratch. It was an enormous inspiration to me!
  • How ES Modules have redefined net growth
    A private submit on how ES Modules have modified the net growth recreation. This dives a bit of additional into the “then and now” of import syntax on the net.
  • An introduction to net parts
    A superb walkthrough on what net parts are, how the shadow DOM works, and the place net parts show helpful. Used this information to use {custom} parts to my very own framework!
Smashing Editorial
(vf, yk, il)

Supply hyperlink

Leave a Reply