Gatsby

Gatsby

Blazing fast modern site generator for React. Go beyond static sites: build blogs, e-commerce sites, full-blown apps, and more with Gatsby
Ruth  Clarke

Ruth Clarke

1673575168

Gatsby V2 Starter for Ethereum Dapps using React & Web3!

gatsby-eth-dapp-starter

Gatsby v2 Starter for Ethereum Dapps using React & Web3!

Account Management Integrations:

QR-Connected Wallets

  • Coinbase WalletLink
  • Wallet Connect

Hosted Wallets

  • Fortmatic
  • Torus
  • Portis
  • Uport
  • Authereum
  • Bitski
  • SquareLink
  • Arkane Network

Browser Wallets

  • MetaMask
  • Native (Brave, Opera, Toshi, Cipher, Status, etc..) -- Partially Done

Hardware Wallets

  • Ledger -- todo
  • Trezor -- todo

Blockchain Event Streaming & Notifications:

  • dfuse.io -- todo

Ethereum Design Components:

  • Rimble UI

Gatsby Plugins:

  • gatsby-plugin-react-helmet
  • gatsby-plugin-create-client-paths
  • gatsby-source-filesystem
  • gatsby-transformer-sharp
  • gatsby-plugin-sharp
  • gatsby-plugin-manifest
  • gatsby-plugin-lodash
  • gatsby-plugin-netlify
  • gatsby-plugin-offline

Build Environment:

  • node: 10.17.0
  • npm: 5.6.0
  • yarn: 1.19.1

Develop/Run:

To start, create the following files in the root directory of the project:

.env.development

GATSBY_ETH_JSONRPC_URL=https://ropsten.infura.io/v3/__YOUR_INFURA_API_KEY_HERE__
GATSBY_ETH_CHAIN_ID=3

GATSBY_FORTMATIC_APIKEY=__YOUR_FORTMATIC_API_KEY_HERE__
GATSBY_PORTIS_DAPP_ID=__YOUR_PORTIS_DAPP_ID_HERE__
GATSBY_UPORT_DAPP_NAME=__YOUR_UPORT_DAPP_NAME_HERE__
GATSBY_BITSKI_CLIENT_ID=__YOUR_BITSKI_CLIENT_ID_HERE__
GATSBY_SQUARELINK_DAPP_ID=__YOUR_SQUARELINK_DAPP_ID_HERE__
GATSBY_ARKANE_CLIENT_ID=__YOUR_ARKANE_CLIENT_ID_HERE__

Next, run the following commands from a terminal:

yarn install
yarn start

Or, with NPM:

npm install
npm run develop

Demo:

https://gatsby-eth-dapp-starter.netlify.com/


Download details:

Author: robsecord
Source code: https://github.com/robsecord/gatsby-eth-dapp-starter

License: MIT license

#web3 #blockchain #Ethereum  #react #Gatsby 

Gatsby V2 Starter for Ethereum Dapps using React & Web3!
Anissa  Beier

Anissa Beier

1671803295

What’s New In Gatsby

In this Gatsby article, we'll learn about What's New in Gatsby. You may have heard things about Gatsby a few years ago, and if you’re not keeping an eye on what we’re doing today, it’s entirely understandable for you to assume nothing has changed.

Naturally, given Gatsby operates in the JavaScript space, things have not only changed in the last few years, but they’ve also likely changed in the last few weeks. This is why I’ve written this article explaining what Gatsby can do today, and how I used some of our new features when upgrading my personal website: paulie.dev from Gatsby 2 to Gatsby 4.

Let’s dive in!

Server-Side Rendering (SSR)

In the fall of 2021, Gatsby launched Gatsby 4 with SSR support. I’ve used this on paulie.dev/dashboard. There are three features on my dashboard that are ideally suited to SSR

Now let’s dive into each of these and how Gatsby 4 enabled me to build them easily!

ALL REACTIONS

The reaction data is requested from a Fauna Database, and displayed in an interactive Accordion component. The reactions are first grouped by type (e.g. Happy, Cool, Tongue, and so on) and then listed by slug (URL), and a count is also displayed for each of the grouped properties.

Happy, Cool, Sad reactions order by amount and displayed in a list

All Reactions posted by visitors to paulie.dev. (Large preview)

VISITORS BY COUNTRY AND VISITORS BY LOCATION

The Visitors By Country data is requested from the new Google Analytics Data API (GA4) and listed in order by the amount of visits per country. Visitors By Location data is requested from the soon-to-be deprecated Google Analytics Core Reporting API (UA), and each location is plotted around a 3D globe that I created using three.js / @react-three/fiber. It’s made interactive using Orbit Controls from @react-three/drei. You might be wondering why I didn’t plot the GA4 data around the globe, too. The lat/long required to plot the points isn’t part of the new GA4 API. See for yourself in the GA4 Dimensions & Metrics Explorer (Built with Gatsby)

Here’s an issue on the ga-dev-tools GitHub Repo… fingers crossed it’ll get looked into at some point. 🤞

Visitors by country ordered by amount displayed next to a country flag emoji. Visitors by locations displayed as small pink markers around an interactive spinning 3D globe

All Countries and Locations of visitors to paulie.dev. (Large preview)

The data displayed in these two features is up to date as of the last time the page loaded. The Visitors By Country data will also be displayed if JavaScript is disabled in the browser. The Interactive globe, sadly, will not because three.js needs JavaScript.

SSR/CSR Hybrid

SSR is a good option for data that changes relatively quickly, but when using SSR, the data will only be “fresh” when a user first visits the page. If data were to change after the page has loaded, users would need to refresh the page to see the latest updates. This is where a hybrid SSR with CSR (Client-side request) can help.

LATEST REACTION

The Latest Reaction Feature uses this hybrid SSR/CSR approach. If Javascript is disabled in the browser, the Latest Reaction is rendered using SSR. However, if JavaScript is enabled, I poll the Fauna database using a Gatsby Serverless Function every 60 seconds and retrieve the latest reaction. This means the Latest Reaction is never more than 60 seconds out-of-date and will refresh without users needing to reload the page.

Progress timer bar decreasing before a new request is made to the database to display the emoji and url for the last reaction captured

Latest Reaction feature polling for updates every 60 seconds. (Large preview)

SSR/SSG Hybrid

Again, whilst SSR is a good option, is it always needed? Some of the data changes that occur on my site happen because of something I change. E.g I write a new post, commit the changes and trigger a build. In this instance, I’ve opted for a hybrid SSR with SSG (Static Site Generation) approach. The page is still Server-side rendered but the charts are statically generated. (Yes, a page can be both SSR and SSG.)

DATA CHARTS

I’ve used this hybrid approach and created 4 data visualizations to help me better understand the frequency with which I write and the kind of content I’m writing about, and who for. Each of these charts is populated by data from around my site that has been extracted from the frontmatter in my .mdx files and then queried from Gatsby’s data layer using GraphQL.

These charts allow me to plot or count the number of posts or articles I’ve posted each month over the last four years, the amount of posts or articles I’ve posted on each day of the week, the external publications I’ve written for (excluding Gatsby) and how many times, and then finally, a chart to show the total count for each tag used in all of the posts and articles.

Line chart displaying quantity of posts plotted over 12 months for the years, 2019, 2020, 2021 and 2022

Amount of posts by month for the last four years. (Large preview)Bar chart displaying quantity of posts plotted over each day of the week for the years, 2019, 2020, 2021 and 2022Amount of posts by day for the last four years. (Large preview)Radar chart showing quantity of posts written for external publications, and Donut chart displaying quantities of times a tag has been usedAmount of articles written for external publications and quantities of tags usage. (Large preview)

As mentioned, the dashboard of my site is Server-side rendered, but all of the above can be considered “static,” and generally speaking, when folks refer to a static site, they’re probably talking about text and images on a page.

The SSG data for the charts can’t really go out of sync because each time I write a new post or article, I commit the .mdx file to my repository, which in turn kicks off a new build in Gatsby Cloud.

This data can therefore be considered up to date as of the time the page loaded and likely won’t change during the duration of a page view.

The way I’ve created these charts uses the same technique, but because I like data, I chose to turn it into something more visually interesting. (fun fact, none of these charts were created using a charting library).

They are all hand-crafted using good ol’ mathematics, the SVG element, and with help from the following folks and their great tutorials — all will work with JavaScript disabled in the browser! 💅.

I prefer this hand-crafted approach as I found I have more control over the final output. When I’ve used charting libraries in the past I always seem to be hacking over the top of something to get the desired look, and not all charting libraries will work if JavaScript is disabled in the browser.

Deferred Static Generation (DSG)

With the release of Gatsby 4 (October 2021), Gatsby announced DSG. This page rendering method is similar to the tried and tested SSG approach (where pages are statically rendered on the server at build time), but the key difference is when.

Historically speaking, all Gatsby pages were SSG, and all pages would have to be built ahead of time. Whilst this often results in better SEO and a faster user experience than SSR, it can have adverse effects on build times.

Builds tend to fall into two main categories, and then there are a few subcategories for each:

  1. Local Development
    1. Content changes
    2. Code changes
      1. Changes that affect every page (e.g. Header/Footer)
      2. Changes that affect a single page
  2. Production Deployment.
    1. Content changes
    2. Code changes
      1. Changes that affect every page (e.g. Header/Footer)
      2. Changes that affect a single page

When developing a Gatsby site locally, it’s not always advisable to build every page, fortunately, while developing locally you probably won’t need to build all the pages.

You can use this “trick” if you like, it works a treat!: How to “fix” Gatsby’s slow local build times.

For production, however, Gatsby will need to build every page and if your content is changing quickly or you have multiple content creators working on your site, they’ll need to see the built page in a timely fashion.

Content creators typically won’t be using local .mdx files as I have on my site to write content, so Gatsby/Gatsby Cloud has a number of super fast preview options for popular CMSs such as Contentful, WordPress, Sanity, and many more!.

Specifically, in the case of production sites and content changes, DSG can be configured to defer the static generation of any page or type of page.

In short, by using DSG, Gatsby hands control of Static Site Generation over to you, the developer. By choosing which pages to defer, you have more control over your build times. After all, you know your site better than anyone, so you’ll be able to create a custom defer strategy that works best for your needs.

HOW DOES GATSBY’S DSG WORK?

Let’s start with the output. A page created using DSG is the same as a page that has been created using SSG. Meaning: it’s a fully constructed HTML page that’s been pre-built and cached on the server ahead of time and is sent to the browser when a user visits that page.

It contains all the important metadata that Google needs to index your site and since the page is pre-built, it’s super fast and provides the best user experience for end users.

When this page is rendered, however, is where DSG comes in.

If a page is deferred using DSG, then Gatsby won’t pre-build it when you deploy your site. Instead, the first time a user visits that page Gatsby will build it on the fly, or just-in-time, and then send it to the browser when it’s ready. How is this different from SSR, then?

HOW IS DSG DIFFERENT FROM SSR?

The above will only happen the first time a page is visited. When one user has visited a page once, the next user will be served an ahead-of-time pre-built SSG page from the cache, and every visitor after the first will experience the same speed as if the page were rendered using SSG.

With SSR, every visitor gets the same, sometimes slow experience, as they have to wait for the Server to generate the page before it’s sent to the browser. Typically, this leads development teams to optimize then cache headers, which is error-prone and oftentimes complex. This leads to pain for teams, and I prefer to minimize my own!

WHEN TO DEFER USING DSG

I’ve seen some really interesting defer strategies from a number of our customers. Some choose to defer pages that aren’t visited that often and this strategy is determined using Google Analytics and page view statistics. Others defer based on the date a post or article has been published; some defer based on the popularity or stock level of a product. The options you have available to you, are quite frankly endless, each business has its own use case and Gatsby is flexible enough to accommodate any and all eventualities.

Here’s a diff of the classic createPage; with DSG, you could defer all but the latest 100 posts (provided the posts have been sorted by date first, of course!)

const posts = result.data.allMdx.nodes

posts.forEach((post, index) => {
  createPage({
    path: post.slug,
    component: path.join(__dirname, `./src/templates/posts.js`),
    context: {
      id: post.id,
    },
    // index is zero-based index
+    defer: index + 1 > 100,
  })
})

…and for the curious, you can also enable DSG in our alternative page creation method: File System Route API.

export async function config() {
  return ({ params }) => {
    return {
      defer: // your defer strategy
    };
  };
}

This one small change typically results in a quite drastic reduction in build times. Of course, it depends upon the use case, but some of our customers have reduced their build times by over 50%, which means that each and every build gives them time back in their day to do more interesting things than wait for a build!

Serverless Functions

In the summer of 2021 Gatsby released Functions, I’ve used Functions for each of my; post, article, demo, or stream pages to capture visitors’ reactions.

Interface of reaction emojis and prompt asking users to click to submit how they feel.

Invite users to leave a reaction to the content. (Large preview)

Using a set of SVG emojis, I invite users to leave a reaction to my content. When any of the emojis are clicked, I post to a Serverless Function from the client with the following payload.

await fetch('/api/add-reaction', {
  method: 'POST',
  body: JSON.stringify({
    title: title,
    slug: slug,
    reaction: reaction,
    date: new Date()
  })
});

The Serverless Function, in turn, securely posts to a Fauna Database where the data is stored and ready to be retrieved and counted on the SSR page as mentioned above.

const faunadb = require('faunadb');

export default async function handler(req, res) {
  const { title, slug, reaction, date } = JSON.parse(req.body);

  const q = faunadb.query;

  const client = new faunadb.Client({ secret: process.env.FAUNA_KEY });

  try {
    await client.query(
      q.Create(q.Collection(`reactions_${process.env.NODE_ENV}`), {
        data: { title: title, slug: slug, reaction: reaction, date: date }
      })
    );
    res.status(200).json({ message: 'Lovely stuff, your reaction has been added!' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
}

Framework Improvements

We’ve made improvements to the core framework by adding a few new APIs too! The new Script API, available from 4.15.0, among other things, comes with an off-main-thread script loading strategy which can be used to offload third-party scripts (such as Google Analytics) using Builder.io ’s Partytown 🎉.

Offloading third-party scripts to a Web Worker is a nice way to speed up page loads. I wrote a little more about this on my site: How to use Gatsby’s Script API with Google Analytics.

We also have the new Head API. Historically speaking, the recommended way to add metadata to your HTML page with Gatsby was to use react-helmet and gatsby-plugin-react-helmet.

Not anymore; from release 4.19.0, this functionality is included in the framework. I’ve written a post detailing a common migration pattern if you’re interested to know more. How to use Gatsby’s Head API with MDX.

Stay tuned for Slices API 🍕. There’s an open RFC here on the Gatsby GitHub: RFC: Slices API.

Gatsby Cloud

The Gatsby framework is free and open source and can be deployed on any number of hosting providers. We have created Gatsby Cloud as a convenient way to streamline your developer experience, with no additional plugins or configuration required. Put simply: it’s the best place to build, preview, and deploy your Gatsby site.

Whilst many in the past have complained about Gatsby’s slow build speeds, I often ask, have you tried Gatsby Cloud?

Here are some build speed benchmarks for my site, which is currently ~110 pages. These are all .mdx with the exception of the dashboard, which, as mentioned, is Server-side rendered.

Many of these pages contain code block syntax highlighting, featured and embedded images, embedded Tweets, Code Sandboxes, and YouTube videos. All of this adds to build times, not to mention MDX taking a little longer to transform than good ol’ Markdown (.md).

Note: These results are from the free tier of Gatsby Cloud (running in Pro mode for the 14-day trial).

Screenshot of Gatsby Cloud interface displaying build times for three main scenarios when a static site needs to be rebuilt

Gatsby Cloud build times (Large preview)

From bottom to top, I’ll explain the results:

  1. Triggered by Gatsby Cloud: 03.22
    This is the first time I deployed, and the site is built from a cold cache.
  2. Triggered by a manual Build: 03.48
    This is a manual build, triggered by me, and is built from a cold cache.
  3. test: content change 1: 55s
    This build was triggered by a commit to GitHub after making a change to one of my posts and is built from a warm cache.

Cold cache builds usually take longer as Gatsby Cloud has nothing to intelligently compare “what’s changed.” However, when there is a cache and the brains behind Gatsby Cloud do their thing, the build speeds are great! Personally, as a hobbyist developer, I’m fine with waiting 55 seconds for my site to be built and deployed.

(Re) Introducing Gatsby, A Reactive Site Generator

If the above isn’t enough to prove Gatsby is a lot more than simply a Static Site Generator, have a read of Gatsby’s CTO’s recent post that describes how Gatsby takes advantage of a reactive approach to regenerating a “static site” when content changes occur: (Re-) Introducing Gatsby, A Reactive Site Generator.

TLDR; When a Gatsby 4 site is deployed to Netlify or Vercel, it can only behave as if it were an SSG. When deployed to Gatsby Cloud, it can behave as though it were an RSG, decreasing build speeds in static page re-generation by 100x!

In this video, Gatsby’s CTO Kyle Mathews demonstrates Gatsby Cloud reactively generating and then deploying a static page in ~2 seconds and all from the push of a single button, our CMS previews have been able to do something similar for a while but never before has it been this fast!

Gatsby has evolved quite dramatically in the last two years. If your experience is with Gatsby 2, you may be surprised at how much faster and more flexible it has become with new page rendering modes and capabilities like DSG and SSR, and we’ve got way more updates to come!

Original article sourced at: https://www.smashingmagazine.com

#Gatsby 

What’s New In Gatsby
田辺  亮介

田辺 亮介

1660571880

Gatsby的優缺點

現代問題需要現代解決方案。科技行業的企業和開發人員努力解決諸如網站加載時間差、網絡安全性不足、搜索引擎優化不足、用戶體驗未改善等許多問題。這些問題可能會導致生產力受挫。

由於對網站問題解決方案的需求,已經開發了幾種技術和框架。這些框架旨在為組織和開發人員解決問題並提高效率。

Gatsby是一個基於React的免費開源框架,程序員使用它來創建快速、靜態和持久的應用程序和網頁。

本文將檢查此框架的優點和缺點,以確定是否值得使用。

蓋茨比的優點

以下是採用 Gatsby 可以為開發人員和公司所有者提供的一些優勢。

出色的性能Gatsby 包括內置的預渲染資產,這些資產是為用戶到達做好準備的網站,這與在服務器上運行程序並告訴用戶瀏覽器生成什麼的其他框架不同。靜態資產由 Gatsby 創建,然後轉移到CDN,一個全球內容分發網絡。然後通過 CDN 從附近的服務器轉換網站的內容。結果,頁面加載時間急劇減少。網站的訪問者不必等待服務器的指示或響應。

SEO 有效性很難理解搜索引擎優化 (SEO) 的功能,但 Google 提供了一個標準列表,用於選擇哪個網站將出現在搜索結果的第一頁上。這些因素包括:

  • 核心網絡生命力
  • 內容質量;
  • 頁面元數據的有效使用;
  • 結構化數據;
  • 指向網站的反向鏈接數。

Gatsby 檢查了這些基本要素中的每一個以獲得最大的結果,提高其 SEO 效率,並且通過正確的配置,你很高興。

快速頁面加載速度快速頁面加載速度至關重要,因為跳出率取決於它。(離開網站而沒有訪問任何更多頁面的訪問者的百分比稱為跳出率。)因為您的頁面加載速度更快並且用戶在等待您的網站加載時不會延遲,他們將充分探索您的頁面謝謝到靜態文件渲染和漸進式圖片加載等內置功能。

安全性 網站安全性可能會出現一些問題。不良黑客希望能夠訪問託管服務、控製網站並利用它來謀取利益。由於 Gatsby 沒有服務器,因此對其發起攻擊將具有挑戰性。此外,由於它主要由專家使用,因此安全性錯誤較少。

可擴展性由於 Gatsby 能夠支持各種 API 和數據源,因此它被廣泛用於各種 Web 應用程序。它從多個來源收集信息,使其成為希望使用其網站集成與其業務線相關的其他應用程序的公司的理想選擇。他們可能會在其網站上顯示其業務績效和成果的可量化結果。

可訪問性Gatsby 為客戶提供了廣泛的工具來實現出色的可訪問性。儘管使用這些工具需要一定程度的實用性,但它們是開放的,可供所有人探索和使用。因此,開發人員無需添加任何插件或擴展,因為所有內容都已安裝。以下是 Gatsby 用於實現可訪問性的一些工具。

基於 React Gatsby 是 Facebook 開發的另一個框架,它是基於 React 構建的,正如我們在文章開頭提到的那樣。由於它在開發人員中的流行,React 擁有一個非常廣泛的社區,並且由於 Gatsby 是建立在它之上的,它可以訪問無窮無盡的資源來支持它的發展和維護,使其經得起未來的考驗。

Gatsby 遵循最新的 Web 標準和技術,例如GraphQLWebpack以及 React ,為您提供了最好的功能。

更大的可持續性支持技術必須經常更新以跟上 GatsbyJS 項目。由於這些修改,該站點可能會遇到一些小問題,但它們通常很容易修復。值得慶幸的是,這些升級不需要定期進行。相反,它們僅在啟動新的 Gatsby 版本時才需要。

頁面元數據Gatsby 讓您可以完全控製網站的佈局和內容。當頁面名稱、替代文本和元描述等元數據添加到網站時,搜索引擎可以解釋網站的內容並選擇何時在搜索結果中顯示它。結果,當執行谷歌搜索時,該網站出現在排名靠前的結果中。

Gatsby Cloud一個獨特的雲基礎設施被用於創建 Gatsby 站點。以下是它的一些好處:

  • 它提供實時 CMS 預覽調整。這消除了錯誤發佈內容更新的任何可能性。
  • 一個完整的網站的修改可以在包含在代碼中之前由程序員預覽。
  • 它提供了令人難以置信的快速增量構建。
  • 它提供 Lighthouse 報告,該功能使您能夠查看自動創建的有關站點性能、可訪問性和結果的正常信息。

蓋茨比的缺點

蓋茨比也有一些缺點。

構建時間隨著內容的增加,構建時間會增加用戶可能會覺得這很煩人,因為這會使他們移動得更慢。即使有對此的修復——Gatsby Cloud 提供了顯著縮短構建時間的增量構建——它也不是免費的,並且所做的任何更新都無法立即訪問。

缺少即插即用功能Gatsby 是一個用於創建網站並將其與其他平台(例如內容管理系統)集成的編程框架。沒有可用的圖形用戶界面。正因為如此,非技術用戶無法安裝 Gatsby 並立即開始使用它。在網站可以使用之前,必須完成規劃、設計和開發。對於只希望建立幾個網頁的小公司來說,這可能很困難。

了解新的 CMS從 WordPress 之類的框架切換到 Gatsby 的用戶可能會發現學習或理解新系統具有挑戰性,這會暫時降低工作效率。

The Need To Update Scripts 和 Google Tag Manager Gatsby 是一個單頁應用程序,因此,Google Analytics無法檢測到頁面何時有最近的瀏覽量。

為了糾正這一點,所有頁面都應該使用谷歌標籤管理器和谷歌分析以正確的順序設置。

優點缺點
出色的表現構建時間
搜索引擎優化效果缺少即插即用功能
頁面加載速度快了解新的 CMS
安全需要更新腳本
可擴展性需要更新 Google Tag Manager
可訪問性 
更大的可持續性 
頁面元數據 
蓋茨比雲 

蓋茨比的替代品

以下是一些出色的蓋茨比替代品:

結論

那麼蓋茨比值得嗎?我們一起討論了蓋茨比的優缺點。這是一個出色的框架,為開發人員和公司面臨的問題提供了許多解決方案。您應該能夠根據其優點和缺點來確定它是否最能滿足您的目標。我們希望這篇文章對您有所幫助!

鏈接:https ://blog.openreplay.com/is-gatsby-worth-using

#Gatsby

Gatsby的優缺點
Saul  Alaniz

Saul Alaniz

1659188940

Como Crear Un Tema En Gatsby Con Stitches

Gatsby es un marco React popular que se utiliza para crear páginas web y aplicaciones. Su diseño prioriza la seguridad, la escalabilidad y el rendimiento. Gatsby cuenta con el respaldo de un gran ecosistema, que incluye complementos para integrar servicios, temas para una configuración simple y recetas para automatizar tareas rutinarias. En este tutorial, aprenderá cómo crear un tema en Gatsby con Stitches.

Para comenzar con este tutorial, asegúrese de tener lo siguiente

  • Node.js versión 14 o posterior instalada
  • administrador de paquetes de hilo instalado.
  • Conocimiento previo de puntadas
  • Conocimiento previo de Gatsby

También asumimos que ha instalado la CLI de Gatsby en todo el mundo; hacer npm install -g gatsby-clisi no.

¿Qué es Puntadas?

Stitches es un marco de React que le permite crear y diseñar con confianza componentes reutilizables. Incluye soporte para otros marcos como Vue, Svelte y Vanilla HTML. Stitches se creó para ayudar a los desarrolladores a evitar interpolaciones de accesorios innecesarias en el tiempo de ejecución, mejorando el rendimiento de la aplicación. Comencemos por crear una nueva aplicación Gatsby.

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

El comando anterior clonará la aplicación de inicio Gatsby con la estructura de carpetas a continuación.

📦gatsby-site┣ 📂src ┃ ┗ 📂pages ┃ ┃ ┗ 📜index.js ┣ 📂static ┃ ┗ 📜favicon.ico ┣ 📜.gitignore ┣ 📜.prettierignore ┣ 📜.prettierrc ┣ 📜LICENSE ┣ 📜README.md ┣ 📜gatsby-config.js ┣ 📜package-lock.json ┗ 📜package.json

Instalación y configuración de puntadas

Ahora configuremos Stitches con su aplicación Gatsby. Primero, debe instalar el complemento Gatsby para diseñar con Stitches con el comando a continuación.

yarn add gatsby-theme-stitches @stitches/react

Una vez completada la instalación, abra el archivo gatsby-config.js y agregue Stitches a la matriz de complementos con el fragmento de código a continuación.

module.exports = {  /* Your site config here */  plugin: ['gatsby-theme-stitches'],}

En este punto, está listo para comenzar a diseñar su aplicación Gatsby con Stitches. Hay dos maneras de evitar esto.

  1. Puede elegir crear su configuración sombreando el gatsby-theme-stitches/src/configmódulo
  2. Puede importar las propiedades directamente a su aplicación.
import { styled } from 'gatsby-theme-stitches/src/config';

Para usar el primer método, cree un gatsby-theme-stitches/config.jsarchivo y agregue las siguientes configuraciones.

import { createStitches } from '@stitches/react';// You should export all propertiesexport const {  styled,  css,  globalCss,  keyframes,  getCssText,  theme,  createTheme,  config,} = createStitches({   theme: {    colors: {      black500: "hsl(0, 0%, 0%)",      white500: "hsl(0, 0%, 100%)",      gray500: "hsl(206,10%,76%)",      blue500: "hsl(206,100%,50%)",      purple500: "hsl(252,78%,60%)",      green500: "hsl(148,60%,60%)",      red500: "hsl(352,100%,62%)",    },    space: {      1: "5px",      2: "10px",      3: "15px",    },    fontSizes: {      1: "12px",      2: "13px",      3: "15px",    },    fonts: {      untitled: "Untitled Sans, apple-system, sans-serif",      mono: "Söhne Mono, menlo, monospace",    },    borderRadius: {      1: "5px",      2: "10px",      3: "15px",    },    borders: {      1: "1px solid #ccc",      2: "2px solid #ccc",      3: "3px solid #ccc",      4: "none",    },    paddings: {      1: "5px",      2: "10px",      3: "15px",    },    margins: {      1: "5px",      2: "10px",      3: "15px",    },    widths: {      1: "100%",      2: "50%",      3: "25%",    },  },});

En el fragmento de código anterior, ha exportado todas las propiedades de puntadas disponibles, por lo que puede importarlas y usarlas. Luego, definimos los temas para los elementos de nuestra aplicación y usaremos las propiedades del tema para diseñar nuestros elementos.

Crear y diseñar elementos personalizados.

Avancemos y usemos Puntadas para crear el estilo de los elementos que usaremos en nuestra aplicación Gatsby. Para separar las preocupaciones, crearemos una carpeta de componentes en el directorio raíz del proyecto para todos los estilos del elemento. Cree un nuevo archivo con el nombre Button.jsen la carpeta del componente y agregue los fragmentos de código a continuación.

import { styled } from '../../stitches.config';export const Button = styled("button", {   // base styles  display: "block",  border: "$4",  borderRadius: "$1",  color: "$white500",  variants: {    size: {      sm: {        fontSize: "13px",        height: "25px",        paddingRight: "10px",        paddingLeft: "10px",      },      lg: {        fontSize: "15px",        height: "35px",        paddingLeft: "15px",        paddingRight: "15px",      },    },    bg: {      primary: {        backgroundColor: "#2196f3",        "&:hover": {          backgroundColor: "#64b5f6",        },      },      secondary: {        backgroundColor: "#009688",        "&:hover": {          backgroundColor: "#4db6ac",        },      },      danger: {        backgroundColor: "#f44336",        "&:hover": {          backgroundColor: "#ef9a9a",        },      },      success: {        backgroundColor: "#4caf50",        color: "white",        "&:hover": {          backgroundColor: "#a5d6a7",        },      },    },  },});

En el fragmento de código anterior, importamos las propiedades con estilo del archivo de configuración de Stitches, lo que nos permite personalizar el componente. Usamos las propiedades que definimos en nuestro tema para agregar el estilo base del elemento usando el símbolo $ seguido de las propiedades del tema. Luego usamos la propiedad variantes para definir el estilo del color de fondo (bg) y el tamaño (size) del componente. A continuación, cree un Container.jsy agregue los fragmentos de código a continuación.

import { styled } from "@stitches/react";export const Container = styled("div", {   // base styles  display: "flex",  flexDirection: "column",  justifyContent: "center",  padding: "$2",  backgroundColor: "$white500",  variants: {    fd: {      column: {        flexDirection: "column",      },      row: {        flexDirection: "row",      },    },    size: {      sm: {        width: "100%",        height: "50px",      },      lg: {        width: "100%",        height: "60px",      },    },    align: {      center: {        alignItems: "center",      },      left: {        alignItems: "flex-start",      },      right: {        alignItems: "flex-end",      },    },  },});

En el componente Container, basamos los temas de estilo y definimos el estilo para alinear y establecer el tamaño del contenedor usando la propiedad variant. A continuación, cree un Image.jsarchivo y agregue el fragmento de código a continuación.

import { styled } from "@stitches/react"export const Image = styled("img", {  display: "block",  width: "$1",  height: "auto",  maxWidth: "100%",  maxHeight: "100%",  margin: "0 auto",  variants: {    size: {      sm: {        width: "50%",        height: "50%",        maxWidth: "100%",        maxHeight: "100%",        margin: "0 auto",      },      lg: {        width: "100%",        height: "auto",        maxWidth: "100%",        maxHeight: "100%",        margin: "0 auto",      },    },  },})

También definimos el estilo para tener una imagen grande y pequeña, el estilo para cambiar la alineación de la imagen y los temas se aplicaron a los estilos base. A continuación, cree un Header.jsarchivo y agregue el fragmento de código a continuación.

import { styled } from "@stitches/react";export const Header = styled("nav", {  // base styles  display: "flex",  flexDirection: "row",  justifyContent: "space-between",  alignItems: "center",  padding: "$2",  backgroundColor: "$white500",  borderBottom: "1px solid #e6e6e6",   variants: {    size: {      sm: {        width: "100%",        height: "50px",      },      lg: {        width: "100%",        height: "60px",      },    },    bg: {      primary: {        backgroundColor: "#2196f3",        "&:hover": {          backgroundColor: "#64b5f6",        },      },      secondary: {        backgroundColor: "#009688",        "&:hover": {          backgroundColor: "#4db6ac",        },      },      danger: {        backgroundColor: "#f44336",        "&:hover": {          backgroundColor: "#ef9a9a",        },      },      success: {        backgroundColor: "#4caf50",        "&:hover": {          backgroundColor: "#a5d6a7",        },      },    },  },});

A continuación, cree un Card.jsarchivo y agregue los fragmentos de código a continuación.

import { styled } from "@stitches/react";export const Card = styled("div", {  display: "flex",  justifyContent: "center",  flexDirection: "column",  padding: "$1",  margin: "$2"  variants: {    align: {      center: {        alignItems: "center",      },      left: {        alignItems: "flex-start",      },      right: {        alignItems: "flex-end",      },    },    boder: {        none: {             border: "none"        },        solid: {            border: "solid 1px #e6e6e6"        }    }  },});

A continuación, agregue un nuevo archivo, Input.js, con el fragmento de código a continuación.

import { styled } from "@stitches/react";export const Input = styled("input", {  display: "block",  marginBottom: "10px",  variants: {    size: {      sm: {        fontSize: "13px",        height: "25px",        paddingRight: "10px",        paddingLeft: "10px",      },      lg: {        fontSize: "15px",        height: "35px",        paddingLeft: "15px",        paddingRight: "15px",      },    },  },});

El fragmento de código anterior tiene un elemento de entrada para manejar la entrada de los usuarios. En el componente de entrada anterior, queremos entradas grandes y pequeñas, y definimos los estilos para eso usando la propiedad de variantes. A continuación, agregue un nuevo archivo, Text.jsy agregue el fragmento de código a continuación.

import { styled } from "@stitches/react";export const Text = styled('p', {    fontFamily: '$mono',    color: '$black5000',      variants: {      size: {        1: {          fontSize: '10px',        },        2: {          fontSize: '12px',        },        3: {          fontSize: '14px',        },      },    },  });

En el fragmento de código anterior, creamos un componente que nos permite agregar y diseñar un párrafo.

Creación de una aplicación de blog

Ahora que hemos diseñado los elementos que necesitamos para esta aplicación, sigamos adelante y creemos un blog. Primero, necesitamos actualizar el pages/index.jsarchivo para importar todos los componentes que acabamos de crear con el fragmento de código a continuación.

import { Button } from "../components/Button"import { Input } from "../components/Input"import { Card } from "../components/Card"import { Text } from "../components/Text"import { Header } from "../components/Header"import { Image } from "../components/Image"import { Container } from "../components/Container"

A continuación, usaremos el componente para actualizar el componente Inicio con el fragmento de código a continuación.

export default function Home() {  const [modal, setModal] = useState(false)  const showModal = () => {    setModel(!model)  }  return (    <>      <Container>        <Header bg="primary">          <Text size="1">My Blog App</Text>          <Button bg="secondary" size="sm" onClick={showModal}>            New Blog          </Button>        </Header>        {model && (          <Card boder="solid">            <Text size="1">Titile:</Text>            <Input />            <Text size="1">Content</Text>            <Input />            <Text size="1">Cover Image</Text>            <Input />            <Button bg="primary" size="sm">              Post            </Button>          </Card>        )}        <Text>Blog Posts</Text>      </Container>      <Container fd="row">        {blogs.map(blog => (          <Card boder="solid">            <Image src={blog.cover} size="lg" />            <Text size="3">{blog.title}</Text>            <Text size="1">{blog.content}</Text>            <Text size="1">{blog.date}</Text>          </Card>        ))}      </Container>    </>  )}

En el fragmento de código anterior, actualizamos el componente Inicio usando los componentes que diseñamos usando Puntadas. Aplicamos los estilos que queríamos a cada componente utilizado en nuestro componente Inicio. Tenemos un campo de entrada de formulario que se alternará para ocultarlo o mostrarlo usando la variable de estado Modal . Luego repasamos los detalles del blog que crearemos en breve usando la función de mapa y se los mostramos al usuario.

Finalmente, agregue los siguientes objetos de matriz de blog al componente Inicio .

...  const blogs = [    {      title: "How to build a website",      content:        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",      cover:        "https://www.hostgator.com/blog/wp-content/uploads/2017/09/MakeOwnWebsite.png",      date: "2020-01-01",    },    {      title: "Getting started with OpenReplay",      content:      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",      cover:        "https://opengraph.githubassets.com/2ddbe84dccfbcc774b1c9861dd327d2efd7e1cd49964dc01229c181bea751e60/openreplay/documentation",      date: "2020-01-01",    },    {      title: "Node.js Vs React",      content:      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",      cover:        "https://miro.medium.com/max/1400/1*CpDidbInbG4Er_0j_hknFQ.jpeg",      date: "2020-01-01",    },  ]...

Probar la aplicación

Con la aplicación de demostración del blog creada, sigamos adelante y pruébela. Ejecute los comandos para cambiar el directorio a la carpeta del proyecto e inicie la aplicación.

cd gatsby-sitegatsby develop

Luego navegue a http://localhost:8000/, y debería ver el resultado a continuación en la página de índice.

primero

Conclusión

Al crear una aplicación de demostración de blog, aprendió cómo crear una interfaz de usuario de tema en una aplicación Gatsby con Stitches. Primero, comenzamos con una introducción a Gatsby y Stitches, y aprendiste a configurar Stitches con Gatsby y diseñar algunos componentes. Ahora que sabe cómo integrar Gatsby y Stitches, ¿cómo diseñaría su próxima aplicación de Gatsby?

Fuente: https://blog.openreplay.com/creating-a-theme-in-a-gatsby-application-with-stitches

 #Gatsby #stitches 

Como Crear Un Tema En Gatsby Con Stitches
Rui  Silva

Rui Silva

1659188580

Como Criar Um Tema Em Gatsby Com Pontos

Gatsby é um framework React popular usado para construir páginas da web e aplicativos. Seu design prioriza segurança, escalabilidade e desempenho. O Gatsby é suportado por um grande ecossistema, que inclui Plugins para integração de serviços, temas para configuração simples e Receitas para automatizar tarefas rotineiras. Neste tutorial, você aprenderá como criar um tema no Gatsby com Stitches.

Para começar com este tutorial, certifique-se de ter o seguinte

  • Node.js versão 14 ou posterior instalado
  • gerenciador de pacotes yarn instalado.
  • Conhecimento prévio de pontos
  • Conhecimento prévio de Gatsby

Também assumimos que você instalou a CLI do Gatsby globalmente; faça npm install -g gatsby-clise não.

O que é Pontos?

Stitches é um framework React que permite que você crie e estilize componentes reutilizáveis ​​com confiança. Inclui suporte para outros frameworks como Vue, Svelte e Vanilla HTML. Stitches foi criado para ajudar os desenvolvedores a evitar interpolações de prop desnecessárias em tempo de execução, melhorando o desempenho do aplicativo. Vamos começar criando um novo aplicativo Gatsby.

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

O comando acima clonará o aplicativo inicial do Gatsby com a estrutura de pastas abaixo.

📦gatsby-site
┣ 📂src
 ┃ ┗ 📂pages
 ┃ ┃ ┗ 📜index.js
 ┣ 📂static
 ┃ ┗ 📜favicon.ico
 ┣ 📜.gitignore
 ┣ 📜.prettierignore
 ┣ 📜.prettierrc
 ┣ 📜LICENSE
 ┣ 📜README.md
 ┣ 📜gatsby-config.js
 ┣ 📜package-lock.json
 ┗ 📜package.json

Configurar e configurar pontos

Agora vamos configurar Stitches com seu aplicativo Gatsby. Primeiro, você deve instalar o plugin Gatsby para estilizar com Stitches com o comando abaixo.

yarn add gatsby-theme-stitches @stitches/react

Quando a instalação estiver concluída, abra o arquivo gatsby-config.js e adicione Stitches ao array de plugins com o snippet de código abaixo.

module.exports = {
  /* Your site config here */
  plugin: ['gatsby-theme-stitches'],
}

Neste ponto, você está pronto para começar a estilizar seu aplicativo Gatsby com Stitches. Existem duas maneiras de contornar isso.

  1. Você pode optar por criar sua configuração sombreando o gatsby-theme-stitches/src/configmódulo
  2. Você pode importar as propriedades diretamente em seu aplicativo.
import { styled } from 'gatsby-theme-stitches/src/config';

Para usar o primeiro método, crie um gatsby-theme-stitches/config.jsarquivo e adicione as seguintes configurações.

import { createStitches } from '@stitches/react';

// You should export all properties
export const {
  styled,
  css,
  globalCss,
  keyframes,
  getCssText,
  theme,
  createTheme,
  config,
} = createStitches({
   theme: {
    colors: {
      black500: "hsl(0, 0%, 0%)",
      white500: "hsl(0, 0%, 100%)",
      gray500: "hsl(206,10%,76%)",
      blue500: "hsl(206,100%,50%)",
      purple500: "hsl(252,78%,60%)",
      green500: "hsl(148,60%,60%)",
      red500: "hsl(352,100%,62%)",
    },
    space: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    fontSizes: {
      1: "12px",
      2: "13px",
      3: "15px",
    },
    fonts: {
      untitled: "Untitled Sans, apple-system, sans-serif",
      mono: "Söhne Mono, menlo, monospace",
    },
    borderRadius: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    borders: {
      1: "1px solid #ccc",
      2: "2px solid #ccc",
      3: "3px solid #ccc",
      4: "none",
    },
    paddings: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    margins: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    widths: {
      1: "100%",
      2: "50%",
      3: "25%",
    },
  },
});

No trecho de código acima, você exportou todas as propriedades Stitches disponíveis, para poder importá-las e usá-las. Em seguida, definimos os temas para os elementos em nosso aplicativo e usaremos as propriedades do tema para estilizar nossos elementos.

Crie e estilize elementos personalizados.

Vamos em frente e usar Stitches para criar o estilo para os elementos que usaremos em nosso aplicativo Gatsby. Para fins de separação de interesses, criaremos uma pasta de componentes no diretório raiz do projeto para todos os estilos do elemento. Crie um novo arquivo chamado Button.jsna pasta do componente e adicione os trechos de código abaixo.

import { styled } from '../../stitches.config';

export const Button = styled("button", {
   // base styles
  display: "block",
  border: "$4",
  borderRadius: "$1",
  color: "$white500",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        color: "white",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

No trecho de código acima, importamos as propriedades de estilo do arquivo de configuração Stitches, permitindo personalizar o componente. Usamos as propriedades que definimos em nosso tema para adicionar o estilo base do elemento usando o símbolo $ seguido pelas propriedades do tema. Em seguida, usamos a propriedade de variantes para definir o estilo da cor de fundo (bg) e tamanho (tamanho) do componente. Em seguida, crie um Container.jse adicione os trechos de código abaixo.

import { styled } from "@stitches/react";

export const Container = styled("div", {
   // base styles
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  padding: "$2",
  backgroundColor: "$white500",

  variants: {
    fd: {
      column: {
        flexDirection: "column",
      },
      row: {
        flexDirection: "row",
      },
    },
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
  },
});

No componente Container, baseamos os temas de estilo e definimos o estilo para alinhar e definir o tamanho do container usando a propriedade variante. Em seguida, crie um Image.jsarquivo e adicione o snippet de código abaixo.

import { styled } from "@stitches/react"

export const Image = styled("img", {
  display: "block",
  width: "$1",
  height: "auto",
  maxWidth: "100%",
  maxHeight: "100%",
  margin: "0 auto",
  variants: {
    size: {
      sm: {
        width: "50%",
        height: "50%",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
      lg: {
        width: "100%",
        height: "auto",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
    },
  },
})

Também definimos o estilo para ter uma imagem grande e pequena, o estilo para alterar o alinhamento da imagem e os temas foram aplicados aos estilos base. Em seguida, crie um Header.jsarquivo e adicione o snippet de código abaixo.

import { styled } from "@stitches/react";

export const Header = styled("nav", {
  // base styles
  display: "flex",
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
  padding: "$2",
  backgroundColor: "$white500",
  borderBottom: "1px solid #e6e6e6",
 
  variants: {
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

Em seguida, crie um Card.jsarquivo e adicione os trechos de código abaixo.

import { styled } from "@stitches/react";

export const Card = styled("div", {
  display: "flex",
  justifyContent: "center",
  flexDirection: "column",
  padding: "$1",
  margin: "$2"

  variants: {
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
    boder: {
        none: { 
            border: "none"
        },
        solid: {
            border: "solid 1px #e6e6e6"
        }
    }
  },
});

Em seguida, adicione um novo arquivo, Input.js, com o snippet de código abaixo.

import { styled } from "@stitches/react";

export const Input = styled("input", {
  display: "block",
  marginBottom: "10px",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
  },
});

O trecho de código acima tem um elemento de entrada para lidar com a entrada dos usuários. No componente de entrada acima, queremos entradas grandes e pequenas, e definimos os estilos para isso usando a propriedade de variantes. Em seguida, adicione um novo arquivo, Text.jse adicione o snippet de código abaixo.

import { styled } from "@stitches/react";

export const Text = styled('p', {
    fontFamily: '$mono',
    color: '$black5000',
  
    variants: {
      size: {
        1: {
          fontSize: '10px',
        },
        2: {
          fontSize: '12px',
        },
        3: {
          fontSize: '14px',
        },
      },
    },
  });

No trecho de código acima, criamos um componente que nos permite adicionar e estilizar um parágrafo.

Criando aplicativo de blog

Agora que estilizamos os elementos necessários para este aplicativo, vamos em frente e criar um blog. Primeiro, precisamos atualizar o pages/index.jsarquivo para importar todos os componentes que acabamos de criar com o trecho de código abaixo.

import { Button } from "../components/Button"
import { Input } from "../components/Input"
import { Card } from "../components/Card"
import { Text } from "../components/Text"
import { Header } from "../components/Header"
import { Image } from "../components/Image"
import { Container } from "../components/Container"

Em seguida, usaremos o componente para atualizar o componente Home com o snippet de código abaixo.

export default function Home() {
  const [modal, setModal] = useState(false)

  const showModal = () => {
    setModel(!model)
  }
  return (
    <>
      <Container>
        <Header bg="primary">
          <Text size="1">My Blog App</Text>
          <Button bg="secondary" size="sm" onClick={showModal}>
            New Blog
          </Button>
        </Header>
        {model && (
          <Card boder="solid">
            <Text size="1">Titile:</Text>
            <Input />
            <Text size="1">Content</Text>
            <Input />
            <Text size="1">Cover Image</Text>
            <Input />
            <Button bg="primary" size="sm">
              Post
            </Button>
          </Card>
        )}
        <Text>Blog Posts</Text>
      </Container>
      <Container fd="row">
        {blogs.map(blog => (
          <Card boder="solid">
            <Image src={blog.cover} size="lg" />
            <Text size="3">{blog.title}</Text>
            <Text size="1">{blog.content}</Text>
            <Text size="1">{blog.date}</Text>
          </Card>
        ))}
      </Container>
    </>
  )
}

No trecho de código acima, atualizamos o componente Home usando os componentes que estilizamos usando Stitches. Aplicamos os estilos que queríamos a cada componente usado em nosso componente Home. Temos um campo de entrada de formulário que será alternado para ocultá-lo ou mostrá-lo usando a variável de estado Modal . Em seguida, percorremos os detalhes do blog que criaremos em breve usando a função map e os renderizamos para o usuário.

Por fim, adicione os seguintes objetos de matriz de blog ao componente Home .

...
  const blogs = [
    {
      title: "How to build a website",
      content:
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://www.hostgator.com/blog/wp-content/uploads/2017/09/MakeOwnWebsite.png",
      date: "2020-01-01",
    },
    {
      title: "Getting started with OpenReplay",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://opengraph.githubassets.com/2ddbe84dccfbcc774b1c9861dd327d2efd7e1cd49964dc01229c181bea751e60/openreplay/documentation",
      date: "2020-01-01",
    },
    {
      title: "Node.js Vs React",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://miro.medium.com/max/1400/1*CpDidbInbG4Er_0j_hknFQ.jpeg",
      date: "2020-01-01",
    },
  ]
...

Teste o aplicativo

Com o aplicativo de demonstração do blog criado, vamos em frente e testá-lo. Execute os comandos para alterar o diretório para a pasta do projeto e iniciar o aplicativo.

cd gatsby-site
gatsby develop

Em seguida, navegue até http://localhost:8000/ e você deverá ver a saída abaixo na página de índice.

primeiro

Conclusão

Ao criar um aplicativo de demonstração de blog, você aprendeu como criar uma interface do usuário de tema em um aplicativo Gatsby com Stitches. Primeiro, começamos com uma introdução ao Gatsby e Stitches, e você aprendeu como configurar Stitches com Gatsby e estilizar alguns componentes. Agora que você sabe como integrar Gatsby e Stitches, como você estilizaria seu próximo aplicativo Gatsby?

Fonte: https://blog.openreplay.com/creating-a-theme-in-a-gatsby-application-with-stitches

#Gatsby #stitches 

Como Criar Um Tema Em Gatsby Com Pontos

Comment Créer Un Thème Dans Gatsby Avec Stitches

Gatsby est un framework React populaire utilisé pour créer des pages Web et des applications. Sa conception donne la priorité à la sécurité, à l'évolutivité et aux performances. Gatsby est pris en charge par un vaste écosystème, qui comprend des plugins pour l'intégration de services, des thèmes pour une configuration simple et des recettes pour automatiser les tâches de routine. Dans ce didacticiel, vous apprendrez à créer un thème dans Gatsby avec Stitches.

Pour commencer avec ce didacticiel, assurez-vous d'avoir les éléments suivants

  • Node.js version 14 ou ultérieure installé
  • gestionnaire de paquets de fils installé.
  • Connaissance préalable des points de suture
  • Connaissance préalable de Gatsby

Nous supposons également que vous avez installé la CLI de Gatsby globalement ; faire npm install -g gatsby-clisinon.

Qu'est-ce que Stitches ?

Stitches est un framework React qui vous permet de créer et de styliser en toute confiance des composants réutilisables. Il inclut la prise en charge d'autres frameworks tels que Vue, Svelte et Vanilla HTML. Stitches a été créé pour aider les développeurs à éviter les interpolations d'accessoires inutiles lors de l'exécution, améliorant ainsi les performances de l'application. Commençons par créer une nouvelle application Gatsby.

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

La commande ci-dessus clonera l'application de démarrage Gatsby avec la structure de dossiers ci-dessous.

📦gatsby-site
┣ 📂src
 ┃ ┗ 📂pages
 ┃ ┃ ┗ 📜index.js
 ┣ 📂static
 ┃ ┗ 📜favicon.ico
 ┣ 📜.gitignore
 ┣ 📜.prettierignore
 ┣ 📜.prettierrc
 ┣ 📜LICENSE
 ┣ 📜README.md
 ┣ 📜gatsby-config.js
 ┣ 📜package-lock.json
 ┗ 📜package.json

Installation et configuration des points

Configurons maintenant Stitches avec votre application Gatsby. Tout d'abord, vous devez installer le plugin Gatsby pour le style avec Stitches avec la commande ci-dessous.

yarn add gatsby-theme-stitches @stitches/react

Une fois l'installation terminée, ouvrez le fichier gatsby-config.js et ajoutez Stitches au tableau de plugins avec l'extrait de code ci-dessous.

module.exports = {
  /* Your site config here */
  plugin: ['gatsby-theme-stitches'],
}

À ce stade, vous êtes prêt à commencer à styliser votre application Gatsby avec Stitches. Il y a deux façons de contourner cela.

  1. Vous pouvez choisir de créer votre config en shadowant le gatsby-theme-stitches/src/configmodule
  2. Vous pouvez importer les propriétés directement dans votre application.
import { styled } from 'gatsby-theme-stitches/src/config';

Pour utiliser la première méthode, créez un gatsby-theme-stitches/config.jsfichier et ajoutez les configurations suivantes.

import { createStitches } from '@stitches/react';

// You should export all properties
export const {
  styled,
  css,
  globalCss,
  keyframes,
  getCssText,
  theme,
  createTheme,
  config,
} = createStitches({
   theme: {
    colors: {
      black500: "hsl(0, 0%, 0%)",
      white500: "hsl(0, 0%, 100%)",
      gray500: "hsl(206,10%,76%)",
      blue500: "hsl(206,100%,50%)",
      purple500: "hsl(252,78%,60%)",
      green500: "hsl(148,60%,60%)",
      red500: "hsl(352,100%,62%)",
    },
    space: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    fontSizes: {
      1: "12px",
      2: "13px",
      3: "15px",
    },
    fonts: {
      untitled: "Untitled Sans, apple-system, sans-serif",
      mono: "Söhne Mono, menlo, monospace",
    },
    borderRadius: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    borders: {
      1: "1px solid #ccc",
      2: "2px solid #ccc",
      3: "3px solid #ccc",
      4: "none",
    },
    paddings: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    margins: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    widths: {
      1: "100%",
      2: "50%",
      3: "25%",
    },
  },
});

Dans l'extrait de code ci-dessus, vous avez exporté toutes les propriétés Stitches disponibles, vous pouvez donc les importer et les utiliser. Ensuite, nous avons défini les thèmes des éléments de notre application et nous utiliserons les propriétés du thème pour styliser nos éléments.

Créez et stylisez des éléments personnalisés.

Allons-y et utilisons Stitches pour créer le style des éléments que nous utiliserons dans notre application Gatsby. Par souci de séparation, nous allons créer un dossier de composants dans le répertoire racine du projet pour tous les styles d'élément. Créez un nouveau fichier nommé Button.jsdans le dossier du composant et ajoutez les extraits de code ci-dessous.

import { styled } from '../../stitches.config';

export const Button = styled("button", {
   // base styles
  display: "block",
  border: "$4",
  borderRadius: "$1",
  color: "$white500",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        color: "white",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

Dans l'extrait de code ci-dessus, nous avons importé les propriétés de style à partir du fichier de configuration Stitches, ce qui nous permet de personnaliser le composant. Nous avons utilisé les propriétés que nous avons définies dans notre thème pour ajouter le style de base de l'élément en utilisant le symbole $ suivi des propriétés du thème. Ensuite, nous avons utilisé la propriété variants pour définir le style de la couleur d'arrière-plan (bg) et de la taille (size) du composant. Ensuite, créez un Container.jset ajoutez les extraits de code ci-dessous.

import { styled } from "@stitches/react";

export const Container = styled("div", {
   // base styles
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  padding: "$2",
  backgroundColor: "$white500",

  variants: {
    fd: {
      column: {
        flexDirection: "column",
      },
      row: {
        flexDirection: "row",
      },
    },
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
  },
});

Dans le composant Container, nous basons les thèmes de style et définissons le style pour aligner et définir la taille du conteneur à l'aide de la propriété variant. Ensuite, créez un Image.jsfichier et ajoutez l'extrait de code ci-dessous.

import { styled } from "@stitches/react"

export const Image = styled("img", {
  display: "block",
  width: "$1",
  height: "auto",
  maxWidth: "100%",
  maxHeight: "100%",
  margin: "0 auto",
  variants: {
    size: {
      sm: {
        width: "50%",
        height: "50%",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
      lg: {
        width: "100%",
        height: "auto",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
    },
  },
})

Nous avons également défini le style pour avoir une grande et une petite image, le style pour modifier l'alignement de l'image et les thèmes ont été appliqués aux styles de base. Ensuite, créez un Header.jsfichier et ajoutez l'extrait de code ci-dessous.

import { styled } from "@stitches/react";

export const Header = styled("nav", {
  // base styles
  display: "flex",
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
  padding: "$2",
  backgroundColor: "$white500",
  borderBottom: "1px solid #e6e6e6",
 
  variants: {
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

Ensuite, créez un Card.jsfichier et ajoutez les extraits de code ci-dessous.

import { styled } from "@stitches/react";

export const Card = styled("div", {
  display: "flex",
  justifyContent: "center",
  flexDirection: "column",
  padding: "$1",
  margin: "$2"

  variants: {
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
    boder: {
        none: { 
            border: "none"
        },
        solid: {
            border: "solid 1px #e6e6e6"
        }
    }
  },
});

Ensuite, ajoutez un nouveau fichier, Input.js, avec l'extrait de code ci-dessous.

import { styled } from "@stitches/react";

export const Input = styled("input", {
  display: "block",
  marginBottom: "10px",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
  },
});

L'extrait de code ci-dessus a un élément Input pour gérer les entrées des utilisateurs. Dans le composant Input ci-dessus, nous voulons des entrées grandes et petites, et nous avons défini les styles pour cela en utilisant la propriété variants. Ensuite, ajoutez un nouveau fichier, Text.js, et ajoutez l'extrait de code ci-dessous.

import { styled } from "@stitches/react";

export const Text = styled('p', {
    fontFamily: '$mono',
    color: '$black5000',
  
    variants: {
      size: {
        1: {
          fontSize: '10px',
        },
        2: {
          fontSize: '12px',
        },
        3: {
          fontSize: '14px',
        },
      },
    },
  });

Dans l'extrait de code ci-dessus, nous avons créé un composant pour nous permettre d'ajouter et de styliser un paragraphe.

Création d'une application de blog

Maintenant que nous avons stylisé les éléments dont nous avons besoin pour cette application, allons-y et créons un blog. Tout d'abord, nous devons mettre à jour le pages/index.jsfichier pour importer tous les composants que nous venons de créer avec l'extrait de code ci-dessous.

import { Button } from "../components/Button"
import { Input } from "../components/Input"
import { Card } from "../components/Card"
import { Text } from "../components/Text"
import { Header } from "../components/Header"
import { Image } from "../components/Image"
import { Container } from "../components/Container"

Ensuite, nous utiliserons le composant pour mettre à jour le composant Home avec l'extrait de code ci-dessous.

export default function Home() {
  const [modal, setModal] = useState(false)

  const showModal = () => {
    setModel(!model)
  }
  return (
    <>
      <Container>
        <Header bg="primary">
          <Text size="1">My Blog App</Text>
          <Button bg="secondary" size="sm" onClick={showModal}>
            New Blog
          </Button>
        </Header>
        {model && (
          <Card boder="solid">
            <Text size="1">Titile:</Text>
            <Input />
            <Text size="1">Content</Text>
            <Input />
            <Text size="1">Cover Image</Text>
            <Input />
            <Button bg="primary" size="sm">
              Post
            </Button>
          </Card>
        )}
        <Text>Blog Posts</Text>
      </Container>
      <Container fd="row">
        {blogs.map(blog => (
          <Card boder="solid">
            <Image src={blog.cover} size="lg" />
            <Text size="3">{blog.title}</Text>
            <Text size="1">{blog.content}</Text>
            <Text size="1">{blog.date}</Text>
          </Card>
        ))}
      </Container>
    </>
  )
}

Dans l'extrait de code ci-dessus, nous avons mis à jour le composant Home en utilisant les composants que nous avons stylisés à l'aide de Stitches. Nous avons appliqué les styles que nous voulions à chaque composant utilisé dans notre composant Home. Nous avons un champ de saisie de formulaire qui sera basculé pour le masquer ou l'afficher à l'aide de la variable d'état modal . Ensuite, nous avons parcouru les détails du blog que nous allons créer sous peu à l'aide de la fonction de carte et les avons rendus à l'utilisateur.

Enfin, ajoutez les objets de tableau de blog suivants au composant Accueil .

...
  const blogs = [
    {
      title: "How to build a website",
      content:
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://www.hostgator.com/blog/wp-content/uploads/2017/09/MakeOwnWebsite.png",
      date: "2020-01-01",
    },
    {
      title: "Getting started with OpenReplay",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://opengraph.githubassets.com/2ddbe84dccfbcc774b1c9861dd327d2efd7e1cd49964dc01229c181bea751e60/openreplay/documentation",
      date: "2020-01-01",
    },
    {
      title: "Node.js Vs React",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://miro.medium.com/max/1400/1*CpDidbInbG4Er_0j_hknFQ.jpeg",
      date: "2020-01-01",
    },
  ]
...

Testez l'application

Une fois l'application de démonstration de blog créée, allons-y et testons-la. Exécutez les commandes pour modifier le répertoire dans le dossier du projet et démarrer l'application.

cd gatsby-site
gatsby develop

Accédez ensuite à http://localhost:8000/ et vous devriez voir la sortie ci-dessous sur la page d'index.

1

Conclusion

En créant une application de démonstration de blog, vous avez appris à créer une interface utilisateur thématique dans une application Gatsby avec Stitches. Tout d'abord, nous avons commencé par une introduction à Gatsby et Stitches, et vous avez appris à configurer Stitches avec Gatsby et à styliser certains composants. Maintenant que vous savez comment intégrer Gatsby et Stitches, comment styliseriez-vous votre prochaine application Gatsby ?

Source : https://blog.openreplay.com/creating-a-theme-in-a-gatsby-application-with-stitches

 #Gatsby #stitches 

Comment Créer Un Thème Dans Gatsby Avec Stitches
曾 俊

曾 俊

1659182400

如何在 Gatsby 中使用 Stitches 创建主题

Gatsby是一个流行的 React 框架,用于构建网页和应用程序。它的设计优先考虑安全性、可扩展性和性能。Gatsby 由一个大型生态系统支持,其中包括用于集成服务的插件、用于简单配置的主题以及用于自动化日常任务的食谱。在本教程中,您将学习如何在 Gatsby 中使用 Stitches 创建主题。

要开始使用本教程,请确保您具备以下条件

我们还假设您已经全局安装了 Gatsby 的 CLI;如果没有就做npm install -g gatsby-cli

什么是针脚?

Stitches是一个 React 框架,可让您自信地创建和设置可重用组件的样式。它包括对其他框架的支持,例如 Vue、Svelte 和 Vanilla HTML。创建 Stitches 是为了帮助开发人员在运行时避免不必要的道具插值,从而提高应用程序性能。让我们从创建一个新的 Gatsby 应用程序开始。

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

上述命令将克隆具有以下文件夹结构的 Gatsby 入门应用程序。

📦gatsby-site
┣ 📂src
 ┃ ┗ 📂pages
 ┃ ┃ ┗ 📜index.js
 ┣ 📂static
 ┃ ┗ 📜favicon.ico
 ┣ 📜.gitignore
 ┣ 📜.prettierignore
 ┣ 📜.prettierrc
 ┣ 📜LICENSE
 ┣ 📜README.md
 ┣ 📜gatsby-config.js
 ┣ 📜package-lock.json
 ┗ 📜package.json

设置和配置针迹

现在让我们使用您的 Gatsby 应用程序配置 Stitches。首先,您必须使用以下命令安装 Gatsby 插件以使用 Stitches 进行样式设置。

yarn add gatsby-theme-stitches @stitches/react

安装完成后,打开 gatsby-config.js 文件并使用下面的代码片段将 Stitches 添加到插件数组中。

module.exports = {
  /* Your site config here */
  plugin: ['gatsby-theme-stitches'],
}

此时,您已准备好开始使用 Stitches 设置 Gatsby 应用程序的样式。有两种方法可以解决这个问题。

  1. 您可以选择通过隐藏gatsby-theme-stitches/src/config模块来创建配置
  2. 您可以将属性直接导入您的应用程序。
import { styled } from 'gatsby-theme-stitches/src/config';

要使用第一种方法,请创建一个gatsby-theme-stitches/config.js文件并添加以下配置。

import { createStitches } from '@stitches/react';

// You should export all properties
export const {
  styled,
  css,
  globalCss,
  keyframes,
  getCssText,
  theme,
  createTheme,
  config,
} = createStitches({
   theme: {
    colors: {
      black500: "hsl(0, 0%, 0%)",
      white500: "hsl(0, 0%, 100%)",
      gray500: "hsl(206,10%,76%)",
      blue500: "hsl(206,100%,50%)",
      purple500: "hsl(252,78%,60%)",
      green500: "hsl(148,60%,60%)",
      red500: "hsl(352,100%,62%)",
    },
    space: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    fontSizes: {
      1: "12px",
      2: "13px",
      3: "15px",
    },
    fonts: {
      untitled: "Untitled Sans, apple-system, sans-serif",
      mono: "Söhne Mono, menlo, monospace",
    },
    borderRadius: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    borders: {
      1: "1px solid #ccc",
      2: "2px solid #ccc",
      3: "3px solid #ccc",
      4: "none",
    },
    paddings: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    margins: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    widths: {
      1: "100%",
      2: "50%",
      3: "25%",
    },
  },
});

在上面的代码片段中,您已经导出了所有可用的 Stitches 属性,因此您可以导入和使用它们。然后我们为应用程序中的元素定义主题,我们将使用主题属性来设置元素的样式。

创建自定义元素并为其设置样式。

让我们继续使用 Stitches 为我们将在 Gatsby 应用程序中使用的元素创建样式。为了关注点分离,我们将在项目的根目录中为所有元素的样式创建一个components文件夹。在组件文件夹中创建一个名为的新文件Button.js并添加下面的代码片段。

import { styled } from '../../stitches.config';

export const Button = styled("button", {
   // base styles
  display: "block",
  border: "$4",
  borderRadius: "$1",
  color: "$white500",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        color: "white",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

在上面的代码片段中,我们从 Stitches 配置文件中导入了样式属性,允许我们自定义组件。我们使用我们在主题中定义的属性来添加元素的基本样式,使用$符号后跟主题属性。然后我们使用 variables 属性来定义组件的背景颜色 (bg) 和大小 (size) 的样式。接下来,创建一个Container.js并添加下面的代码片段。

import { styled } from "@stitches/react";

export const Container = styled("div", {
   // base styles
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  padding: "$2",
  backgroundColor: "$white500",

  variants: {
    fd: {
      column: {
        flexDirection: "column",
      },
      row: {
        flexDirection: "row",
      },
    },
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
  },
});

在 Container 组件中,我们基于样式主题并定义样式以对齐并使用 variant 属性设置容器的大小。接下来,创建一个Image.js文件并添加下面的代码片段。

import { styled } from "@stitches/react"

export const Image = styled("img", {
  display: "block",
  width: "$1",
  height: "auto",
  maxWidth: "100%",
  maxHeight: "100%",
  margin: "0 auto",
  variants: {
    size: {
      sm: {
        width: "50%",
        height: "50%",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
      lg: {
        width: "100%",
        height: "auto",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
    },
  },
})

我们还定义了具有大图像和小图像的样式,更改图像对齐的样式,并将主题应用于基本样式。接下来,创建一个Header.js文件并添加下面的代码片段。

import { styled } from "@stitches/react";

export const Header = styled("nav", {
  // base styles
  display: "flex",
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
  padding: "$2",
  backgroundColor: "$white500",
  borderBottom: "1px solid #e6e6e6",
 
  variants: {
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

接下来,创建一个Card.js文件并添加下面的代码片段。

import { styled } from "@stitches/react";

export const Card = styled("div", {
  display: "flex",
  justifyContent: "center",
  flexDirection: "column",
  padding: "$1",
  margin: "$2"

  variants: {
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
    boder: {
        none: { 
            border: "none"
        },
        solid: {
            border: "solid 1px #e6e6e6"
        }
    }
  },
});

接下来,Input.js使用下面的代码片段添加一个新文件 。

import { styled } from "@stitches/react";

export const Input = styled("input", {
  display: "block",
  marginBottom: "10px",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
  },
});

上面的代码片段有一个 Input 元素来处理用户的输入。在上面的 Input 组件中,我们需要大小输入,并且我们使用 variables 属性为其定义了样式。接下来,添加一个新文件 ,Text.js并添加下面的代码片段。

import { styled } from "@stitches/react";

export const Text = styled('p', {
    fontFamily: '$mono',
    color: '$black5000',
  
    variants: {
      size: {
        1: {
          fontSize: '10px',
        },
        2: {
          fontSize: '12px',
        },
        3: {
          fontSize: '14px',
        },
      },
    },
  });

在上面的代码片段中,我们创建了一个组件来允许我们添加和设置段落样式。

创建博客应用程序

现在我们已经为这个应用程序设计了我们需要的元素,让我们继续创建一个博客。首先,我们需要更新pages/index.js文件以导入我们刚刚使用下面的代码片段创建的所有组件。

import { Button } from "../components/Button"
import { Input } from "../components/Input"
import { Card } from "../components/Card"
import { Text } from "../components/Text"
import { Header } from "../components/Header"
import { Image } from "../components/Image"
import { Container } from "../components/Container"

接下来,我们将使用该组件使用下面的代码片段更新Home组件。

export default function Home() {
  const [modal, setModal] = useState(false)

  const showModal = () => {
    setModel(!model)
  }
  return (
    <>
      <Container>
        <Header bg="primary">
          <Text size="1">My Blog App</Text>
          <Button bg="secondary" size="sm" onClick={showModal}>
            New Blog
          </Button>
        </Header>
        {model && (
          <Card boder="solid">
            <Text size="1">Titile:</Text>
            <Input />
            <Text size="1">Content</Text>
            <Input />
            <Text size="1">Cover Image</Text>
            <Input />
            <Button bg="primary" size="sm">
              Post
            </Button>
          </Card>
        )}
        <Text>Blog Posts</Text>
      </Container>
      <Container fd="row">
        {blogs.map(blog => (
          <Card boder="solid">
            <Image src={blog.cover} size="lg" />
            <Text size="3">{blog.title}</Text>
            <Text size="1">{blog.content}</Text>
            <Text size="1">{blog.date}</Text>
          </Card>
        ))}
      </Container>
    </>
  )
}

在上面的代码片段中,我们使用我们使用 Stitches 设置样式的组件更新了Home组件。我们将我们想要的样式应用到 Home 组件中使用的每个组件。我们有一个表单输入字段,可以使用Modal状态变量切换为隐藏或显示它。然后我们循环浏览我们将使用 map 函数创建的博客详细信息,并将它们呈现给用户。

最后,将以下博客数组对象添加到Home组件。

...
  const blogs = [
    {
      title: "How to build a website",
      content:
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://www.hostgator.com/blog/wp-content/uploads/2017/09/MakeOwnWebsite.png",
      date: "2020-01-01",
    },
    {
      title: "Getting started with OpenReplay",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://opengraph.githubassets.com/2ddbe84dccfbcc774b1c9861dd327d2efd7e1cd49964dc01229c181bea751e60/openreplay/documentation",
      date: "2020-01-01",
    },
    {
      title: "Node.js Vs React",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://miro.medium.com/max/1400/1*CpDidbInbG4Er_0j_hknFQ.jpeg",
      date: "2020-01-01",
    },
  ]
...

测试应用程序

创建博客演示应用程序后,让我们继续测试它。运行命令将目录更改为项目文件夹并启动应用程序。

cd gatsby-site
gatsby develop

然后导航到 http://localhost:8000/,您应该会在索引页面上看到下面的输出。

第一的

结论

通过构建博客演示应用程序,您已经了解了如何在 Gatsby 应用程序中使用 Stitches 创建主题 UI。首先,我们从 Gatsby 和 Stitches 的介绍开始,您学习了如何使用 Gatsby 配置 Stitches 并设置一些组件的样式。既然您知道如何集成 Gatsby 和 Stitches,那么您将如何设计下一个 Gatsby 应用程序?

来源:https ://blog.openreplay.com/creating-a-theme-in-a-gatsby-application-with-stitches

 #Gatsby #stitches 

如何在 Gatsby 中使用 Stitches 创建主题
Trung  Nguyen

Trung Nguyen

1659181080

Cách Tạo Chủ Đề Trong Gatsby Với Stitches

Gatsby là một khung React phổ biến được sử dụng để xây dựng các trang web và ứng dụng. Thiết kế của nó ưu tiên bảo mật, khả năng mở rộng và hiệu suất. Gatsby được hỗ trợ bởi một hệ sinh thái lớn, bao gồm các Plugin để tích hợp các dịch vụ, các chủ đề để cấu hình đơn giản và Công thức để tự động hóa các tác vụ thường ngày. Trong hướng dẫn này, bạn sẽ học cách tạo chủ đề trong Gatsby bằng Stitches.

Để bắt đầu với hướng dẫn này, hãy đảm bảo bạn có những điều sau

  • Node.js phiên bản 14 trở lên được cài đặt
  • đã cài đặt trình quản lý gói sợi.
  • Kiến thức trước về đường khâu
  • Kiến thức trước về Gatsby

Chúng tôi cũng giả định rằng bạn đã cài đặt CLI của Gatsby trên toàn cầu; làm npm install -g gatsby-clinếu không.

Stitches là gì?

Stitches là một khung công tác React cho phép bạn tự tin tạo và tạo kiểu cho các thành phần có thể tái sử dụng. Nó bao gồm hỗ trợ cho các khung công tác khác như Vue, Svelte và Vanilla HTML. Stitches được tạo ra để giúp các nhà phát triển tránh các nội suy chống không cần thiết trong thời gian chạy, cải thiện hiệu suất ứng dụng. Hãy bắt đầu bằng cách tạo một ứng dụng Gatsby mới.

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

Lệnh trên sẽ sao chép ứng dụng Gatsby starter với cấu trúc thư mục bên dưới.

📦gatsby-site
┣ 📂src
 ┃ ┗ 📂pages
 ┃ ┃ ┗ 📜index.js
 ┣ 📂static
 ┃ ┗ 📜favicon.ico
 ┣ 📜.gitignore
 ┣ 📜.prettierignore
 ┣ 📜.prettierrc
 ┣ 📜LICENSE
 ┣ 📜README.md
 ┣ 📜gatsby-config.js
 ┣ 📜package-lock.json
 ┗ 📜package.json

Thiết lập và định cấu hình các đường khâu

Bây giờ, hãy cấu hình Stitches với ứng dụng Gatsby của bạn. Đầu tiên, bạn phải cài đặt plugin Gatsby để tạo kiểu với Stitches bằng lệnh bên dưới.

yarn add gatsby-theme-stitches @stitches/react

Sau khi cài đặt hoàn tất, hãy mở tệp gatsby-config.js và thêm Stitches vào mảng plugin bằng đoạn mã bên dưới.

module.exports = {
  /* Your site config here */
  plugin: ['gatsby-theme-stitches'],
}

Tại thời điểm này, bạn đã sẵn sàng để bắt đầu tạo kiểu cho ứng dụng Gatsby của mình bằng Stitches. Có hai cách để giải quyết vấn đề này.

  1. Bạn có thể chọn tạo cấu hình của mình bằng cách phủ bóng gatsby-theme-stitches/src/configmô-đun
  2. Bạn có thể nhập các thuộc tính trực tiếp vào ứng dụng của mình.
import { styled } from 'gatsby-theme-stitches/src/config';

Để sử dụng phương pháp đầu tiên, hãy tạo một gatsby-theme-stitches/config.jstệp và thêm các cấu hình sau.

import { createStitches } from '@stitches/react';

// You should export all properties
export const {
  styled,
  css,
  globalCss,
  keyframes,
  getCssText,
  theme,
  createTheme,
  config,
} = createStitches({
   theme: {
    colors: {
      black500: "hsl(0, 0%, 0%)",
      white500: "hsl(0, 0%, 100%)",
      gray500: "hsl(206,10%,76%)",
      blue500: "hsl(206,100%,50%)",
      purple500: "hsl(252,78%,60%)",
      green500: "hsl(148,60%,60%)",
      red500: "hsl(352,100%,62%)",
    },
    space: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    fontSizes: {
      1: "12px",
      2: "13px",
      3: "15px",
    },
    fonts: {
      untitled: "Untitled Sans, apple-system, sans-serif",
      mono: "Söhne Mono, menlo, monospace",
    },
    borderRadius: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    borders: {
      1: "1px solid #ccc",
      2: "2px solid #ccc",
      3: "3px solid #ccc",
      4: "none",
    },
    paddings: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    margins: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    widths: {
      1: "100%",
      2: "50%",
      3: "25%",
    },
  },
});

Trong đoạn mã trên, bạn đã xuất tất cả các thuộc tính Stitches có sẵn, vì vậy bạn có thể nhập và sử dụng chúng. Sau đó, chúng tôi xác định các chủ đề cho các phần tử trong ứng dụng của mình và chúng tôi sẽ sử dụng các thuộc tính chủ đề để tạo kiểu cho các phần tử của chúng tôi.

Tạo và tạo kiểu cho các phần tử tùy chỉnh.

Hãy tiếp tục và sử dụng Stitches để tạo kiểu cho các phần tử mà chúng ta sẽ sử dụng trong ứng dụng Gatsby của mình. Để tách biệt mối quan tâm, chúng tôi sẽ tạo một thư mục thành phần trong thư mục gốc của dự án cho tất cả các kiểu của phần tử. Tạo một tệp mới có tên Button.jstrong thư mục thành phần và thêm các đoạn mã bên dưới.

import { styled } from '../../stitches.config';

export const Button = styled("button", {
   // base styles
  display: "block",
  border: "$4",
  borderRadius: "$1",
  color: "$white500",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        color: "white",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

Trong đoạn mã trên, chúng tôi đã nhập các thuộc tính được tạo kiểu từ tệp cấu hình Stitches, cho phép chúng tôi tùy chỉnh thành phần. Chúng tôi đã sử dụng các thuộc tính mà chúng tôi đã xác định trong chủ đề của mình để thêm kiểu cơ sở của phần tử bằng cách sử dụng biểu tượng $ theo sau là các thuộc tính chủ đề. Sau đó, chúng tôi sử dụng thuộc tính biến thể để xác định kiểu dáng cho màu nền của thành phần (bg) và kích thước (size). Tiếp theo, tạo Container.jsvà thêm các đoạn mã bên dưới.

import { styled } from "@stitches/react";

export const Container = styled("div", {
   // base styles
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  padding: "$2",
  backgroundColor: "$white500",

  variants: {
    fd: {
      column: {
        flexDirection: "column",
      },
      row: {
        flexDirection: "row",
      },
    },
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
  },
});

Trong thành phần Vùng chứa, chúng tôi đặt các chủ đề kiểu cơ sở và xác định kiểu để căn chỉnh và đặt kích thước của vùng chứa bằng cách sử dụng thuộc tính biến thể. Tiếp theo, tạo một Image.jstệp và thêm đoạn mã bên dưới.

import { styled } from "@stitches/react"

export const Image = styled("img", {
  display: "block",
  width: "$1",
  height: "auto",
  maxWidth: "100%",
  maxHeight: "100%",
  margin: "0 auto",
  variants: {
    size: {
      sm: {
        width: "50%",
        height: "50%",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
      lg: {
        width: "100%",
        height: "auto",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
    },
  },
})

Chúng tôi cũng xác định kiểu để có một hình ảnh lớn và nhỏ, kiểu thay đổi căn chỉnh hình ảnh và các chủ đề được áp dụng cho các kiểu cơ bản. Tiếp theo, tạo một Header.jstệp và thêm đoạn mã bên dưới.

import { styled } from "@stitches/react";

export const Header = styled("nav", {
  // base styles
  display: "flex",
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
  padding: "$2",
  backgroundColor: "$white500",
  borderBottom: "1px solid #e6e6e6",
 
  variants: {
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

Tiếp theo, tạo một Card.jstệp và thêm các đoạn mã bên dưới.

import { styled } from "@stitches/react";

export const Card = styled("div", {
  display: "flex",
  justifyContent: "center",
  flexDirection: "column",
  padding: "$1",
  margin: "$2"

  variants: {
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
    boder: {
        none: { 
            border: "none"
        },
        solid: {
            border: "solid 1px #e6e6e6"
        }
    }
  },
});

Tiếp theo, thêm một tệp mới Input.js, với đoạn mã bên dưới.

import { styled } from "@stitches/react";

export const Input = styled("input", {
  display: "block",
  marginBottom: "10px",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
  },
});

Đoạn mã trên có phần tử Input để xử lý đầu vào của người dùng. Trong thành phần Đầu vào ở trên, chúng tôi muốn các đầu vào lớn và nhỏ và chúng tôi đã xác định kiểu cho thành phần đó bằng cách sử dụng thuộc tính biến thể. Tiếp theo, thêm một tệp mới Text.jsvà thêm đoạn mã bên dưới.

import { styled } from "@stitches/react";

export const Text = styled('p', {
    fontFamily: '$mono',
    color: '$black5000',
  
    variants: {
      size: {
        1: {
          fontSize: '10px',
        },
        2: {
          fontSize: '12px',
        },
        3: {
          fontSize: '14px',
        },
      },
    },
  });

Trong đoạn mã trên, chúng tôi đã tạo một thành phần để cho phép chúng tôi thêm và tạo kiểu cho một đoạn văn.

Tạo ứng dụng blog

Bây giờ chúng ta đã tạo kiểu các yếu tố chúng ta cần cho ứng dụng này, hãy tiếp tục và tạo một blog. Đầu tiên, chúng ta cần cập nhật pages/index.jstệp để nhập tất cả các thành phần mà chúng ta vừa tạo bằng đoạn mã bên dưới.

import { Button } from "../components/Button"
import { Input } from "../components/Input"
import { Card } from "../components/Card"
import { Text } from "../components/Text"
import { Header } from "../components/Header"
import { Image } from "../components/Image"
import { Container } from "../components/Container"

Tiếp theo, chúng tôi sẽ sử dụng thành phần để cập nhật thành phần Trang chủ với đoạn mã bên dưới.

export default function Home() {
  const [modal, setModal] = useState(false)

  const showModal = () => {
    setModel(!model)
  }
  return (
    <>
      <Container>
        <Header bg="primary">
          <Text size="1">My Blog App</Text>
          <Button bg="secondary" size="sm" onClick={showModal}>
            New Blog
          </Button>
        </Header>
        {model && (
          <Card boder="solid">
            <Text size="1">Titile:</Text>
            <Input />
            <Text size="1">Content</Text>
            <Input />
            <Text size="1">Cover Image</Text>
            <Input />
            <Button bg="primary" size="sm">
              Post
            </Button>
          </Card>
        )}
        <Text>Blog Posts</Text>
      </Container>
      <Container fd="row">
        {blogs.map(blog => (
          <Card boder="solid">
            <Image src={blog.cover} size="lg" />
            <Text size="3">{blog.title}</Text>
            <Text size="1">{blog.content}</Text>
            <Text size="1">{blog.date}</Text>
          </Card>
        ))}
      </Container>
    </>
  )
}

Trong đoạn mã trên, chúng tôi đã cập nhật thành phần Trang chủ bằng cách sử dụng các thành phần mà chúng tôi đã tạo kiểu bằng Stitches. Chúng tôi đã áp dụng các phong cách chúng tôi muốn cho từng thành phần được sử dụng trong thành phần Trang chủ của chúng tôi. Chúng tôi có một trường nhập biểu mẫu sẽ được chuyển đổi để ẩn hoặc hiển thị nó bằng cách sử dụng biến trạng thái Phương thức . Sau đó, chúng tôi lướt qua các chi tiết blog mà chúng tôi sẽ tạo trong thời gian ngắn bằng cách sử dụng chức năng bản đồ và hiển thị chúng cho người dùng.

Cuối cùng, thêm các đối tượng mảng blog sau vào thành phần Home .

...
  const blogs = [
    {
      title: "How to build a website",
      content:
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://www.hostgator.com/blog/wp-content/uploads/2017/09/MakeOwnWebsite.png",
      date: "2020-01-01",
    },
    {
      title: "Getting started with OpenReplay",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://opengraph.githubassets.com/2ddbe84dccfbcc774b1c9861dd327d2efd7e1cd49964dc01229c181bea751e60/openreplay/documentation",
      date: "2020-01-01",
    },
    {
      title: "Node.js Vs React",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://miro.medium.com/max/1400/1*CpDidbInbG4Er_0j_hknFQ.jpeg",
      date: "2020-01-01",
    },
  ]
...

Kiểm tra ứng dụng

Với ứng dụng demo blog đã được tạo, hãy tiếp tục và thử nghiệm nó. Chạy các lệnh để thay đổi thư mục thành thư mục dự án và khởi động ứng dụng.

cd gatsby-site
gatsby develop

Sau đó, điều hướng đến http: // localhost: 8000 / và bạn sẽ thấy kết quả bên dưới trên trang chỉ mục.

1

Sự kết luận

Bằng cách xây dựng ứng dụng demo blog, bạn đã học cách tạo giao diện người dùng chủ đề trong ứng dụng Gatsby với Stitches. Đầu tiên, chúng tôi bắt đầu với phần giới thiệu về Gatsby và Stitches, và bạn đã học cách định cấu hình Stitches với Gatsby và tạo kiểu cho một số thành phần. Bây giờ bạn đã biết cách tích hợp Gatsby và Stitches, bạn sẽ tạo kiểu ứng dụng Gatsby tiếp theo của mình như thế nào?

Nguồn: https://blog.openreplay.com/creating-a-theme-in-a-gatsby-application-with-stitches

#Gatsby #stitches   

Cách Tạo Chủ Đề Trong Gatsby Với Stitches
藤本  結衣

藤本 結衣

1659180981

Gatsby と Stitchesでテーマを作成する方法

Gatsbyは、Web ページやアプリの構築に使用される一般的な React フレームワークです。その設計では、セキュリティ、スケーラビリティ、およびパフォーマンスが優先されます。Gatsby は、サービスを統合するためのプラグイン、簡単な構成のためのテーマ、日常的なタスクを自動化するためのレシピを含む大規模なエコシステムによってサポートされています。このチュートリアルでは、Gatsby でステッチを使用してテーマを作成する方法を学習します。

このチュートリアルを開始するには、次のものが揃っていることを確認してください

  • Node.jsバージョン 14 以降がインストールされている
  • yarn パッケージマネージャーがインストールされました。
  • ステッチの予備知識
  • ギャツビーの予備知識

また、Gatsby の CLI がグローバルにインストールされていることも前提としています。そうでないnpm install -g gatsby-cli場合は行います。

スティッチとは?

Stitchesは、再利用可能なコンポーネントを自信を持って作成し、スタイルを設定できる React フレームワークです。Vue、Svelte、Vanilla HTML などの他のフレームワークのサポートが含まれています。スティッチは、開発者が実行時に不要な prop 補間を回避し、アプリケーションのパフォーマンスを向上させるのに役立つように作成されました。新しい Gatsby アプリケーションを作成することから始めましょう。

gatsby new gatsby-site https://github.com/gatsbyjs/gatsby-starter-hello-world

上記のコマンドは、以下のフォルダー構造を持つ Gatsby スターター アプリケーションを複製します。

📦gatsby-site
┣ 📂src
 ┃ ┗ 📂pages
 ┃ ┃ ┗ 📜index.js
 ┣ 📂static
 ┃ ┗ 📜favicon.ico
 ┣ 📜.gitignore
 ┣ 📜.prettierignore
 ┣ 📜.prettierrc
 ┣ 📜LICENSE
 ┣ 📜README.md
 ┣ 📜gatsby-config.js
 ┣ 📜package-lock.json
 ┗ 📜package.json

ステッチのセットアップと設定

それでは、Gatsby アプリケーションでステッチを構成しましょう。まず、次のコマンドを使用して、Stitches でスタイリングするための Gatsby プラグインをインストールする必要があります。

yarn add gatsby-theme-stitches @stitches/react

インストールが完了したら、gatsby-config.js ファイルを開き、以下のコード スニペットを使用して、Stitches をプラグインの配列に追加します。

module.exports = {
  /* Your site config here */
  plugin: ['gatsby-theme-stitches'],
}

この時点で、Stitches を使用して Gatsby アプリケーションのスタイリングを開始する準備が整いました。これには 2 つの方法があります。

  1. gatsby-theme-stitches/src/configモジュールをシャドウすることにより、構成を作成することを選択できます
  2. プロパティをアプリケーションに直接インポートできます。
import { styled } from 'gatsby-theme-stitches/src/config';

最初の方法を使用するには、gatsby-theme-stitches/config.jsファイルを作成し、次の構成を追加します。

import { createStitches } from '@stitches/react';

// You should export all properties
export const {
  styled,
  css,
  globalCss,
  keyframes,
  getCssText,
  theme,
  createTheme,
  config,
} = createStitches({
   theme: {
    colors: {
      black500: "hsl(0, 0%, 0%)",
      white500: "hsl(0, 0%, 100%)",
      gray500: "hsl(206,10%,76%)",
      blue500: "hsl(206,100%,50%)",
      purple500: "hsl(252,78%,60%)",
      green500: "hsl(148,60%,60%)",
      red500: "hsl(352,100%,62%)",
    },
    space: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    fontSizes: {
      1: "12px",
      2: "13px",
      3: "15px",
    },
    fonts: {
      untitled: "Untitled Sans, apple-system, sans-serif",
      mono: "Söhne Mono, menlo, monospace",
    },
    borderRadius: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    borders: {
      1: "1px solid #ccc",
      2: "2px solid #ccc",
      3: "3px solid #ccc",
      4: "none",
    },
    paddings: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    margins: {
      1: "5px",
      2: "10px",
      3: "15px",
    },
    widths: {
      1: "100%",
      2: "50%",
      3: "25%",
    },
  },
});

上記のコード スニペットでは、使用可能なすべてのステッチ プロパティをエクスポートしたので、それらをインポートして使用できます。次に、アプリケーションの要素のテーマを定義し、テーマ プロパティを使用して要素のスタイルを設定します。

カスタム要素を作成してスタイルを設定します。

では、Stitches を使用して、Gatsby アプリケーションで使用する要素のスタイルを作成しましょう。懸念事項を分離するために、プロジェクトのルート ディレクトリにすべての要素のスタイル用のコンポーネントフォルダーを作成します。コンポーネント フォルダーにという名前の新しいファイルを作成し、Button.js以下のコード スニペットを追加します。

import { styled } from '../../stitches.config';

export const Button = styled("button", {
   // base styles
  display: "block",
  border: "$4",
  borderRadius: "$1",
  color: "$white500",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        color: "white",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

上記のコード スニペットでは、Stitches 構成ファイルからスタイル設定されたプロパティをインポートして、コンポーネントをカスタマイズできるようにしました。テーマで定義したプロパティを使用して、$記号とそれに続くテーマ プロパティを使用して要素の基本スタイルを追加しました。次に、バリアント プロパティを使用して、コンポーネントの背景色 (bg) とサイズ (size) のスタイルを定義しました。次に、Container.js以下のコード スニペットを作成して追加します。

import { styled } from "@stitches/react";

export const Container = styled("div", {
   // base styles
  display: "flex",
  flexDirection: "column",
  justifyContent: "center",
  padding: "$2",
  backgroundColor: "$white500",

  variants: {
    fd: {
      column: {
        flexDirection: "column",
      },
      row: {
        flexDirection: "row",
      },
    },
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
  },
});

コンテナー コンポーネントでは、スタイル テーマをベースにして、バリアント プロパティを使用してコンテナーのサイズを調整および設定するためのスタイルを定義します。次に、Image.jsファイルを作成し、以下のコード スニペットを追加します。

import { styled } from "@stitches/react"

export const Image = styled("img", {
  display: "block",
  width: "$1",
  height: "auto",
  maxWidth: "100%",
  maxHeight: "100%",
  margin: "0 auto",
  variants: {
    size: {
      sm: {
        width: "50%",
        height: "50%",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
      lg: {
        width: "100%",
        height: "auto",
        maxWidth: "100%",
        maxHeight: "100%",
        margin: "0 auto",
      },
    },
  },
})

また、大小の画像を持つスタイル、画像の配置を変更するスタイルを定義し、基本スタイルにテーマを適用しました。次に、Header.jsファイルを作成し、以下のコード スニペットを追加します。

import { styled } from "@stitches/react";

export const Header = styled("nav", {
  // base styles
  display: "flex",
  flexDirection: "row",
  justifyContent: "space-between",
  alignItems: "center",
  padding: "$2",
  backgroundColor: "$white500",
  borderBottom: "1px solid #e6e6e6",
 
  variants: {
    size: {
      sm: {
        width: "100%",
        height: "50px",
      },
      lg: {
        width: "100%",
        height: "60px",
      },
    },
    bg: {
      primary: {
        backgroundColor: "#2196f3",
        "&:hover": {
          backgroundColor: "#64b5f6",
        },
      },
      secondary: {
        backgroundColor: "#009688",
        "&:hover": {
          backgroundColor: "#4db6ac",
        },
      },
      danger: {
        backgroundColor: "#f44336",
        "&:hover": {
          backgroundColor: "#ef9a9a",
        },
      },
      success: {
        backgroundColor: "#4caf50",
        "&:hover": {
          backgroundColor: "#a5d6a7",
        },
      },
    },
  },
});

次に、Card.jsファイルを作成し、以下のコード スニペットを追加します。

import { styled } from "@stitches/react";

export const Card = styled("div", {
  display: "flex",
  justifyContent: "center",
  flexDirection: "column",
  padding: "$1",
  margin: "$2"

  variants: {
    align: {
      center: {
        alignItems: "center",
      },
      left: {
        alignItems: "flex-start",
      },
      right: {
        alignItems: "flex-end",
      },
    },
    boder: {
        none: { 
            border: "none"
        },
        solid: {
            border: "solid 1px #e6e6e6"
        }
    }
  },
});

Input.js次に、以下のコード スニペットを含む新しいファイル を追加します。

import { styled } from "@stitches/react";

export const Input = styled("input", {
  display: "block",
  marginBottom: "10px",

  variants: {
    size: {
      sm: {
        fontSize: "13px",
        height: "25px",
        paddingRight: "10px",
        paddingLeft: "10px",
      },
      lg: {
        fontSize: "15px",
        height: "35px",
        paddingLeft: "15px",
        paddingRight: "15px",
      },
    },
  },
});

上記のコード スニペットには、ユーザーの入力を処理するための Input 要素があります。上記の入力コンポーネントでは、大きな入力と小さな入力が必要であり、バリアント プロパティを使用してそのスタイルを定義しました。次に、新しいファイルText.jsを追加し、以下のコード スニペットを追加します。

import { styled } from "@stitches/react";

export const Text = styled('p', {
    fontFamily: '$mono',
    color: '$black5000',
  
    variants: {
      size: {
        1: {
          fontSize: '10px',
        },
        2: {
          fontSize: '12px',
        },
        3: {
          fontSize: '14px',
        },
      },
    },
  });

上記のコード スニペットでは、段落の追加とスタイル設定を可能にするコンポーネントを作成しました。

ブログアプリの作成

このアプリケーションに必要な要素のスタイルを設定したので、ブログを作成しましょう。まず、pages/index.jsファイルを更新して、以下のコード スニペットで作成したすべてのコンポーネントをインポートする必要があります。

import { Button } from "../components/Button"
import { Input } from "../components/Input"
import { Card } from "../components/Card"
import { Text } from "../components/Text"
import { Header } from "../components/Header"
import { Image } from "../components/Image"
import { Container } from "../components/Container"

次に、コンポーネントを使用して、以下のコード スニペットでHomeコンポーネントを更新します。

export default function Home() {
  const [modal, setModal] = useState(false)

  const showModal = () => {
    setModel(!model)
  }
  return (
    <>
      <Container>
        <Header bg="primary">
          <Text size="1">My Blog App</Text>
          <Button bg="secondary" size="sm" onClick={showModal}>
            New Blog
          </Button>
        </Header>
        {model && (
          <Card boder="solid">
            <Text size="1">Titile:</Text>
            <Input />
            <Text size="1">Content</Text>
            <Input />
            <Text size="1">Cover Image</Text>
            <Input />
            <Button bg="primary" size="sm">
              Post
            </Button>
          </Card>
        )}
        <Text>Blog Posts</Text>
      </Container>
      <Container fd="row">
        {blogs.map(blog => (
          <Card boder="solid">
            <Image src={blog.cover} size="lg" />
            <Text size="3">{blog.title}</Text>
            <Text size="1">{blog.content}</Text>
            <Text size="1">{blog.date}</Text>
          </Card>
        ))}
      </Container>
    </>
  )
}

上記のコード スニペットでは、Stitches を使用してスタイルを設定したコンポーネントを使用してHomeコンポーネントを更新しました。Home コンポーネントで使用される各コンポーネントに必要なスタイルを適用しました。Modal状態変数を使用して非表示または表示に切り替えるフォーム入力フィールドがあります。次に、これから作成するブログの詳細を map 関数を使用してループし、ユーザーに表示します。

最後に、次のブログ配列オブジェクトをHomeコンポーネントに追加します。

...
  const blogs = [
    {
      title: "How to build a website",
      content:
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://www.hostgator.com/blog/wp-content/uploads/2017/09/MakeOwnWebsite.png",
      date: "2020-01-01",
    },
    {
      title: "Getting started with OpenReplay",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://opengraph.githubassets.com/2ddbe84dccfbcc774b1c9861dd327d2efd7e1cd49964dc01229c181bea751e60/openreplay/documentation",
      date: "2020-01-01",
    },
    {
      title: "Node.js Vs React",
      content:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel consectetur euismod, nisi nisl aliquet nisi, eget consectetur nisl nisi eget nisi. Nullam euismod, nisi vel",
      cover:
        "https://miro.medium.com/max/1400/1*CpDidbInbG4Er_0j_hknFQ.jpeg",
      date: "2020-01-01",
    },
  ]
...

アプリケーションをテストする

ブログ デモ アプリケーションが作成されたので、テストしてみましょう。コマンドを実行してディレクトリをプロジェクト フォルダーに変更し、アプリケーションを起動します。

cd gatsby-site
gatsby develop

次に、http://localhost:8000/ に移動すると、インデックス ページに以下の出力が表示されます。

1

結論

ブログ デモ アプリケーションを作成することで、Stitches を使用して Gatsby アプリケーションでテーマ UI を作成する方法を学習しました。まず、ギャツビーとステッチの紹介から始めました。ギャツビーでステッチを構成し、いくつかのコンポーネントのスタイルを設定する方法を学びました。Gatsby と Stitches を統合する方法がわかったので、次の Gatsby アプリケーションのスタイルをどのように設定しますか?

ソース: https://blog.openreplay.com/creating-a-theme-in-a-gatsby-application-with-stitches

 #Gatsby #stitches 

Gatsby と Stitchesでテーマを作成する方法

How to Create A Theme in Gatsby with Stitches

Gatsby is a popular React framework used to build webpages and apps. Its design prioritizes security, scalability, and performance. Gatsby is supported by a large ecosystem, which includes Plugins for integrating services, themes for simple configuration, and Recipes for automating routine tasks. In this tutorial, you’ll learn how to create a theme in Gatsby with Stitches.

To get started with this tutorial, ensure you have the following

  • Node.js version 14 or later installed
  • yarn package manager installed.
  • Prior Knowledge of Stitches
  • Prior Knowledge of Gatsby

We also assume you have installed Gatsby’s CLI globally; do npm install -g gatsby-cli if not.

See more at: https://blog.openreplay.com/creating-a-theme-in-a-gatsby-application-with-stitches

#Gatsby #stitches 

How to Create A Theme in Gatsby with Stitches

How to Incrementally Migrate A Gatsby App To TypeScript

It shouldn’t come as a surprise that TypeScript is getting more traction among developers by the day. Support for it has grown considerably, as well as the community and number of projects adopting this technology.

It wasn’t always like that, though. Web developers have been burned before by hot technologies that disappeared, and it’s only fair that some in the community are more skeptical about big changes. In fact, the Lindy effect proposes that every day a piece of technology continues to survive, the longer it is expected to exist.

The goal of this article is not to convince you to migrate to TypeScript; I assume that if you are here, you have already been sold on the benefits of static typing in a dynamic language like JavaScript. However, if you are like me, you probably have been delaying the migration, fearful of the amount of work needed to set it in motion.

See more at: https://blog.logrocket.com/incrementally-migrate-gatsby-app-typescript/

#Gatsby #typescript 

How to Incrementally Migrate A Gatsby App To TypeScript
许 志强

许 志强

1659015000

如何将 Gatsby 应用程序增量迁移到 TypeScript

TypeScript 在开发人员中越来越受欢迎,这不足为奇。对它的支持已经大大增加,社区和采用这项技术的项目数量也在增加。

不过,情况并非总是如此。Web 开发人员以前曾被消失的热门技术所困扰,社区中的一些人对重大变化持怀疑态度是公平的。事实上,林迪效应表明,一项技术每天都在继续生存,它预计存在的时间越长。

本文的目的不是说服您迁移到 TypeScript;而是要说服您迁移到 TypeScript。我假设如果你在这里,你已经被 JavaScript 这样的动态语言中静态类型的好处所吸引。但是,如果您像我一样,您可能一直在推迟迁移,担心启动它所需的工作量。

好吧,不要再害怕了!我已经为你完成了繁重的工作。在本文中,您将学习如何逐步采用 TypeScript,以便您可以顺利过渡并在下班后睡个好觉。

为什么是渐进式的?

为什么我们在这篇文章的标题中有“增量”?这不就是推迟不可避免的事情吗?为什么不立即执行完整迁移?

这些都是有效的观点,在某些情况下,它们甚至是最可取的。但是,我假设您有一个有点大的项目,足够大以至于使用 codemod 将不起作用(或者需要太多的解决方法)。

或者,也许您在一个更大的团队中处理应用程序的特定部分,并希望在进行重大更改之前进行试点。

在所有情况下,都有一些有效的场景,人们会首先采取谨慎的态度。即使你会发现一堆声称是无缝的 codemod 或迁移方法,但现实情况是,如果你的项目有一些复杂性,它可能不像他们说的那么容易。

然而,为了提供一个对立面,Stripe 的人似乎不同意我的观点。他们最近刚刚发布了一篇声称已将数百万行代码迁移到 TypeScript 的文章。如果您喜欢冒险,那么值得一试!

如何在现有的 Gatsby 应用程序中设置 TypeScript

好的,对于今天的实验,我们假设您已经有一个 Gatsby 应用程序并希望执行逐步迁移。

请记住,如果您今天创建一个新项目,Gatsby 从一开始就已经支持 TypeScript 作为主要语言。不幸的是,在旧版本的 Gatsby 中引导的大多数项目并非如此,因此我们将采取不同的路线。

Gatsby 文档已经为如何迁移提供了一个很好的指南。然而,为了让它顺利启动和运行,我们需要做一些调整。

将 .js 文件更改为 .tsx

更简单的部分是更改要迁移到 .tsx 的所有组件,或以这种格式创建新组件。盖茨比方面不需要做任何工作就可以了!这很整洁。

安装依赖项

但是,需要安装一些库。确保将它们添加到您的devDependencies

$ npm i –save-dev @types/node @types/react @types/react-dom typescript 

产生.tsconfig

TypeScript 有一个名为 的配置文件.tsconfig,它是高度可定制的,并且会因项目而异。但是,为了让 TypeScript 和 JavaScript 和谐共存,我们需要做一些具体的改变,因为这是每个人逐渐采用 TS 的要求。

一个工作的例子.tsconfig如下。确保将其添加到项目的根文件夹中:

{
  "compilerOptions": {
    "target": "es2016",
    "jsx": "react",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "exclude": ["node_modules", "public", ".cache"]
}

您还可以在 GitHub 中的这个公共 repo 上查看示例。

一些需要的配置如下:

  • 添加"jsx": "react" 以确保编译器知道我们在 React 项目中
  • 设置allowJs: true;一旦 JavaScript 和 TypeScript 需要共存,这个标志应该被打开
  • 添加outDir: "./dist",这使 VS Code 快乐并防止不必要的错误

声明全局变量

如果你走到这一步,你的大部分设置已经在工作了。但是,仍然存在一些粗糙的边缘。

最明显的是关于 CSS 模块;Gatsby 默认使用 CSS 模块,我们需要让 TypeScript 对此感到满意。如果您使用SVG 作为此处描述的组件,这也将很有用。

src项目的文件夹中,创建一个名为globals.d.ts并添加以下内容的文件:

声明模块“*.module.css”;声明模块“*.module.scss”;声明模块“*.svg”{ 常量内容:字符串;导出默认内容;}

这将确保 CSS 和 SVG 都被视为模块并被处理

同样,您可以在 GitHub 中查看一个工作示例

如果你使用 ESLint,它可能会抱怨 .d.ts 文件。在这种情况下,您可以在此类扩展中禁用 linter

使用道具类型打字

TypeScript 的主要优点之一是允许在 JavaScript 中进行静态类型。在使用 React 开发时,这是非常受欢迎的,因为它使我们更难添加不存在的 props 甚至传递错误的变量。

在 TypeScript 出现之前,React 团队使用 prop types普及了类型检查。

道具类型是无验证和严格类型之间的中间步骤。使用道具类型,开发人员可以列出给定组件中的所有道具、它们对应的类型以及它们是可选的还是强制的。

例如,假设我们有一个组件接收一个名为 的 prop magicNumber,它当然应该有类型号:

import PropTypes from 'prop-types'

const MyComponent = ({ magicNumber }) => { … } 

MyComponent.propTypes = {
  magicNumber: PropTypes.number.isRequired
} 

假设我们渲染MyComponent但忘记magicNumber作为道具传递,或者传递一个字符串。在开发模式下,我们会在控制台中看到这样的警告:

开发模式下的警告

但是,不会有静态验证,在较大的组件或较大的项目中很容易忽略这种错误。此外,我们可以添加一个道具,但忘记设置它的类型(不过有一些 linter 可以帮助你)。

使用静态类型,您可以弃用 prop 类型以支持常规 TypeScript 类型:

type Props = {
  magicNumber: number
}

const MyComponent = ({ magicNumber }: Props) => { … } 

现在,如果你有一个 render 的 .tsx 组件MyComponent,传递一个错误类型的 prop 将在构建时引发错误:

构建时间错误

就是这样!更安全,但不那么冗长,并且具有所有打字优势。总而言之,prop 类型可以工作,但不如 TypeScript 等健壮的类型策略强大。如果你想更深入地了解这个主题,我建议你阅读我们关于这个主题的预览文章:比较 React 应用程序中的 TypeScript 和 PropTypes

如果您确信静态类型优于 prop 类型,那么您还应该知道在混合 TypeScript 和 JavaScript 的项目中放弃 prop 类型时有一个警告。

假设我们有一个WithTypeScript.tsx渲染 TypeScript 版本的组件MyComponent。如果我们尝试通过magicNumber="Hello World",一旦出现类型不匹配,就会引发错误,如上所示。

但是,如果WithTypeScript.tsxmagicNumber用纯 JavaScript 编写的父组件接收并将其传递给MyComponent.tsx,则无法验证变量是否确实是数字。一旦父组件没有类型,就不会引发静态错误。并且因为 中没有 prop 类型MyComponent.tsx,所以不会引发运行时错误。因此,不会在任何地方引发这种类型不匹配。

没有运行时错误

请注意如何使用错误的 prop 类型IndexPage.js调用 TypeScript 组件。WithTypeScript.tsx在编辑器或浏览器控制台中都看不到警告。

请记住,这只发生在 .js 和 .tsx 组件通信时,如果您逐渐采用 TypeScript,这将不可避免地发生。幸运的是,有一个解决方案:通过从 TypeScript 组件中的 prop 类型推断类型,我们可以两全其美。这样,我们保留了 prop 类型,但使用 prop-types 库中的函数自动将它们转换InferProps类型

这将MyComponent.tsx结合类型和道具类型:

import React from "react";
import PropTypes, { InferProps } from "prop-types";

const Props = {
  magicNumber: PropTypes.number.isRequired,
};

type MyComponentTypes = InferProps<typeof Props>;

const MyComponent = ({ magicNumber }: MyComponentTypes) => { … };

MyComponent.propTypes = Props;

export default MyComponent;

一个完整的例子可以在这里看到

如果存在类型不匹配,上述解决方案将在构建时引发静态错误,但如果在此过程中将错误的类型从 .js 传递到 .ts 组件,也会在浏览器控制台中引发运行时错误。缺点是您的代码变得更加冗长。

但是,如果较新的组件只与其他 .ts 文件通信,那么放弃 prop 类型应该是安全的。最终,当迁移完成时,您可以完全删除它们。

结论

TypeScript 是一种特殊的工具,但一些开发人员避免在现有代码库中采用它。本文旨在阐明如何在您的项目中安全地做到这一点,而无需进行重大更改。

虽然 Gatsby 特别支持开箱即用的 .tsx 文件,但考虑到 Gatsby 代码库中存在的典型方法,您需要一些变通方法来使编译器满意。为 CSS 模块和 SVG 声明全局变量是常见的痛点。

最后,通过让 JavaScript 与 TypeScript 通信,我们不能保证某些输入错误不会是不透明的。正因为如此,我们可以利用 prop-types 库并推断类型,在我们可以安全地弃用之前获得两全其美的效果。

本文中的所有代码和示例都可以在 GitHub 的这个 repo 中找到。试试看!

来源:https ://blog.logrocket.com/incrementally-migrate-gatsby-app-typescript/

#Gatsby #typescript 

如何将 Gatsby 应用程序增量迁移到 TypeScript

Migrar De Forma Incremental Una Aplicación De Gatsby A TypeScript

No debería sorprender que TypeScript esté ganando más terreno entre los desarrolladores cada día. El apoyo a la misma ha crecido considerablemente, así como la comunidad y el número de proyectos que adoptan esta tecnología.

Sin embargo, no siempre fue así. Los desarrolladores web han sido quemados antes por tecnologías candentes que desaparecieron, y es justo que algunos en la comunidad sean más escépticos acerca de los grandes cambios. De hecho, el efecto Lindy propone que cada día que sobreviva una pieza de tecnología, más tiempo se espera que exista.

El objetivo de este artículo no es convencerlo de que migre a TypeScript; Supongo que si está aquí, ya le han vendido los beneficios de la escritura estática en un lenguaje dinámico como JavaScript. Sin embargo, si es como yo, probablemente haya estado retrasando la migración, temeroso de la cantidad de trabajo necesario para ponerla en marcha.

Bueno, ¡no temas más! He hecho el trabajo pesado por ti. En este artículo, aprenderá cómo adoptar TypeScript de forma incremental, para que pueda tener una transición fluida y una buena noche de sueño después del trabajo.

¿Por qué incrementalmente?

¿Por qué tenemos "incrementalmente" en el título de este artículo? ¿No es eso solo retrasar lo inevitable? ¿Por qué no realizar una migración completa a la vez?

Esos son puntos válidos, y en algunos casos, incluso pueden ser los más recomendables. Sin embargo, supongo que tiene un proyecto algo grande, lo suficientemente grande como para que el uso de un codemod no funcione (o requerirá demasiada solución).

O tal vez trabaja en una parte específica de una aplicación en un equipo más grande y desea ejecutar una prueba piloto antes de hacer el gran cambio.

En todos los casos, hay escenarios válidos en los que uno tomaría primero el camino de precaución. Y aunque encontrará un montón de codemods o métodos de migración que afirman ser perfectos, la realidad es que si su proyecto tiene cierta complejidad, puede que no sea tan fácil como predican.

Sin embargo, para ofrecer un contrapunto, la gente de Stripe parece no estar de acuerdo conmigo. Recientemente publicaron un artículo que afirmaba haber migrado millones de líneas de código a TypeScript. Si te sientes aventurero, ¡vale la pena echarle un vistazo!

Cómo configurar TypeScript en una aplicación Gatsby existente

Bien, para el experimento de hoy asumiremos que ya tienes una aplicación de Gatsby y quieres realizar una migración gradual.

Recuerda que si estás creando un nuevo proyecto hoy, Gatsby ya admite TypeScript como lenguaje principal desde el principio. Desafortunadamente, ese no es el caso para la mayoría de los proyectos que se iniciaron en versiones anteriores de Gatsby, por lo que tomaremos una ruta diferente.

Los documentos de Gatsby ya presentan una buena guía sobre cómo migrar . Sin embargo, hay algunos ajustes que debemos hacer para que funcione sin problemas.

Cambie sus archivos .js a .tsx

La parte más fácil es cambiar todos los componentes que desea migrar a .tsx o crear nuevos en este formato. ¡No se necesita ningún trabajo por parte de Gatsby para que esto funcione! Eso es bastante bueno.

Instalar dependencias

Sin embargo, hay algunas bibliotecas para instalar. Asegúrate de agregarlos a tu devDependencies:

$ npm i –save-dev @types/node @types/react @types/react-dom typescript 

Generar.tsconfig

TypeScript tiene un archivo de configuración llamado .tsconfig, que es enormemente personalizable y variará de un proyecto a otro. Sin embargo, hay algunos cambios específicos que debemos realizar para permitir que TypeScript y JavaScript coexistan en armonía, ya que este es un requisito para que todos adopten TS gradualmente.

Un ejemplo de funcionamiento .tsconfiges el siguiente. Asegúrese de agregarlo a la carpeta raíz de su proyecto:

{
  "compilerOptions": {
    "target": "es2016",
    "jsx": "react",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "exclude": ["node_modules", "public", ".cache"]
}

También puede consultar un ejemplo en este repositorio público en GitHub .

Algunas de las configuraciones necesarias son las siguientes:

  • Agregue "jsx": "react" para asegurarse de que el compilador sepa que estamos en un proyecto React
  • Establecer allowJs: true; una vez que JavaScript y TypeScript necesiten coexistir, esta bandera debe estar activada
  • Add outDir: "./dist", que hace feliz a VS Code y evita errores no deseados

Declarando globales

Si llegaste hasta aquí, ya tienes la mayor parte de tu configuración funcionando. Sin embargo, todavía hay algunas asperezas.

El más obvio es sobre los módulos CSS; Gatsby funciona con módulos CSS de forma predeterminada y debemos dejar que TypeScript esté contento con eso. Si usa SVG como componentes como se describe aquí , esto también será útil.

En la srccarpeta de su proyecto, cree un archivo llamado globals.d.tsy agregue lo siguiente:

declarar módulo "*.module.css"; declarar módulo "*.module.scss"; declarar módulo "*.svg" { const contenido: cadena; exportar contenido predeterminado; }

Esto asegurará que tanto CSS como SVG sean tratados y manejados como módulos .

Nuevamente, puede consultar un ejemplo de trabajo en GitHub .

Si está utilizando ESLint, puede quejarse de los archivos .d.ts. En este caso, puedes deshabilitar el linter en dichas extensiones .

Escribir usando tipos de accesorios

Una de las principales ventajas de TypeScript es permitir la escritura estática en JavaScript. Al desarrollar con React, esto es muy bienvenido, porque nos dificulta agregar accesorios que no existen o incluso pasar la variable incorrecta.

Antes de que TypeScript existiera, el equipo de React popularizó la verificación de tipos con tipos de accesorios .

Los tipos de utilería eran un paso intermedio entre la ausencia de validación y la tipificación estricta. Con los tipos de accesorios, los desarrolladores pueden enumerar todos los accesorios en un componente determinado, su tipo correspondiente y si son opcionales u obligatorios.

Por ejemplo, supongamos que tenemos un componente que recibe un accesorio llamado magicNumber, que por supuesto debería tener el número de tipo:

import PropTypes from 'prop-types'

const MyComponent = ({ magicNumber }) => { … } 

MyComponent.propTypes = {
  magicNumber: PropTypes.number.isRequired
} 

Supongamos entonces que renderizamos MyComponentpero olvidamos pasar magicNumbercomo prop, o pasamos una cadena en su lugar. Veríamos una advertencia como esta en la consola, cuando estamos en modo de desarrollo:

advertencia en modo de desarrollo

Sin embargo, no habría validación estática y es fácil pasar por alto este tipo de error en componentes o proyectos más grandes. Además, podemos agregar un accesorio pero olvidar establecer su tipo (aunque hay algunos linters que te ayudan con eso).

Con la escritura estática, puede desaprobar los tipos de accesorios en favor de los tipos de TypeScript normales:

type Props = {
  magicNumber: number
}

const MyComponent = ({ magicNumber }: Props) => { … } 

Ahora, si tiene un componente .tsx que se procesa MyComponent, pasar un accesorio con el tipo incorrecto generará un error en el momento de la compilación:

error de tiempo de compilación

¡Y eso es! Más seguro, pero menos detallado, y viene con todos los beneficios de escritura. En general, los tipos de accesorios funcionan, pero son menos potentes que una estrategia de escritura robusta como TypeScript. Si desea profundizar en este tema, le recomiendo que lea nuestro artículo de vista previa sobre el tema: Comparación de TypeScript y PropTypes en aplicaciones React .

Si está convencido de que la escritura estática es superior a los tipos de accesorios, también debe saber que hay una advertencia al deshacerse de los tipos de accesorios en un proyecto que es un híbrido de TypeScript y JavaScript.

Supongamos que tenemos un WithTypeScript.tsxcomponente que representa la versión de TypeScript de MyComponent. Si intentamos pasar magicNumber="Hello World"esto, generará un error una vez que haya una falta de coincidencia de tipo, como se ve arriba.

Sin embargo, si WithTypeScript.tsxrecibe magicNumberde un componente principal escrito en JavaScript puro y lo pasa a MyComponent.tsx, no hay forma de validar si la variable es realmente un número. Una vez que el componente principal no tiene escritura, no se generará ningún error estático. Y debido a que no hay tipos de accesorios en MyComponent.tsx, no se generará ningún error de tiempo de ejecución. Como tal, esta discrepancia de tipos no se planteará en ninguna parte.

sin error de tiempo de ejecución

Observe cómo IndexPage.jsllama a un componente de TypeScript WithTypeScript.tsxcon un tipo de accesorio incorrecto. No se ve ninguna advertencia ni en el editor ni en la consola del navegador.

Tenga en cuenta que esto solo sucede cuando los componentes .js y .tsx se comunican, lo que inevitablemente sucederá si está adoptando TypeScript gradualmente. Afortunadamente, hay una solución para ello: podemos tener lo mejor de ambos mundos infiriendo tipos a partir de tipos prop en componentes de TypeScript. De esta forma, conservamos los tipos de accesorios, pero los convertimos automáticamente en tipos usando la función InferPropsde la biblioteca de tipos de accesorios .

Esto sería MyComponent.tsxcombinar tipos y tipos de accesorios:

import React from "react";
import PropTypes, { InferProps } from "prop-types";

const Props = {
  magicNumber: PropTypes.number.isRequired,
};

type MyComponentTypes = InferProps<typeof Props>;

const MyComponent = ({ magicNumber }: MyComponentTypes) => { … };

MyComponent.propTypes = Props;

export default MyComponent;

Un ejemplo completo se puede ver aquí .

La solución anterior generará un error estático en el momento de la compilación si hay una falta de coincidencia de tipo, pero también generará un error de tiempo de ejecución en la consola del navegador si se pasa el tipo incorrecto de un componente .js a un componente .ts en el camino. El inconveniente es que su código se vuelve más detallado.

Sin embargo, si los componentes más nuevos solo se comunican con otros archivos .ts, entonces debería ser seguro deshacerse de los tipos de accesorios. Eventualmente, cuando se complete la migración, puede eliminarlos por completo.

Conclusión

TypeScript es una herramienta excepcional, pero algunos desarrolladores se abstienen de adoptarlo en una base de código existente. Este artículo tuvo como objetivo dilucidar cómo puedes hacerlo de forma segura en tu proyecto, ahora mismo, sin grandes cambios.

Si bien Gatsby, en particular, admite archivos .tsx listos para usar, necesita algunas soluciones para que su compilador esté feliz considerando los enfoques típicos presentes en las bases de código de Gatsby. Declarar globales para módulos CSS y SVG son puntos débiles comunes.

Finalmente, al tener JavaScript comunicándose con TypeScript, no podemos garantizar que algunos errores de tipeo no sean opacos. Por eso, podemos aprovechar la biblioteca de tipos de accesorios e inferir los tipos, obteniendo lo mejor de ambos mundos hasta que estemos seguros de desaprobarlos.

Todo el código y los ejemplos presentes en este artículo se pueden encontrar en este repositorio en GitHub . ¡Darle una oportunidad!

Fuente: https://blog.logrocket.com/incrementally-migrate-gatsby-app-typescript/

#Gatsby #typescript 

Migrar De Forma Incremental Una Aplicación De Gatsby A TypeScript

Como Migrar Incrementalmente Um Aplicativo Gatsby Para O TypeScript

Não deve ser uma surpresa que o TypeScript esteja ganhando mais força entre os desenvolvedores a cada dia. O apoio a ela cresceu consideravelmente, assim como a comunidade e o número de projetos que adotam essa tecnologia.

Nem sempre foi assim, no entanto. Os desenvolvedores da Web foram queimados antes por tecnologias quentes que desapareceram, e é justo que alguns na comunidade sejam mais céticos em relação a grandes mudanças. De fato, o efeito Lindy propõe que a cada dia uma peça de tecnologia continue a sobreviver, quanto mais tempo se espera que ela exista.

O objetivo deste artigo não é convencê-lo a migrar para o TypeScript; Presumo que, se você está aqui, já conhece os benefícios da digitação estática em uma linguagem dinâmica como JavaScript. No entanto, se você é como eu, provavelmente está atrasando a migração, com medo da quantidade de trabalho necessária para colocá-la em movimento.

Bem, não tema mais! Eu fiz o trabalho pesado para você. Neste artigo, você aprenderá a adotar o TypeScript de forma incremental, para que possa ter uma transição suave e uma boa noite de sono após o trabalho.

Por que incrementalmente?

Por que temos “incrementalmente” no título deste artigo? Isso não é apenas adiar o inevitável? Por que não realizar uma migração completa de uma só vez?

Esses são pontos válidos e, em alguns casos, podem até ser os mais aconselháveis. No entanto, estou assumindo que você tem um projeto um pouco grande, grande o suficiente para que o uso de um codemod não funcione (ou exigirá muita solução alternativa).

Ou talvez você trabalhe em uma parte específica de um aplicativo em uma equipe maior e queira executar um piloto antes de fazer a grande mudança.

Em todos os casos, existem cenários válidos em que se tomaria primeiro a estrada de precaução. E mesmo que você encontre um monte de codemods ou métodos de migração que afirmam ser perfeitos, a realidade é que, se o seu projeto tiver alguma complexidade, pode não ser tão fácil quanto eles pregam.

No entanto, para oferecer um contraponto, o pessoal da Stripe parece discordar de mim. Eles publicaram recentemente um artigo alegando ter migrado milhões de linhas de código para o TypeScript. Se você está se sentindo aventureiro, vale a pena conferir!

Como configurar o TypeScript em um aplicativo Gatsby existente

Tudo bem, para o experimento de hoje, vamos supor que você já tenha um aplicativo Gatsby e queira realizar uma migração gradual.

Lembre-se que se você está criando um novo projeto hoje, o Gatsby já suporta TypeScript como linguagem principal desde o início. Infelizmente, esse não é o caso da maioria dos projetos que foram inicializados em versões mais antigas do Gatsby, então vamos seguir um caminho diferente.

A documentação do Gatsby já apresenta um bom guia de como migrar . No entanto, existem alguns ajustes que precisamos fazer para colocá-lo em funcionamento sem problemas.

Altere seus arquivos .js para .tsx

A parte mais fácil é alterar todos os componentes que você deseja migrar para .tsx ou criar novos neste formato. Nenhum trabalho é necessário do lado de Gatsby para que isso funcione! Isso é muito legal.

Instalar dependências

Existem, no entanto, algumas bibliotecas a serem instaladas. Certifique-se de adicioná-los ao seu devDependencies:

$ npm i –save-dev @types/node @types/react @types/react-dom typescript 

Gerar.tsconfig

O TypeScript possui um arquivo de configuração chamado .tsconfig, que é altamente personalizável e varia de projeto para projeto. No entanto, há algumas mudanças específicas que precisamos fazer para permitir que o TypeScript e o JavaScript coexistam em harmonia, pois esse é um requisito para que todos adotem o TS gradualmente.

Um exemplo de trabalho .tsconfigé o seguinte. Certifique-se de adicioná-lo à pasta raiz do seu projeto:

{
  "compilerOptions": {
    "target": "es2016",
    "jsx": "react",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "exclude": ["node_modules", "public", ".cache"]
}

Você também pode verificar um exemplo neste repositório público no GitHub .

Algumas das configurações necessárias são as seguintes:

  • Adicione "jsx": "react" para garantir que o compilador saiba que estamos em um projeto React
  • Definir allowJs: true; uma vez que JavaScript e TypeScript precisam coexistir, esse sinalizador deve ser ativado
  • Adicionar outDir: "./dist", o que deixa o VS Code feliz e evita erros indesejados

Declarando globais

Se você chegou até aqui, já tem a maior parte de sua configuração funcionando. No entanto, ainda existem algumas arestas.

O mais óbvio é sobre os módulos CSS; Gatsby trabalha com módulos CSS por padrão e precisamos deixar o TypeScript ficar feliz com isso. Se você usar SVGs como componentes conforme descrito aqui , isso também será útil.

Na srcpasta do seu projeto, crie um arquivo chamado globals.d.tse adicione o seguinte:

declare o módulo "*.module.css"; declare o módulo "*.module.scss"; declare module "*.svg" { const content: string; exportar conteúdo padrão; }

Isso garantirá que CSS e SVG sejam tratados e tratados como módulos .

Novamente, você pode verificar um exemplo funcional no GitHub .

Se você estiver usando o ESLint, ele pode reclamar de arquivos .d.ts. Nesse caso, você pode desabilitar o linter nessas extensões .

Digitando usando tipos de prop

Uma das principais vantagens do TypeScript é permitir a digitação estática em JavaScript. Ao desenvolver com React, isso é muito bem-vindo, pois dificulta adicionar props inexistentes ou até mesmo passar a variável errada.

Antes do TypeScript ser uma coisa, a equipe do React popularizou a verificação de tipos com tipos prop .

Os tipos de props eram um passo intermediário entre a não validação e a tipagem estrita. Com tipos de prop, os desenvolvedores podem listar todas as props em um determinado componente, seu tipo correspondente e se são opcionais ou obrigatórios.

Por exemplo, suponha que temos um componente que recebe um prop chamado magicNumber, que obviamente deve ter o número do tipo:

import PropTypes from 'prop-types'

const MyComponent = ({ magicNumber }) => { … } 

MyComponent.propTypes = {
  magicNumber: PropTypes.number.isRequired
} 

Suponha então que renderizamos, MyComponentmas esquecemos de passar magicNumbercomo prop, ou passamos uma string. Veríamos um aviso como este no console, quando no modo dev:

aviso no modo dev

No entanto, não haveria validação estática e é fácil ignorar esse tipo de erro em componentes maiores ou projetos maiores. Além disso, podemos adicionar um prop, mas esquecemos de definir seu tipo (existem alguns linters que ajudam com isso).

Usando a tipagem estática, você pode descontinuar os tipos prop em favor dos tipos regulares do TypeScript:

type Props = {
  magicNumber: number
}

const MyComponent = ({ magicNumber }: Props) => { … } 

Agora, se você tiver um componente .tsx que renderiza MyComponent, passar um prop com o tipo errado gerará um erro em tempo de compilação:

erro de tempo de compilação

E é isso! Mais seguro, mas menos detalhado, e vem com todos os benefícios de digitação. Em suma, os tipos de props funcionam, mas são menos poderosos do que uma estratégia de digitação robusta como o TypeScript. Se você quiser se aprofundar nesse assunto, recomendo que leia nosso artigo de visualização sobre o assunto: Comparando TypeScript e PropTypes em aplicativos React .

Se você está convencido de que a tipagem estática é superior aos tipos de prop, você também deve saber que há uma ressalva ao descartar tipos de prop em um projeto que é um híbrido de TypeScript e JavaScript.

Suponha que tenhamos um WithTypeScript.tsxcomponente que renderiza a versão TypeScript do MyComponent. Se tentarmos passar, magicNumber="Hello World"isso gerará um erro quando houver uma incompatibilidade de tipo, como visto acima.

No entanto, se WithTypeScript.tsxrecebe magicNumberde um componente pai escrito em JavaScript puro e o repassa para MyComponent.tsx, não há como validar se a variável é realmente um número. Uma vez que o componente pai não tenha digitação, nenhum erro estático será gerado. E como não há tipos de prop em MyComponent.tsx, nenhum erro de tempo de execução será gerado. Como tal, essa incompatibilidade de tipo não será levantada em nenhum lugar.

nenhum erro de tempo de execução

Observe como IndexPage.jschama um componente TypeScript WithTypeScript.tsxcom um tipo de prop errado. Nenhum aviso é visto no editor ou no console do navegador.

Tenha em mente que isso só acontece quando os componentes .js e .tsx estão se comunicando, o que inevitavelmente acontecerá se você estiver adotando gradualmente o TypeScript. Felizmente, há uma solução para isso: podemos ter o melhor dos dois mundos inferindo tipos de tipos de prop em componentes TypeScript. Dessa forma, mantemos os tipos de prop, mas os convertemos automaticamente em tipos usando a função InferPropsda biblioteca prop-types .

Isso seria MyComponent.tsxcombinar tipos e tipos de prop:

import React from "react";
import PropTypes, { InferProps } from "prop-types";

const Props = {
  magicNumber: PropTypes.number.isRequired,
};

type MyComponentTypes = InferProps<typeof Props>;

const MyComponent = ({ magicNumber }: MyComponentTypes) => { … };

MyComponent.propTypes = Props;

export default MyComponent;

Um exemplo completo pode ser visto aqui .

A solução acima gerará um erro estático em tempo de compilação se houver uma incompatibilidade de tipo, mas também gerará um erro de tempo de execução no console do navegador se o tipo errado for passado de um componente .js para um componente .ts ao longo do caminho. A desvantagem é que seu código se torna mais detalhado.

No entanto, se os componentes mais novos se comunicarem apenas com outros arquivos .ts, deve ser seguro descartar os tipos de prop. Eventualmente, quando a migração estiver concluída, você poderá removê-los completamente.

Conclusão

O TypeScript é uma ferramenta excepcional, mas alguns desenvolvedores evitam adotá-lo em uma base de código existente. Este artigo teve como objetivo elucidar como você pode fazer isso com segurança em seu projeto, neste momento, sem grandes alterações.

Embora o Gatsby em particular suporte arquivos .tsx prontos para uso, você precisa de algumas soluções alternativas para deixar seu compilador feliz considerando as abordagens típicas presentes nas bases de código do Gatsby. Declarar globais para módulos CSS e SVGs são pontos problemáticos comuns.

Por fim, ao ter JavaScript se comunicando com o TypeScript, não podemos garantir que alguns erros de digitação não sejam opacos. Por causa disso, podemos aproveitar a biblioteca prop-types e inferir os tipos, obtendo o melhor dos dois mundos até que estejamos seguros para descontinuar.

Todo o código e exemplos presentes neste artigo podem ser encontrados neste repositório no GitHub . De uma chance!

Fonte: https://blog.logrocket.com/incrementally-migrate-gatsby-app-typescript/

#Gatsby #typescript 

Como Migrar Incrementalmente Um Aplicativo Gatsby Para O TypeScript
高橋  花子

高橋 花子

1659009840

GatsbyアプリをTypeScriptに段階的に移行する方法

TypeScriptが日ごとに開発者の間でより多くの注目を集めていることは驚くべきことではありません。このテクノロジーを採用するコミュニティやプロジェクトの数だけでなく、それに対するサポートも大幅に拡大しています。

しかし、いつもそうだったわけではありません。Web開発者は以前、姿を消した最新のテクノロジーに悩まされてきました。コミュニティの一部が大きな変化に懐疑的であるのは当然のことです。実際、リンディー効果は、テクノロジーの一部が毎日存続し続けるほど、それがより長く存在すると予想されることを提案しています。

この記事の目的は、TypeScriptに移行するように説得することではありません。あなたがここにいるなら、JavaScriptのような動的言語での静的型付けの利点についてはすでに売りに出されていると思います。しかし、あなたが私のようであれば、移行を遅らせている可能性があり、移行を開始するために必要な作業量を恐れています。

まあ、もう恐れることはありません!私はあなたのために重労働をしました。この記事では、TypeScriptを段階的に採用する方法を学習します。これにより、スムーズな移行と、仕事の後のぐっすりと眠ることができます。

なぜ段階的に?

この記事のタイトルに「インクリメンタル」が含まれているのはなぜですか。それは避けられないことを遅らせるだけではありませんか?一度に完全な移行を実行してみませんか?

これらは有効なポイントであり、場合によっては、最も推奨されることもあります。ただし、codemodを使用しても機能しない(または回避策が多すぎる)ほど大きなプロジェクトがあると想定しています。

または、大規模なチームでアプリの特定の部分に取り組んでいて、大きな変更を行う前にパイロットを実行したい場合もあります。

すべての場合において、最初に注意の道を進むという有効なシナリオがあります。また、シームレスであると主張するコードモッドや移行方法がたくさんある場合でも、プロジェクトに複雑さが含まれていると、説教するほど簡単ではない可能性があります。

しかし、対位法を提供するために、Stripeの人々は私に同意しないようです。彼らは最近、数百万行のコードをTypeScriptに移行したと主張する記事を公開しました。あなたが冒険を感じているなら、それをチェックする価値があります!

既存のGatsbyアプリでTypeScriptを設定する方法

了解しました。今日の実験では、すでにGatsbyアプリがあり、段階的な移行を実行したいとします。

今日新しいプロジェクトを作成する場合、Gatsbyは最初からすでにTypeScriptをメイン言語としてサポートしていることを忘れないでください。残念ながら、古いバージョンのGatsbyでブートストラップされたほとんどのプロジェクトには当てはまらないため、別のルートを使用します。

Gatsbyのドキュメントには、移行方法に関する優れたガイドがすでに記載されています。ただし、スムーズに稼働させるために必要な調整がいくつかあります。

.jsファイルを.tsxに変更します

簡単なのは、.tsxに移行するすべてのコンポーネントを変更するか、この形式で新しいコンポーネントを作成することです。これが機能するためにギャツビー側で作業する必要はありません!それはかなりきちんとしています。

依存関係をインストールする

ただし、インストールするライブラリがいくつかあります。あなたがあなたのにそれらを追加することを確認してくださいdevDependencies

$ npm i –save-dev @types/node @types/react @types/react-dom typescript 

生成.tsconfig

TypeScriptには、と呼ばれる構成ファイルがあります.tsconfig。これは非常にカスタマイズ可能で、プロジェクトごとに異なります。ただし、TypeScriptとJavaScriptを調和させるために必要な特定の変更がいくつかあります。これは、すべての人がTSを徐々に採用するための要件であるためです。

動作例は以下の.tsconfigとおりです。プロジェクトのルートフォルダに必ず追加してください。

{
  "compilerOptions": {
    "target": "es2016",
    "jsx": "react",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "./dist",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  },
  "exclude": ["node_modules", "public", ".cache"]
}

GitHubのこの公開リポジトリで例を確認することもできます。

必要な構成の一部は次のとおりです。

  • 追加"jsx": "react" して、コンパイラがReactプロジェクトにいることを認識していることを確認します
  • セットallowJs: true; JavaScriptとTypeScriptを共存させる必要がある場合は、このフラグをオンにする必要があります
  • 追加outDir: "./dist"します。これにより、VS Codeが満足し、不要なエラーが防止されます。

グローバルの宣言

ここまで進んだら、セットアップのほとんどはすでに機能しています。ただし、まだいくつかの粗いエッジがあります。

最も明白なのはCSSモジュールについてです。GatsbyはデフォルトでCSSモジュールで動作するので、TypeScriptに満足させる必要があります。ここで説明するようにSVGをコンポーネントとして使用する場合、これも役立ちます。

プロジェクトのsrcフォルダーで、というファイルを作成しglobals.d.ts、以下を追加します。

モジュール"*.module.css"を宣言します。モジュール"*.module.scss"を宣言します。モジュール"*.svg" {const content:string;を宣言します。デフォルトのコンテンツをエクスポートします。}

これにより、CSSとSVGの両方がモジュールとして扱われ処理されるようになります

繰り返しになりますが、GitHubで実際の例を確認できます。

ESLintを使用している場合、.d.tsファイルについて文句を言うことがあります。この場合、そのような拡張機能でリンターを無効にすることができます。

小道具タイプを使用した入力

TypeScriptの主な利点の1つは、JavaScriptで静的型付けができることです。Reactで開発する場合、これは大歓迎です。存在しない小道具を追加したり、間違った変数を渡したりすることが難しくなるからです。

TypeScriptが登場する前は、Reactチームはprop型を使用した型チェックを普及させていました。

プロップタイプは、検証なしと厳密なタイピングの間の中間ステップでした。プロップタイプを使用すると、開発者は、特定のコンポーネント内のすべてのプロップ、それらに対応するタイプ、およびそれらがオプションか必須かを一覧表示できます。

たとえば、と呼ばれる小道具を受け取るコンポーネントがあるとします。magicNumberもちろん、タイプ番号は次のようになります。

import PropTypes from 'prop-types'

const MyComponent = ({ magicNumber }) => { … } 

MyComponent.propTypes = {
  magicNumber: PropTypes.number.isRequired
} 

次に、レンダリングするが、propとしてMyComponent渡すのを忘れるか、代わりに文字列を渡すとします。magicNumber開発モードの場合、コンソールに次のような警告が表示されます。

開発モードでの警告

ただし、静的な検証は行われず、より大きなコンポーネントやより大きなプロジェクトでは、この種のエラーを見落としがちです。また、小道具を追加することはできますが、そのタイプを設定するのを忘れます(ただし、それを支援するリンターがいくつかあります)。

静的型付けを使用すると、通常のTypeScript型を優先してprop型を非推奨にすることができます。

type Props = {
  magicNumber: number
}

const MyComponent = ({ magicNumber }: Props) => { … } 

ここで、レンダリングする.tsxコンポーネントがある場合MyComponent、間違ったタイプの小道具を渡すと、ビルド時にエラーが発生します。

ビルド時間エラー

以上です!より安全ですが、冗長性は低く、すべてのタイピングの利点があります。全体として、propタイプは機能しますが、TypeScriptのような堅牢なタイピング戦略ほど強力ではありません。このテーマについてさらに深く知りたい場合は、このテーマに関するプレビュー記事「ReactアプリケーションでのTypeScriptとPropTypeの比較」を読むことをお勧めします。

静的型付けが小道具型よりも優れていると確信している場合は、TypeScriptとJavaScriptのハイブリッドであるプロジェクトで小道具型を捨てるときに注意点があることも知っておく必要があります。

WithTypeScript.tsxTypeScriptバージョンのをレンダリングするコンポーネントがあるとしますMyComponent。上記のように、型の不一致があると、これを渡そうとするとmagicNumber="Hello World"エラーが発生します。

ただし、純粋なJavaScriptで記述された親コンポーネントからWithTypeScript.tsxを受け取り、それをに渡す場合、変数が実際に数値であるかどうかを検証する方法はありません。親コンポーネントに入力がない場合、静的エラーは発生しません。また、にはpropタイプがないため、ランタイムエラーは発生しません。そのため、このタイプの不一致はどこにも発生しません。magicNumberMyComponent.tsxMyComponent.tsx

ランタイムエラーなし

間違ったpropタイプでIndexPage.jsTypeScriptコンポーネントを呼び出す方法に注意してください。WithTypeScript.tsxエディターにもブラウザーコンソールにも警告は表示されません。

これは、.jsコンポーネントと.tsxコンポーネントが通信しているときにのみ発生することに注意してください。これは、TypeScriptを徐々に採用している場合は必然的に発生します。幸いなことに、それに対する解決策があります。TypeScriptコンポーネントのprop型から型を推測することで、両方の長所を活かすことができます。InferPropsこのようにして、propタイプを保持しますが、prop-typesライブラリの関数を使用してそれらをタイプに自動的に変換します。

これはMyComponent.tsx、タイプと小道具タイプを組み合わせたものになります。

import React from "react";
import PropTypes, { InferProps } from "prop-types";

const Props = {
  magicNumber: PropTypes.number.isRequired,
};

type MyComponentTypes = InferProps<typeof Props>;

const MyComponent = ({ magicNumber }: MyComponentTypes) => { … };

MyComponent.propTypes = Props;

export default MyComponent;

完全な例はここで見ることができます

上記のソリューションでは、タイプの不一致がある場合、ビルド時に静的エラーが発生しますが、途中で間違ったタイプが.jsから.tsコンポーネントに渡されると、ブラウザーコンソールでランタイムエラーが発生します。欠点は、コードがより冗長になることです。

ただし、新しいコンポーネントが他の.tsファイルとのみ通信する場合は、propタイプを破棄しても安全です。最終的に、移行が完了したら、それらを完全に削除できます。

結論

TypeScriptは例外的なツールですが、一部の開発者は既存のコードベースでの採用を控えています。この記事は、大きな変更を加えることなく、現在プロジェクトで安全にそれを行う方法を解明することを目的としています。

Gatsbyは特に.tsxファイルをすぐにサポートしますが、Gatsbyコードベースに存在する一般的なアプローチを考慮して、コンパイラーを満足させるためのいくつかの回避策が必要です。CSSモジュールとSVGのグローバルを宣言することは、一般的な問題点です。

最後に、JavaScriptをTypeScriptと通信させることにより、一部の入力エラーが不透明にならないことを保証できません。そのため、prop-typesライブラリを活用して型を推測し、非推奨になるまで両方の長所を活用できます。

この記事にあるすべてのコードと例は、GitHubのこのリポジトリにあります。試してみる!

ソース:https ://blog.logrocket.com/incrementally-migrate-gatsby-app-typescript/

#Gatsby #typescript 

GatsbyアプリをTypeScriptに段階的に移行する方法