惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
Security Latest
Security Latest
C
Cisco Blogs
P
Palo Alto Networks Blog
Know Your Adversary
Know Your Adversary
Project Zero
Project Zero
C
Cyber Attacks, Cyber Crime and Cyber Security
NISL@THU
NISL@THU
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Secure Thoughts
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Docker
Google Online Security Blog
Google Online Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Recent Announcements
Recent Announcements
T
The Exploit Database - CXSecurity.com
G
Google Developers Blog
Schneier on Security
Schneier on Security
小众软件
小众软件
爱范儿
爱范儿
GbyAI
GbyAI
J
Java Code Geeks
T
Tailwind CSS Blog
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
D
DataBreaches.Net
Blog — PlanetScale
Blog — PlanetScale
TaoSecurity Blog
TaoSecurity Blog
MyScale Blog
MyScale Blog
B
Blog RSS Feed
Cyberwarzone
Cyberwarzone
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
C
CXSECURITY Database RSS Feed - CXSecurity.com
S
Securelist
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Y
Y Combinator Blog
S
Schneier on Security
Latest news
Latest news
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
F
Fortinet All Blogs
M
MIT News - Artificial intelligence
PCI Perspectives
PCI Perspectives
V
V2EX
V2EX - 技术
V2EX - 技术
O
OpenAI News
W
WeLiveSecurity

Bryan Robinson's Blog

Does our technology still work for us? Product pricing, dev bad habits, and the role of the pit of success Astro Server Island for latest Bluesky post (heavily cached!) Type-safe environment variables in Astro 5.0 New Website, but really is it? Netlify Durable Cache: Caching for a third-party world Introducing the Hygraph Astro Content Loader Integrating Astro.js Starlight Documentation into a Next.js Project Using Proxies Jamstack is meaningless 😱 Book Release: Eleventy by Example – Learn 11ty with 5 in-depth projects 11ty Second 11ty: Creating Template Filters 11ty Second 11ty: Global Data files (JS and JSON) 11ty second 11ty: The Render Plugin Part 1 Help needed: Netlify Frontend environment variables with Astro.js Quick experiment with the Slinkity 11ty plugin Creating a dynamic color converter with 11ty Serverless Using 11ty JavaScript Data files to mix Markdown and CMS content into one collection How to show your template code in 11ty blog posts New City, New Job, New Content Using Nunjucks Climbing the 11ty Performance leaderboard with Cloudinary, critical CSS and more Three JAMstack movements to watch in 2020 Create a Codepen promo watermark with no additional HTML, CSS or JS 3 underused CSS features to learn for 2020 Use CSS Subgrid to layout full-width content stripes in an article template CSS Gap creates a bright future for margins in Flex as well as Grid Create your first CSS Custom Properties (Variables) Use CSS Grid to create a self-centering full-width element Creating an 11ty Plugin - SVG Embed Tool Now offering design and code reviews at PeerReviews.dev Routing contact-form emails to different addresses with Netlify, Zapier and SendGrid Create an Eleventy (11ty) theme based on a free HTML template Client work and the JAMstack Grid vs. Flex: A Tale of a "Simple" Promo Space Using Eleventy The Tech Barrier to Entry What Can We Learn from CERN Let Practical CSS Grid - Launching My First Course Build Trust on the Web incorporating User Worries with your User Stories 2019 The Year of Markup-First Development Refactoring CSS into a Sass mixin Starting a new journey with Code Contemporary Dynamic Static Sites with Netlify and iOS Shortcuts Top 3 uses for the ::before and ::after CSS pseudo elements How To: Use CSS Grid to Mix and Match Design Patterns Use CSS ::before and ::after for simple, spicy image overlays Modern CSS: Four Things Every Developer and Designer Should Know About CSS 3 Strategies for Getting Started with CSS Grid CSS Tip: Use rotate() and skew() together to introduce some clean punk rock to your CSS The 5 Stages of Grid Love How To: A CSS-Only Mobile Off Canvas Navigation How To: Use CSS Grid Layout to Make a Simple, Fluid Card Grid Make a More Flexible Cover Screen with CSS Grid Can CSS Grid open up interesting CMS Layout options? Firefox 52 to Introduce New Box-Alignment Values Falling Forward — Rethinking Progressive Enhancement, Graceful Degradation and Developer Morality Start Exploring the Magic of CSS Grid Layout I Converted My Blog to CSS Grid Layout and Regret Nothing Feature Queries are on the Rise CSS Shapes — Let the Text Flow Around You Flexbox -- Let Memorializing Prince and Print vs. The Web I went to Italy and noticed UX fails How to Get Designers to Contribute in Open Source The True Gift of Your Former Code
Adapt client-side JavaScript for use in 11ty (Eleventy) data files
2019-09-04 · via Bryan Robinson's Blog

My good friend James Q. Quick recently wrote an awesome post describing interacting with APIs without a framework. He used the Pokémon API PokeAPI. He hooked me and I had to put my own spin on it!

Before we go any further, you need to head over to his site and read the original post! I won’t be going into details on what he did and it’s necessary to understanding what’s happening in this post.

You can even watch it embedded right here! Go ahead, I’ll wait.

{% youtube “T-VQUKeSU1w” %}

My Challenge: Take James’ client-side JS and convert it to a build process to build HTML

I love JavaScript, but I love rendered HTML much more, so I challenged myself to convert James’ client-side JS code to something that rendered HTML. I wanted to do it as quickly and as concisely as possible.

I did what I usually do in a situation like this and reached for my favorite static site tool: 11ty. 11ty brings JavaScript data files and simple templating to the party. I thought about keeping in the spirit of James’ piece and trying to go framework-free, but I’m not that good a developer.

Step 0: Set up 11ty dependency

Since we’ll be using 11ty, we need to create our package.json and install 11ty into our project.

Run the following to get this set up:

Initial your package.json with the basics.

npm init -y

Then install 11ty:

npm install --save @11ty/eleventy

Once the install is done, you should be able to run npx eleventy --serve and 11ty will start serving your site. 

Step 1: Get only the necessary functionality

In James’ code, he’s got two main JavaScript functions: fetchPokemon() and displayPokemon(). Our display concerns will be handled by our template, so we can get rid of that function. 

The main functionality of the fetchPokemon() function is to create an array of Promises and build out a data array when all the Promises resolve. He runs through these to get additional data on each Pokemon to display instead of the base details the API would normally give. After he builds that data array, he invokes his displayPokemon function to handle the building of the HTML.

In our case, this JavaScript needs to just return that array to 11ty.

Here’s the modified code: 

const fetchPokemon = () => {
    const promises = [];
    for (let i = 1; i <= 150; i++) {
        const url = `https://pokeapi.co/api/v2/pokemon/${i}`;
        promises.push(fetch(url).then((res) => res.json()));
    }
    return Promise.all(promises).then((results) => {
        const pokemon = results.map((result) => ({
            name: result.name,
            image: result.sprites['front_default'],
            type: result.types.map((type) => type.type.name).join(', '),
            id: result.id
        }));
        return pokemon;
    });
};

In the file structure of our project, we need to have a folder to contain our data files. I’m keeping this barebones with configuration, so we’ll name our folder _data which is the 11ty default.

We’ll put our data fetcher file in here. Whatever you name the file will be the variable you get in your templates. In this case, I named mine pokemon.js. Put our function in the top of this file. 11ty’s data files are node modules, so we need to export our data.

module.exports = async function() {
    return await fetchPokemon();
}

That await in the export is very important. Otherwise, 11ty will finish building the site before the data has returned.

The discerning eye might notice that James is using a powerful new browser API to get his data: The Fetch API! This is an amazing API, but we don’t have a browser in our build process. In our case, this will break. We need to import a package to cover this. You could convert this code over to Node’s native https module, but I’m putting this together and rewriting as little code as possible. I’ll opt to use the lovely node-fetch module which has similar syntax and style.

Install the package:

npm install --save node-fetch

Require the package at the top of your file:

const fetch = require('node-fetch');

From here, our data file should work when 11ty is building or serving the site.

Step 2: Rework the display to use an HTML template instead of a JavaScript function

Next, we’ll need to add a basic HTML template that uses this variable.

For my purposes, I blatantly borrowed James’ HTML and CSS, and worked a template loop around his <li> for each Pokemon.

<div class="container">
    <h1>Robinson's Pokedex</h1>
    <ul id="pokedex">
        {% for pokemon in pokemon %}
            <li class="card">
                <img class="card-image" src="{{ pokemon.image }}"/>
                <h2 class="card-title">{{ pokemon.id }}. {{ pokemon.name }}</h2>
                <p class="card-subtitle">Type: {{ pokemon.type }}</p>
            </li>
        {% endfor %}
    </ul>
</div>

Step 3: Add some styles

By default, 11ty won’t pass through your static assets. In this case, our style.css file.

We need to add a minimal piece of configuration to take care of this.

We’ll create an .eleventy.js file in the root of our project.

In that file, we’ll export one line that sets 11ty to pass any root-level CSS into our final distribution directory.

module.exports = function(eleventyConfig) {  
   eleventyConfig.addPassthroughCopy("*.css");  
};

That’s it!

If you’ve been running the 11ty server this entire time, you may need to restart it. When it restarts, you’ll have a functioning, “server rendered” version of James’ Pokedex! Push it up to GitHub, host it on Netlify and pat yourself on the back!

You can find the 11ty code here and James’ initial post here.