盖茨比乔布斯_我如何使自己的投资组合网站在盖茨比市快速崛起

盖茨比乔布斯

by Maribel Duran

通过Maribel Duran

我如何使自己的投资组合网站在盖茨比市快速崛起 (How I made my portfolio website blazing fast with Gatsby)

If you are thinking of building a static site with React and want it to perform as fast as a cheetah, you should consider using GatsbyJS. I decided to try it out and was amazed with how easy it was to setup, deploy, and how fast the site loads now. Gatsby uses the best parts of other front end tools to make the development experience feel like you’re on vacation.

如果您正在考虑使用React构建静态站点,并希望它像猎豹一样快地运行,则应考虑使用GatsbyJS。 我决定尝试一下,并且对它的设置,部署和站点加载速度如此之快感到惊讶。 Gatsby使用其他前端工具的最佳组成部分,使您的开发体验就像您在度假一样。

原始网站的性能问题 (Performance Issues With Original Website)

I had been meaning to optimize the images on my portfolio website, which was one of my first freeCodeCamp Frontend Development projects.

我一直想优化我的投资组合网站上的图像,这是我的第一个freeCodeCamp前端开发项目之一。

Ouch! A 33/100 Google optimization score was painful to see. Yup I needed some help from the optimization gods. My website contained at least 17 project screenshots. I didn’t want to have to compress each image, generate multiple sizes and resolutions of each image, and lazy-load them.

哎哟! Google的最佳化分数是33/100。 是的,我需要优化神的帮助。 我的网站至少包含17个项目屏幕截图。 我不想压缩每个图像,为每个图像生成多个大小和分辨率并延迟加载它们。

When I first created this website, the Bootstrap 3 img-responsive class took care of scaling the images to fit different screen sizes, but I didn’t think about the fact that it was still loading some of my screenshots that were around 1400 x 860 pixels on mobile devices!

当我第一次创建此网站时,Bootstrap 3 img-responsiveimg-responsive缩放图像以适合不同的屏幕尺寸,但是我没有想到它仍在加载我的一些1400 x 860的屏幕截图移动设备上的像素!

My score was also low because I had not minified my CSS or setup browser caching for it, and was not async loading external CSS resources.

我的分数也很低,因为我没有为此减少CSS或设置浏览器的缓存,也没有异步加载外部CSS资源。

盖茨比救援 (Gatsby To The Rescue)

I really wanted to rebuild this project using React. I could have used create-react-app which provides an out-of-the box build script and development server, but this still didn’t take care of the long task of having to crop different image sizes for all of my images.

我真的很想使用React来重建这个项目。 我本可以使用create-react-app提供开箱即用的构建脚本和开发服务器,但是这仍然不能解决为所有图像裁切不同图像大小的长期任务。

Fortunately I was listening to Syntax’s, “Why Static Site Generators are Awesome” episode, and they talked about a few static site generators on the StaticGen.com list. If you haven’t heard what static site generators do, they transform your site into a directory with a single HTML file and static assets. No database or server code needed.

幸运的是,我在听Syntax的 “为什么静态网站生成器如此出色一集 ,他们谈论了StaticGen.com列表上的一些静态网站生成器。 如果您还没有听说过静态网站生成器的工作,那么它们会将您的网站转换为具有单个HTML文件和静态资产的目录。 无需数据库或服务器代码。

Gatsby won me over due to the similarities it has with create-react-app, which includes hot reloading, easy dev environment setup, and a build script. Gatsby takes it further by offering server-side rendering, smart image loading, and dedication to performance.

Gatsby之所以赢得了我,是因为它与create-react-app的相似之处,其中包括热重载,轻松的开发环境设置和构建脚本。 Gatsby通过提供服务器端渲染,智能图像加载以及对性能的奉献精神,将其进一步发展。

Since Gatsby is built on the React, GraphQL, and Webpack stack, we can write our content as React components! Winning! Gatsby takes care of rendering at build time to the DOM as static HTML, CSS, and JavaScript.

由于Gatsby是基于React,GraphQL和Webpack堆栈构建的,因此我们可以将内容编写为React组件! 赢了! Gatsby负责在构建时以静态HTML,CSS和JavaScript的形式呈现给DOM。

盖茨比图像组件是BAE (Gatsby-image Component is BAE)

So now to what I’ve really been wanting to share with you. Gatsby-image! Gatsby-image, is a React component that was designed to work with Gatsby’s GraphQL queries to completely optimize image loading for sites.

现在,我真正想要与您分享的内容。 盖茨比图片! Gatsby-image是一个React组件,旨在与Gatsby的GraphQL查询配合使用,以完全优化站点的图像加载。

The approach is to use GraphQL queries to get images of the optimal size and then display them with the gatsby-image component.

该方法是使用GraphQL查询来获取最佳大小的图像,然后将其与gatsby-image组件一起显示。

How did I use this component to automatically create 3 thumbnails for each of my 17 project images? Magic! Not really, but it feels like it!

如何使用此组件为我的17个项目图像中的每个图像自动创建3个缩略图? 魔法! 不是真的,但是感觉就像这样!

In my src/pages/index.js file, I queried all of the project images and gave it an alias of ProjectImgs. Since the queried data is now accessible through the data object as a prop, I was able to pass the projectImgData data (which is a node list of my project images) to my <Projects /> component:

在我的src / pages / index.js文件中,我查询了所有项目图像,并为其命名了ProjectImgs。 由于现在可以通过数据对象作为道具来访问查询的数据,因此我能够将projectImgData数据(这是我的项目图像的节点列表)传递给我的<Projects />组件:

//imports
const HomePage = ({ data }) => {  const siteTitle = data.site.siteMetadata.title;  console.log(data.ProjectImgs);   const { edges: projectImgData } = data.ProjectImgs;  const { edges: iconImgData } = data.iconImgs;  return (    <div>     <Helmet      title={siteTitle}      link={[{ rel: "icon", type: "image/png", href: `${favicon}`}]}     />     <Cover coverImg={data.coverImg} />     <div className="container-fluid main">      <Navigation />      <AboutMe profileImg={data.profileImg} iconImgs={iconImgData}       />                     &lt;Projects projectImgs={projectImgData} />     <Contacts />     <Footer />     </div>    </div>  );};
export const query = graphql`  query allImgsQuery {    //additional queries    ...
ProjectImgs: allFile(      sort: { order: ASC, fields: [absolutePath] }      filter: { relativePath: { regex: "/projects/.*.png/" } }    ) {      edges {        node {          relativePath          name          childImageSharp {            sizes(maxWidth: 320) {              ...GatsbyImageSharpSizes            }          }        }      }    }
//additional queries...  }`;
Note: I had some trouble getting my graphQL queries to work and had to do a little digging around to figure out how to query for multiple images within a folder. What helped me was looking at other portfolio sites made with Gatsby.
注意:我无法使我的graphQL查询正常工作,并且不得不做一些挖掘工作以弄清楚如何在一个文件夹中查询多个图像。 帮助我寻找由Gatsby制作的其他投资组合网站的原因。

Using the console, we can see what data.ProjectImgs returns to give you a better idea of what I am receiving from the query and what I am passing to my Projects component:

使用控制台,我们可以看到返回了哪些数据data.ProjectImgs返回的内容使您可以更好地了解我从查询中收到的内容以及要传递给我的Projects组件的内容:

Console.log(data.ProjectImgs) returns an array of edges:

Console.log(data.ProjectImgs)返回边的数组:

{edges: Array(17)}edges:(17) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]__proto__:Object{edges: Array(17)}

Extending one of the edges shows a node object that contains a childImageSharp property. This contains a sizes object which holds the image’s thumbnail sources. This sizes object is what we ultimately want to pass to our gatsby-image’s <Img /> component.

延伸边缘之一将显示一个包含childImageSharp属性的节点对象。 它包含一个sizes对象,该对象保存图像的缩略图源。 这个尺寸对象是我们最终要传递给gatsby-image的<Img />组件的对象。

Extending an edge to show the information in a node:

扩展边缘以显示节点中的信息:

{edges: Array(17)} edges: Array(17) 0:  node:   childImageSharp: {sizes: {…}}   name: "CamperLeaderboard"   relativePath:"projects/CamperLeaderboard.png"   __proto__:Object   __proto__:Object 1:{node: {…}}
//more nodes...

In my <Projects /> component, I receive the node list of project images as a prop and for each project, I extract the childImageSharp.sizes object (which is renamed to imageSizes), and pass it into the gatsby-image’s &lt;Img /> component:

在我的<Projects />组件中,我以道具的形式接收项目图像的节点列表,并为每个项目提取 childImageSharp .sizes对象(已重命名为imag eSizes),并将其传递到gatsby-im中。 age's & lt; Img />组件:

import React, { Component } from "react";import Img from "gatsby-image";//more imports...
class Projects extends Component {  constructor(props) {    super(props);
this.state = {      selectedType: "front-end"   };
this.onSelectChange = this.onSelectChange.bind(this);  }   onSelectChange(e) {    this.setState({ selectedType: e.target.value }); }
render() {    const projectImgs = this.props.projectImgs;    const { selectedType } = this.state;    return (      <section id="projects" className="section projects">        <h2 className="text-center">PROJECTS</h2>        <div className="section-content">          <div className="subheader">            <FormGroup controlId="formControlsSelect">             ...            </FormGroup>          </div>          <div className="project-list">            {projectList.map(project => {              const isSelectedType = selectedType === project.type;              const singleCardClass = classNames("single-card", {                hide: !isSelectedType               });              const image = projectImgs.find(n => {                return n.node.relativePath ===                        `projects/${project.img}`;                     });              const imageSizes = image.node.childImageSharp.sizes;              return (                <a                  href={project.url}                  key={project.url}                  className={singleCardClass}                  target="_blank"                >;                  <div className="card-img">                    <Img                      title={project.name}                      alt="Screenshot of Project"                      sizes={imageSizes}                      className="card-img_src center-block"                    />                  </div>                  <div className="blue-divider" />                  <div className="card-info">                    <h4 className="card-name">{project.name}</h4>                    <p>{project.description}</p>                  </div>                </a>              );            })}          </div>        </div>      </section>    );  }}
export default Projects;

And this is the end result:

这是最终结果:

That’s it! The <Img /> component takes care of using the correct image size, creating the blur up effects, and lazy loading my project images, since they are located further down the screen. The above querying was a bit more complex than querying a single image.

而已! <Img />组件负责使用正确的图像尺寸,创建模糊效果以及延迟加载我的项目图像,因为它们位于屏幕下方。 上面的查询比查询单个图像要复杂一些。

If you’re new to GraphQL, below are a few resources that better explain how to use GraphQL queries and the gatsby-image component:

如果您是GraphQL的新手,以下是一些资源,可以更好地解释如何使用GraphQL查询和gatsby-image组件:

主持Netlify轻而易举 (Hosting To Netlify Was a Breeze)

Since Gatsby generates static files, you can pretty much use any hosting provider. I decided to change my hosting provider from Github Pages to Netlify. I had been hearing about how easy it is to deploy a website to Netlify and they were not lying. Their free tier provides awesome features that makes the deployment process and making a website secure a breeze. It provides one click HTTPS, global CDN, continuous deployment, and the list goes on.

由于Gatsby生成静态文件,因此您几乎可以使用任何托管服务提供商。 我决定将托管提供商从Github Pages更改为Netlify。 我一直在听说将网站部署到Netlify有多么容易,而且他们没有撒谎。 他们的免费层提供了很棒的功能,这些功能使部署过程和网站安全变得轻而易举。 它提供一键式HTTPS,全局CDN,连续部署,然后列表继续。

The setup process was so simple. I logged into Netlify, clicked the “New site from Git” button on my dashboard, and chose the Git repository for this project. I configured the site to deploy from master and clicked “Deploy Site”. That was it! Netlify takes care of the build process and publishes it to the web.

设置过程非常简单。 我登录Netlify,单击仪表板上的“来自Git的新站点”按钮,然后为该项目选择了Git存储库。 我将站点配置为从主站点进行部署,然后单击“部署站点”。 就是这样! Netlify负责构建过程并将其发布到Web。

As I mentioned, Netlify offers continuous deployment, so now whenever I push changes to my master branch on GitHub, this automatically triggers a new build on Netlify. Once the build is complete, my changes will be live on the web.

正如我提到的,Netlify提供了连续部署,因此现在每当我将更改推送到GitHub上的master分支时,这都会自动触发Netlify上的新构建。 构建完成后,我的更改将在线发布。

未来看起来光明 (The Future Looks Bright)

By rebuilding my website with Gatsby, not only did I learn about the different image optimization techniques for future projects, I also learned a bit about GraphQL, practiced my React skills, and took the opportunity to try out a new hosting provider.

通过使用Gatsby重建网站,我不仅了解了未来项目的不同图像优化技术,还学到了一些有关GraphQL的知识,练习了React的技巧,并借此机会尝试了新的托管服务提供商。

I am really excited for the future of Gatsby and similar front end tools that remove the complexities of configuring environments and build tools. Instead, we can focus our energy and time on our code to build awesome stuff for our users.

我对Gatsby和类似的前端工具的未来感到非常兴奋,这些前端工具将消除配置环境和构建工具的复杂性。 相反,我们可以将精力和时间集中在我们的代码上,以为我们的用户构建出色的东西。

If you liked this article, click the? below so other people will see it here on Medium.
如果您喜欢这篇文章,请单击“?”。 下方,因此其他人会在Medium上看到它。

Let’s be friends on Twitter. Happy Coding :)

让我们在Twitter上成为朋友。 快乐编码:)

翻译自: https://www.freecodecamp.org/news/how-i-made-my-portfolio-website-blazing-fast-with-gatsby-82ccddc2f671/

盖茨比乔布斯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值