本文共 11502 字,大约阅读时间需要 38 分钟。
盖茨比乔布斯
Talk about the latest cutting-edge web technologies, and you find some impressive names like React.js
, Vue.js
, Next.js
, and so on. They have opened new gateways and approach to building websites, hence targeting the next billion internet users.
谈论最新的前沿Web技术,您会发现一些令人印象深刻的名称,例如React.js
, Vue.js
, Next.js
等等。 他们打开了新的门户网站和网站建设方法,从而瞄准了下一个十亿互联网用户。
Let's start with a simple question. Have you ever visited a website for reading a single post and ended up exploring the whole bunch of pages — because it's super fast?
让我们从一个简单的问题开始。 您是否曾经访问过一个网站以阅读单个帖子并最终浏览整个页面-因为它超级快?
Yes, it happened with me, and that's how I met Gatsby.js
. Today, fast is everything! If you talk about web performance parameters, then improving page load time is number ONE on my to-do list. Because website speed is now no more a luxury, it's a necessity.
是的,它发生在我身上,这就是我遇到Gatsby.js
。 今天,一切都快! 如果您谈论Web性能参数,那么改善页面加载时间就成为我的待办事项清单上的第一位 。 因为现在网站速度不再是一种奢侈,所以这是必要的 。
A website which loads fast brings the following perks and benefits for you:
快速加载的网站为您带来以下好处和好处:
Gatsby.js
is a free and open-source React.js-based framework which helps developers build blazing-fast websites and apps. JAMstack (JavaScript APIs Markup) is the recent trend and WordPress powers more than 33% of the internet users.
Gatsby.js
是一个免费的基于开源React.js的框架,可帮助开发人员构建快速的网站和应用程序 。 JAMstack(JavaScript API标记)是最近的趋势,而WordPress为超过33%的互联网用户提供了强大的动力。
Despite all the ease and usability, it is quite hard to build a modern front-end with WordPress, which meets all the latest tech needs. I tried figuring out some of the reasons, and here they are:
尽管具有所有的易用性和可用性,但是使用WordPress构建满足所有最新技术需求的现代前端非常困难。 我尝试找出一些原因,原因如下:
On the contrary, Gatsby.js
takes care of all these limitations and helps you build a robust front-end, which is not only fast but also modern. In this piece, I am going to show how you can leverage Gatsby.js
to supercharge your next WordPress site.
相反, Gatsby.js
可以解决所有这些限制,并帮助您构建健壮的前端,这不仅快速而且现代。 在本文中,我将展示如何利用Gatsby.js
您的下一个WordPress网站。
First, we are going to configure a basic Gatsby project setup. And then we'll use it to fetch data from our WordPress site.
首先,我们将配置基本的盖茨比项目设置。 然后,我们将使用它从WordPress网站获取数据。
In case you are an absolute beginner, and this is your first time with Gatsby.js
, all you need to do is follow these steps mentioned below. These will help you set up a basic Gatsby project.
如果您是绝对的初学者,并且这是您第一次使用Gatsby.js
,那么您只需执行下面提到的这些步骤。 这些将帮助您建立基本的盖茨比项目。
npm install -g gatsby-cli
Gatsby.js
site through the following. 接下来,通过以下步骤创建一个新的Gatsby.js
网站。 gatsby new site-name
cd site-name
gatsby develop
If you have a WordPress site and you want to have its front-end built with Gatsby.js all you need to do is pull the existing data into your static Gatsby site. You can do that with the gatsby-source-wordpress
plugin.
如果您有一个WordPress网站,并且想要使用Gatsby.js来构建其前端,那么您要做的就是将现有数据拉入您的静态Gatsby网站。 您可以使用gatsby-source-wordpress
插件来做到这一点。
Inside your terminal type the following to install this plugin.
在终端内键入以下内容以安装此插件。
npm install gatsby-source-wordpress
Inside your gatsby-config.js
file, add the configuration options which includes your WordPress site’s baseUrl
, protocol
, whether it’s hosted on wordpress.com or self-hosted i.e., hostingWPCOM
, and whether it uses the Advanced Custom Fields (ACF) plugin or not useACF
Also, we are going to mention all the includedRoutes
which tells what data do we exactly want to fetch.
在您的gatsby-config.js
文件中,添加配置选项,其中包括WordPress网站的baseUrl
, protocol
,是否托管在wordpress.com上或自行托管(即托管hostingWPCOM
)以及是否使用高级自定义字段(ACF)插件或不useACF
此外,我们要提到的所有includedRoutes
告诉什么样的数据做我们真正想要获取。
I am using the default WordPress REST API site as a demo which you can also access from here → . Right now the front-end appears as follows:
我正在使用默认的WordPress REST API站点作为演示,也可以从此处→ 访问。 现在,前端显示如下:
The configuration options inside your gatsby-config.js
file look like this:
gatsby-config.js
文件中的配置选项如下所示:
module.exports = { // ... plugins: [ // ... { resolve: `gatsby-source-wordpress`, options: { // Your WordPress source. baseUrl: `demo.wp-api.org`, protocol: `https`, // Only fetches posts, tags and categories from the baseUrl. includedRoutes: ['**/posts', '**/tags', '**/categories'], // Not using ACF so putting it off. useACF: false } }, ],}
Once your Gatsby site is fetching data from your WordPress source URL, it's time to create your site pages. This is done by implementing the createPages
API in the gatsby-node.js
.
一旦您的Gatsby网站从WordPress源URL提取数据,就可以创建网站页面了。 这是通过在gatsby-node.js
实现createPages
API来gatsby-node.js
。
This makes your fetched data available to be queried with GraphQL. At build
time, the gatsby-source-wordpress
plugin brings your data, and use it to ”automatically infer a GraphQL schema” which you can query against.
这使您获取的数据可通过GraphQL查询。 在build
时, gatsby-source-wordpress
插件会带您的数据,并使用它“自动推断GraphQL模式”,您可以对其进行查询。
Here's the code is of the gatsby-node.js
file which iterates the WordPress post data.
这是gatsby-node.js
文件的代码,该文件迭代WordPress帖子数据。
/** * Implement Gatsby's Node APIs in this file. * * See: https://www.gatsbyjs.org/docs/node-apis/ */// You can delete this file if you're not using itconst path = require(`path`);const slash = require(`slash`);/** Implement the Gatsby API “createPages”. This is * called after the Gatsby bootstrap is finished so you have * access to any information necessary to programmatically * create pages. * Will create pages for WordPress pages (route : /{slug}) * Will create pages for WordPress posts (route : /post/{slug}) */exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions; // @TODO: STEP #2: Query all WordPress Posts Data. /** The “graphql” function allows us to run arbitrary * queries against the local Gatsby GraphQL schema. Think of * it like the site has a built-in database constructed * from the fetched data that you can run queries against. */ const result = await graphql(` { allWordpressPost { edges { node { id slug status template format } } } } `); // Check for any errors if (result.errors) { throw new Error(result.errors); } // Access query results via object destructuring. const { allWordpressPost } = result.data; const postTemplate = path.resolve(`./src/templates/post.js`); // @TODO: STEP #3: Create pages in Gatsby with WordPress Posts Data. /** * We want to create a detailed page for each * post node. We'll just use the WordPress Slug for the slug. * The Post ID is prefixed with 'POST_' */ allWordpressPost.edges.forEach(edge => { createPage({ path: `/${ edge.node.slug}/`, component: slash(postTemplate), context: { id: edge.node.id } }); });};
Next, create a folder for templates and add files for posts, pages, layouts, etc. For now, I am creating a post.js
file since I am fetching the posts from my WordPress site.
接下来,为模板创建一个文件夹,并为帖子,页面,布局等添加文件。由于我是从WordPress网站中获取帖子的,因此我现在正在创建一个post.js
文件。
Here's the code:
这是代码:
import { graphql } from 'gatsby';import PropTypes from 'prop-types';import React, { Component } from 'react';import Layout from '../layouts';class PostTemplate extends Component { render() { const post = this.props.data.wordpressPost; // @TODO: STEP #5: Use title and content in Gatsby. return (); }}PostTemplate.propTypes = { data: PropTypes.object.isRequired, edges: PropTypes.array};export default PostTemplate;// @TODO: STEP #4: Get current WP Post data via ID.export const pageQuery = graphql` query($id: String!) { wordpressPost(id: { eq: $id }) { title content } }`;
To start the development server to view the final result type the following command.
要启动开发服务器以查看最终结果,请键入以下命令。
npm start
You get the link from where you can access the site locally along with other details like no. of posts
, categories
and tags
that are being fetched.
您可以从本地访问该站点的链接以及其他详细信息(例如“否”)获得链接。 的posts
, categories
和tags
。
Here's a GIF for it:
这是它的GIF:
See how it has fetched only the required data from the WordPress site. To remind you once again, we are only getting posts
, tags
and categories
. To retrieve other types of data like widgets, comments, etc. you need to add in the includedRoutes
option.
查看它如何仅从WordPress网站获取所需的数据。 再次提醒您,我们只会收到posts
, tags
和categories
。 要检索其他类型的数据(例如小部件,注释等),您需要添加includedRoutes
选项。
To sum things up, the purpose of writing this article is to let you know how you can empower your site's front-end with these cutting-edge technologies. Gatsby.js not only provides a fast web experience but brings several added benefits which can uplift your WordPress site to the next level. Try this out and share your feedback in the comments section below.
综上所述,撰写本文的目的是让您知道如何使用这些尖端技术来增强站点的前端功能。 Gatsby.js不仅提供了快速的Web体验,还带来了一些附加的好处,这些好处可以将您的WordPress网站提升到一个新的水平。 尝试一下并在下面的评论部分中分享您的反馈。
翻译自:
盖茨比乔布斯
转载地址:http://ksuwd.baihongyu.com/