博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
盖茨比乔布斯_用盖茨比快速浏览WordPress站点
阅读量:2518 次
发布时间:2019-05-11

本文共 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.jsVue.jsNext.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性能参数,那么改善页面加载时间就成为我的待办事项清单上的第一位 。 因为现在网站速度不再是一种奢侈,所以这是必要的

快速网站的目标 (Goals of a Fast Website)

A website which loads fast brings the following perks and benefits for you:

快速加载的网站为您带来以下好处和好处:

  • Traffic and Engagement: You get more site visitors on a fast site that translates to better ROI and user engagement.

    流量和参与度 :在快速的网站上吸引更多的网站访问者,可以带来更好的ROI和用户参与度。
  • Page Ranks: Fast websites earn not only better but higher browser rankings. Google ranks sites higher which, load in less than one second.

    网页排名 :快速的网站不仅可以获得更好的浏览器排名,而且可以获得更高的浏览器排名。 Google对网站的排名较高,加载时间不到一秒钟。
  • Sales: Better SEO rankings and user engagement bring more earnings. A fast site encourages a visitor to stay much longer; hence, more chances of lead conversions.

    销售 :更好的SEO排名和用户参与度带来更多收益。 快速的网站会鼓励访客停留更长的时间; 因此,潜在客户转换的机会更大。

( )

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构建满足所有最新技术需求的现代前端非常困难。 我尝试找出一些原因,原因如下:

  • Updates and Changes: WordPress is one of the most regularly updated CMS, but it still can't meet the speed with which front-end technologies change. Staying up-to-date with these added structural modifications is super hard and brings an additional responsibility.

    更新和更改 :WordPress是更新最频繁的CMS之一,但是它仍然不能满足前端技术更改的速度。 与这些附加的结构修改保持最新是非常困难的,并带来了额外的责任。
  • Deployment and Continuous Integration: Right now limited deploying and continuous integration options exist in the WordPress ecosystem. The process is not only challenging but requires a lot of money.

    部署和持续集成 :目前,WordPress生态系统中存在有限的部署和持续集成选项。 该过程不仅具有挑战性,而且需要大量资金。
  • Knowing Everything: Staying up-to-date with all the latest web trends is not easy. You cannot learn about React, Webpack, GraphQl, etc. and then integrate everything inside WordPress. A big NO!

    了解一切 :掌握所有最新的网络趋势并不容易。 您无法了解React,Webpack,GraphQl等,然后将所有内容集成到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 ,那么您只需执行下面提到的这些步骤。 这些将帮助您建立基本的盖茨比项目。

  • Install the Gatsby CLI by typing the following command in your terminal.

    通过在终端中键入以下命令来安装Gatsby CLI。
npm install -g gatsby-cli
  • Next, create a new Gatsby.js site through the following.

    接下来,通过以下步骤创建一个新的Gatsby.js网站。
gatsby new site-name
  • To access your site folder contents type the following.

    要访问您的站点文件夹内容,请键入以下内容。
cd site-name
  • Finally, start the development server to begin building your Gatsby.js site.

    最后,启动开发服务器以开始构建您的Gatsby.js网站。
gatsby develop

步骤1:安装gatsby-source-wordpress插件 (Step #1: Install gatsby-source-wordpress Plugin)

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

步骤2:配置插件 (Step #2: Configuring the Plugin)

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网站的baseUrlprotocol ,是否托管在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        }    },  ],}

步骤#3:使用提取的WordPress数据 (Step #3: Using the Fetched WordPress Data)

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 } }); });};

步骤#4:创建一个post.js模板 (Step #4: Create a post.js Template)

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 } }`;

步骤#5:最终结果 (Step #5: Final Result)

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.

您可以从本地访问该站点的链接以及其他详细信息(例如“否”)获得链接。 的postscategoriestags

Here's a GIF for it:

这是它的GIF:

Let's take a look at this revamped front-end which is now powered with Gatsby.js and a WordPress back-end.

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网站获取所需的数据。 再次提醒您,我们只会收到poststagscategories 。 要检索其他类型的数据(例如小部件,注释等),您需要添加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/

你可能感兴趣的文章
【BZOJ3994】[SDOI2015] 约数个数和(莫比乌斯反演)
查看>>
对其他组的评价
查看>>
MVC设计模式
查看>>
Grunt 实战
查看>>
如何修改WAMP中mysql默认空密码
查看>>
[Android]做android蛮有用的一个技巧
查看>>
Swift - defer关键字(推迟执行)
查看>>
LintCode "Coins in a Line"
查看>>
Windows 批处理bat程序设计简明教程
查看>>
Selenium之前世今生
查看>>
High Five Lintcode
查看>>
【linux就该这么学】-03
查看>>
文件资源下载到本地后如何调用
查看>>
K2BPM怎么让金融数据更有意义?
查看>>
AndroidManifest Ambiguity方案原理及代码
查看>>
目前的小幸福。
查看>>
MSSQL2008 常用sql语句
查看>>
图片里的文字转换成word
查看>>
远程多台服务器备份数据方案
查看>>
Linux与Windows协同工作
查看>>