gatsby_Gatsby更快的WordPress网站

news/2024/7/7 19:57:24

gatsby

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 approaches to building websites that can serve content to users quickly.

谈论最新的前沿Web技术,您会发现一些令人印象深刻的名称,例如React.js,Vue.js,Next.js等。 他们打开了新的门户网站和方法来构建可以向用户快速提供内容的网站。

One framework that can increase overall site speed and load times is Gatsby.js.

Gatsby.js是可以提高整体网站速度和加载时间的一种框架 。

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

A website that loads fast entails the following perks and benefits for developers:

快速加载的网站为开发人员带来以下好处和好处:

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

    流量和参与度 :快速网站上吸引了更多网站访问者,这意味着更高的投资回报率和用户参与度。

  • Page Ranks: Fast websites earn higher browser rankings.

    页面排名 :快速网站在浏览器中的排名更高。

使用Gatsby.js和WordPress提高网站速度 (Improving Site Speed With Gatsby.js and WordPress)

Gatsby.js is a free and open-source React.js-based framework that helps developers build websites and applications. It is part of a general trend toward JAMstack (JavaScript APIs Markup) sites, which aim to increase overall site speed and load times.

Gatsby.js是一个免费的基于开源React.js的框架,可帮助开发人员构建网站和应用程序。 这是向JAMstack(JavaScript API标记)网站发展的总体趋势的一部分,该网站旨在提高网站的整体速度和加载时间。

But where does Gatsby fit with WordPress, one of the most widely-used CMS options available today? Despite its usability and robust community, WordPress can pose challenges to building a modern frontend, for the following reasons:

但是,盖茨比在哪里适合WordPress(今天可用的最广泛使用的CMS选项之一)? 尽管具有可用性和强大的社区,但出于以下原因,WordPress可能会给构建现代前端带来挑战:

  • Updates and Changes: WordPress is regularly updated, but it still lacks parity with other rapidly-changing front-end technologies. Staying up-to-date with these technologies adds an additional burden for the developer.

    更新和变更 :WordPress会定期更新,但仍与其他快速变化的前端技术缺乏同等性。 紧跟这些技术的最新发展为开发人员增加了额外的负担。

  • Continuous Integration and Deployment: Right now, few Continuous Integration/Deployment (CI/CD) options exist in the WordPress ecosystem.

    持续集成和部署 :目前,WordPress生态系统中几乎没有持续集成/部署(CI / CD)选项。

  • Integration Costs: It can be challenging to integrate some of the latest front-end technologies with a WordPress application.

    集成成本 :将一些最新的前端技术与WordPress应用程序集成可能是一个挑战。

Using Gatsby can address some of these limitations. In the following steps, we will show you how to integrate Gatsby with WordPress to take full advantage of both. First, we are going to configure a basic Gatsby project setup. Then, we’ll use it to fetch data from our WordPress site.

使用盖茨比可以解决其中一些限制。 在以下步骤中,我们将向您展示如何将Gatsby与WordPress集成以充分利用两者。 首先,我们将配置基本的盖茨比项目设置。 然后,我们将使用它来从WordPress网站获取数据。

将Gatsby.js与WordPress集成 (Integrating Gatsby.js with WordPress)

First, we will set up a demo Gatsby project.

首先,我们将建立一个Gatsby示范项目。

Install the Gatsby CLI by typing the following command in your terminal:

通过在终端中键入以下命令来安装Gatsby CLI:

  • npm install -g gatsby-cli

    npm install -g gatsby-cli

Next, create a new Gatsby site with the following command:

接下来,使用以下命令创建一个新的Gatsby网站:

  • gatsby new site-name

    gatsby新站点名称

To access your site folder contents, type the following:

要访问您的站点文件夹内容,请键入以下内容:

  • cd site-name

    cd 站点名称

Finally, start the development server to begin building your site:

最后,启动开发服务器以开始构建您的站点:

  • gatsby develop

    盖茨比开发

安装gatsby-source-wordpress插件 (Installing the gatsby-source-wordpress Plugin)

Assuming that you have a WordPress site already set up, and you would like to have a frontend built with Gatsby.js, all you need to do is pull your existing site data into your static Gatsby site. You can do that with the gatsby-source-wordpress plugin.

假设您已经建立了一个WordPress网站,并且希望使用Gatsby.js构建前端,那么您要做的就是将现有的网站数据拉入静态的Gatsby网站。 您可以使用gatsby-source-wordpress插件来做到这一点。

This tutorial uses the default WordPress REST API site, though you are free to use a pre-existing WordPress setup if you have one.

本教程使用默认的WordPress REST API站点 ,但是如果您有的话,可以自由使用现有的WordPress设置。

Inside your terminal, type the following to install this plugin:

在终端内,键入以下内容以安装此插件:

  • npm install gatsby-source-wordpress

    npm安装gatsby-source-wordpress

配置插件 (Configuring the Plugin)

Inside your gatsby-config.js file, the main Gatsby configuration file, you will add some WordPress-specific configuration options. These include your WordPress site’s baseUrl, the preferred HTTP protocol, and settings pertaining to the Advanced Custom Fields (ACF) plugin. The includedRoutes fields specifies the data we want to fetch.

在您的主要盖茨比( gatsby-config.js配置文件gatsby-config.js文件中,您将添加一些特定于WordPress的配置选项。 其中包括WordPress网站的baseUrl ,首选HTTP protocol以及与“ 高级自定义字段(ACF)插件”有关的设置。 includedRoutes字段指定我们要获取的数据。

Using the demo WordPress site from the step above, the current frontend looks like this:

使用上面步骤中的演示WordPress网站,当前前端如下所示:

For the purposes of this tutorial, add the following code to a file called gatsby-config.js:

就本教程而言,将以下代码添加到名为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
        }
    },
  ],
}

使用提取的WordPress数据 (Using 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.jsfile, which makes the fetched data available to queries from GraphQL. At build time, the gatsby-source-wordpress plugin fetches your data, and uses it to ”automatically infer a GraphQL schema” which you can query against.

一旦Gatsby网站从WordPress源URL提取数据,就该创建网站页面了。 这是通过在gatsby-node.js文件中实现createPages API来完成的,该文件使获取的数据可用于GraphQL的查询。 在构建时, gatsby-source-wordpress插件获取您的数据,并使用它“自动推断一个GraphQL模式”,您可以对其进行查询。

Add the following code to a file called gatsby-node.js:

将以下代码添加到名为gatsby-node.js的文件中:

/**
 * 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 it

const path = require(`path`);
const slash = require(`slash`);

/** STEP #1: 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;

    // 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`);

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

This will iterate through existing WordPress post data.

这将遍历现有的WordPress发布数据。

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

Next, we will create a folder for templates, where you can add files for posts, pages, and layouts. For now, we will create a post.js file to fetch posts from our WordPress site.

接下来,我们将为模板创建一个文件夹,您可以在其中添加文章,页面和布局的文件。 现在,我们将创建一个post.js文件以从WordPress网站获取帖子。

Add the following code to the file:

将以下代码添加到文件中:

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;

        // STEP #5: Use title and content in Gatsby.
        return (
            <Layout>
                <h1 dangerouslySetInnerHTML={{ __html: post.title }} />
                <div dangerouslySetInnerHTML={{ __html: post.content }} />
            </Layout>
        );
    }
}

PostTemplate.propTypes = {
    data: PropTypes.object.isRequired,
    edges: PropTypes.array
};

export default PostTemplate;

// STEP #4: Get current WP Post data via ID.
export const pageQuery = graphql`
    query($id: String!) {
        wordpressPost(id: { eq: $id }) {
            title
            content
        }
    }
`;

检查最终结果 (Examining the Final Result)

To start the development server and view the final result, type the following command in your terminal:

要启动开发服务器并查看最终结果,请在终端中键入以下命令:

  • npm start

    npm开始

You will get the link where you can access the site locally, along with other details like the number of posts, categories, and tags that are being fetched.

您将获得一个链接,您可以在其中本地访问该站点,以及其他详细信息,例如正在获取的posts数, categoriestags

Here’s a GIF that demonstrates what this will look like:

这是一个GIF,展示了它的外观:

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

You can see how our application is only fetching the required data from the WordPress site. This includes posts, tags and categories. To retrieve other types of data like widgets or comments, you will need to add the appropriate values to the includedRoutes option.

您可以看到我们的应用程序如何仅从WordPress网站获取所需数据。 这包括poststagscategories 。 要检索其他类型的数据(例如小部件或注释),您需要将适当的值添加到includedRoutes选项。

结论 (Conclusion)

By following this tutorial, you now have a WordPress application backend integrated with a Gatsby.js frontend. Gatsby provides a fast web experience and brings with it added benefits that can enhance your existing WordPress site. You now have a platform for further experimentation with using Gatsby to power your site,

通过遵循本教程,您现在拥有了一个与Gatsby.js前端集成的WordPress应用程序后端。 Gatsby提供了快速的Web体验,并带来了额外的好处,可以增强您现有的WordPress网站。 现在,您有了使用Gatsby为网站提供动力的进一步试验平台,

翻译自: https://www.digitalocean.com/community/tutorials/faster-wordpress-sites-with-gatsby

gatsby


http://www.niftyadmin.cn/n/3649230.html

相关文章

经典面试问题:12小球问题算法(源码)

(文档请参考&#xff1a;http://blog.csdn.net/CXXSoft/archive/2006/09/28/1299731.aspx)3、 运行效果4、 算法源码...{ 作品名称: 小球问题通用解决方案 开发作者: 成晓旭 开发时间: 2003年01月22日 完成时间: 2003年01月23日 修改时间1: 2003年11…

three react_使用react-three-fiber在React中编写Three.js

three reactSo you want to write some 3D graphics/animations in your React apps using three.js? Let’s see how we can do just that, leveraging the react-three-fiber library. 那么您想使用three.js在React应用中编写一些3D图形/动画吗&#xff1f; 让我们看看如何利…

Ubuntu 安装Postgres数据库,Windows 安装PgAdmin进行远程管理,Django远程连接 手记

Ubuntu通过SSH操作&#xff1a; 1. 安装postgres ~$ sudo apt-get install postgresql 2. 添加数据库用户&#xff1a;sudo -u postgres createuser -P YOURNAME3. 别忘了配置密码&#xff0c;作为超级用户。4. 创建用户名对应的数据库sudo -u postgres createdb YOURNAME …

通用网页数据采集系统的架构和运行机理

VersionDateCreatorDescription1.0.0.12004-9-06郑昀 掌上灵通草稿摘要&#xff1a;本文档详细介绍了网页数据采集系统的架构和运行机理。第一章简单介绍了Spider的设计意图和模块构成。第二章简单介绍了Spider.Crawler层如何抓取网页并落地。第三章简单介绍了Spider.Parser层如…

Android源码学习之ActivityManager框架解析

ActivityManager在操作系统中有重要的作用&#xff0c;本文利用操作系统源码&#xff0c;逐步理清ActivityManager的框架&#xff0c;并从静态类结构图和动态序列图两个角度分别进行剖析&#xff0c;从而帮助开发人员加强对系统框架及进程通信机制的理解。 ActivityManager的作…

使用flutter_launcher_icons自动生成Flutter应用程序图标

I’ve been working on a Flutter application for the better half of this year, and as we get closer to release, I realized I hadn’t set an app icon yet. I initially went ahead and set my icons with Xcode and Android Studio, but after finding the flutter_la…

开源软件许可探究

选择了“原创”标签&#xff0c;其实内容并非完全原创 今天研究了一下开源软件&#xff0c;本文将自己的理解各篇转载的文章做个归并和整理 如今开源的软件已经越来越被广泛使用&#xff0c;各种专利纠纷也越来越多。工作上要求对开源协议的理解也很迫切&#xff0c;做技术架构…

Android框架层之音频管理器AudioManager的使用

为了能通过程序管理系统音量&#xff0c;或者直接让系统静音&#xff0c;可以使用AudioManager来实现&#xff0c;同时也用到MediaPlayer对音频进行控制。 下面是一个简单的对音频控制的例子&#xff08;注&#xff1a;音频文件需要在res文件夹下创建一个raw文件夹&#xff0c;…