1675656264
Build a complete ecommerce website from scratch, In this video we will cover all important topics of react js such as jsx, components, props, state, lifecycle of components, conditional rendering, lists, keys, context api & more. At the end of this tutorial you would have a fully functional ecommerce website which you can use for your own business or you can sell out if to the others.
In this tutorial you’ll learn:
- React 18 and its latest features
- React functional components and their reusability
- React hooks and state management
- How to use Context API
- Advance concepts or Context API
- Rapid UI building with SCSS
- Most important concepts of SCSS
- Mobile first responsive approach
- How to use Strapi Headless CMS
- CRUD Operations in Strapi
- Functional Programming through utility methods
- How to use Axios in react app
- How to integrate Stripe payment gateway
👇 Time Stamps
00:00:00 Intro & Project Demo
00:03:58 Project Setup & Walkthrough of Folder Structure
00:08:39 React Router DOM Setup
00:19:21 Header Section
00:58:05 Homepage Hero Banner Section
01:19:38 Newsletter Section
01:34:35 Footer Section
01:59:28 Homepage Popular Products Section
02:13:58 Category Page
02:23:16 Product Details Page
02:49:04 Related Products for Product Details Page
02:52:07 Shopping Cart
03:30:35 Search Product Modal
03:50:22 Strapi Integration & Walkthrough
04:06:00 API Testing
04:17:20 API Setup for Homepage Categories & Products Section
04:28:17 Homepage Categories API Integration
04:31:24 Homepage Products API Integration
04:34:40 Category Page API Integration
04:52:53 Product Details Page API Integration
05:12:28 Product Details Page Related Products API Integration
05:17:17 Shopping Cart Functionality
05:50:03 Live Search Functionality
05:59:20 Stripe Payment Gateway Integration
⭐ React - https://reactjs.org/docs/getting-started.html
⭐ Strapi - https://strapi.io/
⭐ Stripe - https://stripe.com/en-in
📚 Materials/References:
GitHub Repository Client (give it a star ⭐): http://bit.ly/3hBeEjc
GitHub Repository Api (give it a star ⭐): http://bit.ly/3v12SSo
Gist: http://bit.ly/3jfyZuU
Assets: http://bit.ly/3jcQYlD
Products: http://bit.ly/3FOpUAy
Installed NPM Packages:
Axios - https://www.npmjs.com/package/axios-react
React Router DOM - https://www.npmjs.com/package/react-router-dom
React Icons - https://www.npmjs.com/package/react-icons
Download node 16 LTS version: https://drive.google.com/file/d/1CbEP6fQHqLLKgPMm-7yabGnwNyHagayn/view?usp=sharing
Subscribe: https://www.youtube.com/@jsdevhindi/featured
1669435680
00:00 Introduction
05:36 Installation
07:12 React Router Dom v6.4 Tutorial
14:05 React Navbar Design
25:46 React Footer Design
32:11 React Slider Tutorial (without any library)
44:00 Featured Products and Product Card Design
55:21 Grid System Using CSS Flexbox
01:09:13 React Product List Page Design
01:21:07 React Single Product Page Design
01:34:00 React Shopping Cart Design
01:43:15 Strapi Tutorial for Beginners
01:56:20 React Strapi E-commerce App (Connection)
02:07:56 React Strapi E-commerce App (Fetching Items)
02:17:35 React Strapi Rest Api Filtering Tutorial
02:28:35 React E-commerce Fetch a Single Product
02:31:26 React Redux Shopping Cart Tutorial
02:27:40 React Redux Toolkit How to Persist State
02:50:05 Strapi Stripe Payment Using a React App
03:11:40 How to Deploy React app to a Shared Hosting?
03:13:22 How to Deploy Strapi app to a VPS Server?
03:30:15 Outro
Source Code:
https://github.com/safak/youtube2022/tree/e-commerce ( Coming soon (updating files) )
Deployment source:
https://github.com/safak/youtube/tree/mern-deployment
#react #strapi #stripe #programming #developer #morioh #softwaredeveloper #computerscience #webdev #webdeveloper #webdevelopment
1660878420
This is a boilerplate for building applications using Strapi and Next.js. This boilerplate consists of the following:
This boilerplate is built using the following technologies:
It supports GraphQL Query and Mutation out of the box.
This application is the primary user-facing application. Once it’s up and running (see Development section), it’s available on http://localhost:3000/.
Strapi is the leading open-source headless CMS. It’s 100% Javascript, fully customizable and developer-first.
git clone https://github.com/ghoshnirmalya/nextjs-strapi-boilerplate
cd frontend && yarn install
We might need to run the following command:
source .env
Create a new Google OAuth Client and copy the credentials (Client ID and Client Secret) in your .env file.
From the frontend directory, we can run the following command to start our Next.js frontend application:
yarn dev
The above command will start the frontend application on http://localhost:3000/.
cd backend
docker-compose up
We need to start Docker and then run the above command which will change the current directory to the backend package’s directory and then start the backend package. If everything goes well, it’ll be up and running on http://localhost:1337/graphql.
a. Allow permissions for all operations on the Feed content-type for Authenticated users.
b. Allow permissions for all operations on the Feed content-type for Authenticated users as well.
c. Enable the Google provider.
d. Click on the "Done" button and now we can log into our Next.js application using our Google account.
Click on the button below to deploy the frontend application on Vercel. You'll need to sign up for a free Vercel account.
We're still working on it.
Author: ghoshnirmalya
Source code: https://github.com/ghoshnirmalya/nextjs-strapi-boilerplate
License: MIT license
#nextjs #react #reactjs #javascript #strapi
1659443361
Tìm hiểu cách tạo cửa hàng thương mại điện tử Jamstack bằng Gatsby và Strapi. Chúng tôi sẽ xây dựng một cửa hàng giày trực tuyến với cách tiếp cận từng bước.
Hãy bắt đầu với một câu hỏi: Khi xây dựng một trang web hoặc ứng dụng trong thời đại ngày nay, những điều chính chúng ta cần xem xét là gì?
Có rất nhiều câu trả lời tiềm năng cho câu hỏi này, nhưng speed
, cost
và security
nên làm nổi bật bất kể chúng tôi đang xây dựng cái gì. Cho dù đó là một trang blog, trang web cá nhân hay cổng thương mại điện tử, người dùng của chúng tôi sẽ mong đợi nó tải nhanh, duy trì và bảo mật không tốn kém cho người dùng cuối.
Rất may, kiến trúc Jamstack có thể giúp chúng tôi trên cả ba khía cạnh.
Jamstack cho phép chúng tôi xây dựng các trang web tĩnh bằng cách sử dụng các đánh dấu dựng sẵn, API không máy chủ… thậm chí cả dữ liệu từ CMS. Các trang web tĩnh này nhanh hơn so với lựa chọn thay thế, vì các đánh dấu được tạo sẵn và phân phát an toàn từ một CDN bảo mật (thay vì máy chủ gốc).
Và có cả một hệ sinh thái công nghệ hỗ trợ việc tạo các ứng dụng Jamstack. Trong bài viết này, chúng tôi sẽ đề cập đến hai công nghệ nổi tiếng nhất trong số những công nghệ này: Gatsby
và Strapi.
Chúng tôi sẽ sử dụng chúng để xây dựng một ứng dụng Thương mại điện tử - một cửa hàng giày trực tuyến được gọi là shoes.
Original, đúng không?
Gatsby là một trình tạo trang web tĩnh dựa trên React được thiết kế đặc biệt để tạo các đánh dấu dựng sẵn và cung cấp một nền tảng đám mây thống nhất để xây dựng, xem trước và lưu trữ các ứng dụng của bạn. Nó siêu nhanh, dễ dàng tích hợp với nhiều nguồn dữ liệu khác nhau và đi kèm với rất nhiều hệ sinh thái plug-in.
Mặt khác, Strapi là một ứng dụng mã nguồn mở, có khả năng tùy biến cao giúp bạn xây dựng các API nhanh hơn và quản lý nội dung của mình một cách dễ dàng. Bất kỳ ứng dụng khách front-end nào cũng có thể sử dụng các API bằng REST hoặc GraphQL và bạn có thể tự lưu trữ ứng dụng Strapi một cách dễ dàng trên một nhà cung cấp như Heroku.
Hai chương trình kết hợp hoàn hảo với nhau: trong khi Gatsby cung cấp giao diện người dùng nhanh hơn, Strapi giải quyết nhu cầu về hệ thống quản lý nội dung và kho dữ liệu phía sau (CMS).
Được rồi, bây giờ bạn đã biết Gatsby và Strapi có thể cung cấp những gì, hãy xem cách chúng hoạt động trong thực tế bằng cách xây dựng shoes
ứng dụng.
shoes
ứng dụngChúng tôi sẽ chia shoes
ứng dụng thành hai phần chính:
datastore
: Điều này yêu cầu Strapi
dự án, với tất cả nội dung và API cần thiết cho ứng dụng.client
: Điều này dựa vào Gatsby
dự án sử dụng các API, với sự trợ giúp của GraphQL, để tìm nạp nội dung từ Strapi và hiển thị nội dung đó trong các giao diện người dùng đẹp mắt.Đầu tiên, chúng tôi sẽ thiết lập datastore
bằng cách sử dụng Strapi. Xin lưu ý rằng bạn phải cài đặt Node.js để chạy ứng dụng cục bộ. Bạn cũng có tùy chọn cài đặt sợi , nhưng nếu bạn không có sợi, vui lòng sử dụng npm
thay thế.
datastore
sử dụngStrapi
Strapi cung cấp một loạt các mẫu để bắt đầu ứng dụng một cách nhanh chóng. Vì cửa hàng giày của chúng tôi là một ứng dụng thương mại điện tử, chúng tôi sẽ sử dụng ecommerce
mẫu để tạo datastore
.
Để thực hiện việc này, chỉ cần tạo một shoes
thư mục và mở dấu nhắc lệnh (hoặc thiết bị đầu cuối) trên thư mục giày.
Bây giờ, sử dụng lệnh sau để tạo một dự án Strapi:
yarn create strapi-app datastore --template ecommerce
Xin lưu ý rằng chúng tôi đã cung cấp tên dự án datastore
và mẫu như ecommerce
trong lệnh trên.
Lệnh sẽ mất một lúc để tải xuống các phụ thuộc cần thiết, cài đặt chúng và thiết lập chúng cho bạn. Tuy nhiên, sau khi hoàn tất, ứng dụng Strapi sẽ có thể truy cập được trên trình duyệt của bạn bằng cách sử dụng URL [localhost:1337](http://localhost:1337)
.
Điều quan trọng cần nhớ là bạn cần đăng ký hồ sơ của mình lần đầu tiên để tạo thông tin đăng nhập. Những thông tin đăng nhập tương tự này sẽ được sử dụng để xác thực trong Strapi, vì vậy vui lòng dành thời gian để điền vào các chi tiết bắt buộc và đăng ký.
Sau khi đăng ký, bạn sẽ đến trang chào mừng của Strapi. Điều này sẽ cung cấp cho bạn các gợi ý hướng dẫn bạn cần để tạo cấu trúc nội dung, tham gia cộng đồng và hoàn thành nhiều chức năng khác.
Bây giờ chúng ta sẽ bắt đầu tạo types
trong Strapi. Bạn có thể coi các loại này như là các bảng có lược đồ trong cơ sở dữ liệu quan hệ.
Đối với ứng dụng của chúng tôi, chúng tôi muốn tạo dữ liệu giày dưới dạng một Product
loại. Mỗi sản phẩm giày sẽ có thông tin meta riêng, như tên, giá cả, mô tả, cổ phiếu, danh mục và công ty.
Chúng tôi cũng sẽ quản lý Category
và Company
với tư cách là các loại độc lập, và tạo mối quan hệ với Product
loại.
Vì vậy, chúng ta hãy bắt đầu tạo từng loại một. Đầu tiên, hãy tạo các trường sau cho Category
loại:
Tương tự, bạn có thể tạo loại Công ty với các trường tên và slug.
Và bây giờ chúng ta sẽ tạo Loại sản phẩm, với các trường được hiển thị trong hình dưới đây.
Hầu hết các trường ở trên là tự giải thích. Tuy nhiên, một số lĩnh vực cần giải thích.
Media
. Trong Strapi, bạn có thể tải nội dung (hình ảnh, video, tệp) lên thư viện phương tiện để sử dụng sau này.Vì tất cả các kiểu bắt buộc hiện đã được tạo, chúng ta có thể bắt đầu tạo dữ liệu mẫu trong Strapi. Đầu tiên, chúng ta hãy tải lên một số hình ảnh giày mát mẻ. Bạn có thể thu thập chúng từ một trang web truyền thông như unsplash
và tải lên các mục từ Media Library
menu.
Tiếp theo, duyệt qua tùy chọn Trình quản lý nội dung từ điều hướng bên trái và bắt đầu tạo các mục nhập cho loại Danh mục. Bạn có thể tạo các danh mục được đề cập trong hình ảnh bên dưới hoặc thoải mái tạo danh mục của riêng bạn.
Tương tự, hãy chèn các mục nhập cho dữ liệu Công ty.
Cuối cùng, nhập dữ liệu cho Loại sản phẩm.
Cho đến nay, chúng tôi đã tạo tất cả nội dung bắt buộc trong Strapi và sắp sử dụng tất cả các phần tử trong giao diện người dùng, với các API của Strapi. Bạn có thể truy cập các API Strapi bằng cách sử dụng REST đến GraphQL, nhưng hãy nhớ rằng bạn cần lấy Mã thông báo API để thực hiện các lệnh gọi API thành công.
Nhấp vào Cài đặt> Cài đặt chung> Mã thông báo API từ thanh điều hướng bên trái và nhấp vào Create new API Token
nút để tạo mã thông báo toàn quyền truy cập cho ứng dụng giày. Vui lòng giữ mã thông báo này an toàn với bạn, vì chúng tôi sẽ sớm sử dụng mã thông báo này.
client
sử dụngGatsby
Chúng tôi đã thiết lập thành công datastore
với Strapi, và bây giờ đã đến lúc thiết lập client
bên với Gatsby
.
Để làm như vậy, hãy mở một dấu nhắc lệnh / thiết bị đầu cuối khác tại thư mục gốc của dự án và thực hiện lệnh sau.
yarn global add gatsby-cli
Lệnh này sẽ cài đặt Giao diện dòng lệnh Gatsby (CLI) trên toàn cầu. Điều này giúp chúng tôi tương tác với khung Gatsby để thực hiện các tác vụ khác nhau.
Cũng giống như Strapi, Gatsby đi kèm với một số mẫu để tạo một dự án. Trong thế giới Gatsby, chúng được gọi là 'mẫu khởi động'. Chúng tôi sẽ sử dụng mẫu khởi động mặc định để tạo dự án và đặt tên client
.
Vui lòng thực hiện lệnh sau để tạo dự án Gatsby.
npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default
Lệnh trên sẽ mất một lúc và tạo cấu trúc dự án cho bạn. Bây giờ thay đổi thư mục client
và khởi động ứng dụng cục bộ bằng gatsby develop
lệnh.
cd client
gatsby develop
Ứng dụng Gatsby sẽ chạy trên [localhost:8000](http://localhost:8000)
URL và bạn sẽ thấy giao diện người dùng như thế này khi truy cập bằng trình duyệt của mình. Đó là một trang mặc định từ mẫu ban đầu mà chúng tôi đã sử dụng. Chúng tôi sẽ thay đổi nó sớm.
Vì vậy, bây giờ chúng tôi sẽ kết hợp Gatsby và Strapi lại với nhau để tạo hình dạng cho ứng dụng của chúng tôi. Chúng tôi sẽ gọi các API Strapi từ Gatsby và tìm nạp dữ liệu giày tại thời điểm xây dựng.
Hệ sinh thái trình cắm thêm Gatsby có một trình cắm thêm nguồn được gọi là gatsby-source-strapi
giúp tìm nạp dữ liệu từ Strapi bằng cách sử dụng GraphQL. Hãy cài đặt plug-in đó và một số phụ thuộc khác để xử lý hình ảnh và chuyển đổi. Vui lòng thực hiện lệnh sau từ thiết bị đầu cuối trong thư mục client
.
yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp
Tạo một tệp được gọi là thư mục .env.development
gốc client
, với nội dung sau.
STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337
Đây <STRAPI-API-TOKEN>
là mã thông báo bạn đã sao chép trong khi thiết lập kho dữ liệu Strapi. Bây giờ bạn có thể nhập client
dự án trong trình soạn thảo mã yêu thích của mình (như Mã VS trong trường hợp của tôi).
Bây giờ, hãy mở gatsby-config.js
tệp và thay thế nội dung bằng nội dung bên dưới. Đây là tệp cấu hình xác định siêu dữ liệu của trang web và các tùy chọn trình cắm.
Hãy xem xét kỹ hơn các tùy chọn mà chúng tôi đã xác định cho gatsby-source-strapi
trình cắm: chúng tôi đã chỉ định URL API Strapi, Mã thông báo API và tên của các loại bộ sưu tập mà chúng tôi muốn tương tác.
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `Shoes`,
description: `The one stop shop for your shoes and footwear needs.`,
author: `@tapasadhikary`,
siteUrl: `https://shoes.io/`,
},
plug-ins: [
"gatsby-plugin-gatsby-cloud",
{
resolve: "gatsby-source-strapi",
options: {
apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
accessToken: process.env.STRAPI_TOKEN,
collectionTypes: [
{
singularName: "product",
},
{
singularName: "company",
},
{
singularName: "category",
},
],
},
},
"gatsby-plugin-image",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
"gatsby-transformer-remark",
],
}
Vui lòng dừng và khởi động lại gatsby develop
chức năng và truy cập URL http://localhost:8000/__graphql
để mở trình khám phá GraphQL của Gatsby.
Gatsby cung cấp trình khám phá GraphQL như một công cụ dành cho nhà phát triển, vì vậy bạn có thể xây dựng các truy vấn GraphQL một cách dễ dàng. Bạn nên tìm tất cả các loại bộ sưu tập Strapi từ Explorer
cột ngoài cùng bên trái: tất cả chúng đều bắt đầu bằng văn bản allStrapi
.
Được rồi, bây giờ chúng ta hãy thử tạo một truy vấn mẫu cho allStrapiProduct
bộ sưu tập. Bạn có thể mở rộng bộ sưu tập và chọn các trường mà bạn muốn tìm nạp dữ liệu; bạn sẽ thấy một truy vấn GraphQL được tạo tự động, dựa trên lựa chọn của bạn.
Bây giờ bạn có thể chạy truy vấn bằng cách nhấn vào nút 'chạy' trong tiêu đề của bảng điều khiển ở giữa. Bạn có thể tìm thấy đầu ra ở bảng ngoài cùng bên phải.
Tôi khuyên bạn nên dành một chút thời gian với trình khám phá GraphQL và thử với các truy vấn để làm quen với nó.
Để xây dựng các truy vấn GraphQL, chúng tôi sẽ sử dụng chúng để tạo các thành phần giao diện người dùng. Gatsby dựa trên React, vì vậy bạn có thể sử dụng toàn bộ sức mạnh của thư viện React trong Gatsby. Chỉ cần mở index.js
tệp và thay thế nội dung hiện có bằng mã sau.
// index.js
import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"
import { useStaticQuery, graphql } from "gatsby"
import '../style/shoes.css'
const IndexPage = () => {
const { allStrapiProduct } = useStaticQuery(graphql`
query {
allStrapiProduct(sort: {order: ASC, fields: title}) {
edges {
node {
image {
url
}
slug
price
title
id
stock
status
}
}
}
}
`)
return (
<Layout>
<Seo title="Home" />
<ShoeList shoes={allStrapiProduct.edges} />
</Layout>
)
}
export default IndexPage
Bây giờ chúng ta hãy đi sâu vào mã trong index.js
tệp. Chúng tôi sử dụng truy vấn GraphQL để tìm nạp tất cả các sản phẩm được sắp xếp theo tiêu đề sản phẩm theo thứ tự tăng dần. Gatsby cung cấp cho chúng ta một móc React được gọi useStaticQuery
để thực hiện truy vấn GraphQL.
Tiếp theo, chúng ta chuyển mảng sản phẩm đã tìm nạp (giày) làm chỗ dựa cho ShoeList
thành phần. Chúng ta cần tạo thành phần sẽ lặp lại trên shoes
mảng và bắt đầu tạo bố cục thẻ cho từng chi tiết giày.
Để thực hiện việc này, vui lòng tạo một tệp có tên ShowList.js
dưới components
thư mục với nội dung sau.
// ShoeList.js
import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
console.log(shoes);
return (
<div className="shoe-list">
{shoes.map((shoe) => (
<ShoeCard key={shoe.node.id} shoe={shoe.node} />
))}
</div>
)
}
export default ShoeList
Như bạn nhận thấy trong đoạn mã trên, chúng tôi lấy ra từng chi tiết giày và chuyển chúng làm đạo cụ cho một thành phần khác, ShoeCard. Vì vậy, bạn cần tạo một tệp có tên ShoeCard.js
dưới components
thư mục, với nội dung như sau.
// ShoeCard.js
import * as React from "react"
import { Link } from "gatsby"
const ShoeCard = ({ shoe }) => {
return (
<Link
to={`/${shoe.slug}`}
className="shoe-card" >
<div className="img-container">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="details">
<h2>{shoe.title} - ${shoe.price}</h2>
</div>
</Link>
)
}
export default ShoeCard
Thành phần ShoeCard hiển thị hình ảnh, tiêu đề và giá của giày. Sau đó, chúng tôi sẽ chỉ tiết lộ tiêu đề và giá khi người dùng di chuột qua hình ảnh chiếc giày bằng các kiểu CSS.
Ngoài ra, hãy lưu ý rằng thẻ giày được bọc bằng a Link
. Thành phần Liên kết đến từ Gatsby và giúp chúng tôi liên kết giữa các trang trong ứng dụng Gatsby. Thành phần Liên kết có một thuộc tính mà chúng tôi sử dụng để liên kết đến trang đích. Trong ví dụ trên, giá trị thuộc tính là giá trị slug của mỗi chiếc giày.
Chúng tôi dự định chuyển sang một trang mới khi người dùng nhấp vào thẻ giày; trang mới này sẽ hiển thị thêm chi tiết về một đôi giày và các tùy chọn mua. Nhưng chúng tôi cần thực hiện một số thay đổi và chúng tôi sẽ thực hiện điều đó sau. Đầu tiên, chúng ta cần tập trung vào việc chuẩn bị trang danh sách giày với tất cả các kiểu dáng.
Hãy tinh chỉnh Bố cục và các thành phần Header một chút. Đầu tiên, thay thế nội dung của layout.js
tệp bằng nội dung sau. Nó khá giống với tệp layout.js hiện có đi kèm với mẫu, nhưng chúng tôi đã thực hiện một số chỉnh sửa nhỏ về kiểu dáng.
// layout.js
import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Header from "./header"
import "./layout.css"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<Header siteTitle={data.site.siteMetadata?.title || `Title`} />
<div className="container">
<main className="content">{children}</main>
<footer>
© {new Date().getFullYear()} · Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
Đây là nội dung của Header.js
tệp bạn cần thay thế trong tệp hiện có.
// Header.js
import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"
const Header = ({ siteTitle }) => (
<header>
<Link to="/" className="logo">
👠 {siteTitle}
</Link>
</header>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
Bây giờ, chúng ta hãy tạo một style
thư mục trong thư mục src
. Để làm như vậy, hãy tạo một shoes.css
tệp trong style
thư mục với nội dung sau.
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");
*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: border-box;
scroll-behavior: smooth;
}
html {
overflow: auto;
}
body {
height: 100vh;
background-color: rgb(3, 28, 34);
color: #ffffff;
font-family: "Poppins", sans-serif;
}
a {
text-decoration: none;
color: #ffffff;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #282d2e;
padding-left: 0.5rem;
padding-right: 0.5rem;
margin: 0 0 0.5rem 0;
}
header .logo {
font-size: 2rem;
font-weight: 500;
color: #ffffff;
padding: 0.5rem;
}
footer {
width: 100%;
padding: 0.3rem;
background-color: #282d2e;
text-align: center;
}
footer > a {
color: #1af41a;
text-decoration: underline;
}
.btn {
padding: 10px;
cursor: pointer;
font-size: 18px;
border: none;
border-radius: 10px;
}
.btn.btn-primary {
background-color: #40ee10;
color: #000000;
}
.btn.btn-primary:hover {
background-color: #70e007;
color: #000000;
}
.btn.btn-secondary {
background-color: #ffffff;
color: #282d2e;
}
.btn.btn-secondary:hover {
background-color: #282d2e;
color: #ffffff;
}
.container {
height: calc(100vh - 73px);
overflow: hidden;
display: flex;
flex-direction: column;
}
.content {
flex-grow: 1;
overflow: auto;
}
.shoe-list {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.shoe-card {
position: relative;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
width: 15rem;
height: 15rem;
margin: 1.2rem;
}
.shoe-card .img-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
transition: all 0.5s ease-in-out;
}
.shoe-card .img-container > IMG {
width: 15rem;
height: 15rem;
object-fit: cover;
resize: both;
border-radius: 10px;
}
.shoe-card:hover .img-container {
transform: translate(-1rem, -1rem);
}
.shoe-card:hover .details {
transform: translate(1rem, 1rem);
}
.shoe-card .details {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 0.5rem;
display: flex;
background-color: #fff;
z-index: 1;
align-items: flex-end;
transition: 0.5s ease-in-out;
line-height: 1rem;
border-radius: 10px;
}
.shoe-card .details h2 {
display: block;
font-size: 1rem;
color: #000000;
font-weight: 500;
}
Và… đó là nó!
Bây giờ chạy ứng dụng cục bộ bằng cách sử dụng URL [http://localhost:8000](http://localhost:8000)
và bạn sẽ thấy danh sách hình ảnh chiếc giày trên trang. Di chuột qua các hình ảnh giày và một hình ảnh động sẽ hiển thị tên giày và giá.
Thật tuyệt. Vì vậy, bây giờ, hãy thử nhấp vào bất kỳ thẻ giày nào.
Oái oăm! bạn nhận được một trang như dưới đây, và nó có vẻ bị hỏng. Nó đã cố gắng điều hướng đến một trang được xác định bởi giá trị slug của chiếc giày, nhưng không thành công.
Nhưng đừng lo lắng, chúng tôi có thể khắc phục sự cố.
Gatsby có thể tạo các trang tại thời điểm xây dựng bằng cách sử dụng các mẫu. Các cấu trúc này khai thác cùng một cấu trúc giao diện người dùng mà bạn muốn sử dụng cho một tập dữ liệu khác.
Ví dụ: trong shoes
ứng dụng của chúng tôi, chúng tôi muốn hiển thị chi tiết của từng đôi giày. Cấu trúc trang chi tiết sẽ giống nhau, nhưng dữ liệu về giày sẽ thay đổi tùy thuộc vào hình ảnh giày mà chúng ta đang nhấp vào.
Vì vậy, chúng ta có thể tạo một mẫu có tên shoe-details.js
dưới src/templates
thư mục với nội dung như sau.
// shoe-details.js
import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
export default function ShoeDetails({ data }) {
const shoe = data.strapiProduct
const [quantity, setQuantity] = useState(1)
return (
<Layout>
<div className="shoe-details">
<div className="cover">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="info">
<div className="info-heading">
<h2>{shoe.title}</h2>
<Link to={`/category/${shoe.categories[0].slug}`}>
<span>{shoe.categories[0].name}</span>
</Link> { ' '}
from {' '}
<Link to={`/company/${shoe.company.slug}`}>
{shoe.company.name}
</Link>
</div>
<div className="info-body">
<p>{shoe.description}</p>
<span>${shoe.price} per unit</span> { ' - '}
<>
{
shoe.stock > 0 ?
<span>{shoe.stock} In Stock</span> :
<span>Out of Stock</span>
}
</>
</div>
<div className="info-purchase">
{
shoe.stock > 0 ?
<>
<p>
I want to purchase {' '}
<input
type="number"
min="1"
max={shoe.stock}
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/> {' '} unit
</p>
<p className="price">Total Price: ${quantity * shoe.price}</p>
<button className="btn btn-primary">Add to Cart</button>
</> :
<>
<p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
<button className="btn btn-secondary">Notify Me!</button>
</>
}
</div>
</div>
</div>
</Layout>
)
}
export const query = graphql`
query($slug: String!) {
strapiProduct(slug: {eq: $slug}) {
id
title
price
status
stock
categories {
name
slug
}
company {
name
slug
}
description
image {
url
}
updatedAt
}
}
`
Trong đoạn mã trên, chúng tôi thực hiện truy vấn GraphQL để tìm nạp thông tin chi tiết của sản phẩm (giày) dựa trên giá trị slug.
Chúng tôi có thể sử dụng các chi tiết sản phẩm để xây dựng cấu trúc khi chúng tôi tìm nạp các chi tiết sản phẩm. Trong trường hợp này, cấu trúc bao gồm ảnh của sản phẩm và thông tin như danh mục, công ty, giá cả và kho. Trang này cũng bao gồm hộp số đầu vào để chỉ định số lượng giày cần thiết và tự động tính toán tổng số tiền phải trả cho một lần thanh toán.
Tất cả điều này là tuyệt vời, nhưng làm thế nào để chúng tôi lấy giá trị slug của giày và ánh xạ nó với shoe-details
mẫu? Hãy thử và làm điều đó ngay bây giờ.
Mở gatsby-node.js
tệp và thay thế nội dung bằng mã sau:
// gatsby-node.js
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allStrapiProduct {
edges {
node {
slug
}
}
}
}
`)
data.allStrapiProduct.edges.forEach(edge => {
const slug = edge.node.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/shoe-details.js`),
context: { slug: slug },
})
})
}
Gatsby chạy gatsby-node.js
tệp tại thời điểm xây dựng. Ở đây, chúng tôi tìm nạp các slugs cho tất cả các sản phẩm, vì vậy chúng tôi có thể tích hợp các slugs và tạo các trang cho từng sản phẩm.
Phương createPage
thức lấy một đối tượng làm đối số trong đó chúng tôi cung cấp chi tiết về đường dẫn được tham chiếu với slug và ánh xạ tới thành phần nào. Xin lưu ý rằng thành phần là tệp mẫu mà chúng ta đã thấy ở trên. Chúng tôi cũng truyền dữ liệu ngữ cảnh là chính slug.
Vì vậy, mỗi đường dẫn với giá trị slug bây giờ được ánh xạ tới tệp mẫu, với giá trị slug được truyền dưới dạng ngữ cảnh. Chúng tôi đã tìm hiểu cách thành phần mẫu sử dụng giá trị slug này và tìm nạp các chi tiết của sản phẩm. Tôi hy vọng tất cả các dấu chấm được kết nối tốt ngay bây giờ.
Bây giờ, hãy mở shoes.css
tệp và thêm các kiểu sau vào bên dưới những kiểu hiện có. Các phong cách sau đây dành cho trang chi tiết giày.
.shoe-details {
padding: 1rem;
display: flex;
justify-content: space-around;
align-items: center;
}
.shoe-details .cover {
display: flex;
align-content: center;
justify-content: center;
}
.shoe-details .cover > IMG {
width: 30rem;
height: 30rem;
border-radius: 50%;
}
.shoe-details .info-heading {
margin-bottom: 1rem;
}
.shoe-details .info-heading > a {
color: #1af41a;
text-decoration: underline;
}
.shoe-details .info-heading > H2 {
font-size: 3rem;
}
.shoe-details .info-body > P {
margin: 0;
}
.shoe-details .info-body > SPAN {
font-size: 1.5rem;
}
.shoe-details .info-purchase {
margin: 2rem 0 0 0;
border: 1px solid #4a4545;
border-radius: 5px;
padding: 1rem;
background-color: black;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.shoe-details .info-purchase .price {
font-size: 1.5rem;
font-weight: 500;
color: #ffffff;
}
.shoe-details .info-purchase INPUT {
border: 1px solid #ececec;
padding: 5px;
border-radius: 3px;
font-size: 1rem;
}
.shoe-filtered-list H2 {
font-size: 2rem;
font-weight: 500;
color: #1af41a;
margin: 0 0 1rem 1rem;
}
@media only screen and (max-width: 900px) {
.shoe-details {
padding: 1rem;
display: flex;
flex-direction: column;
justify-content: space-around;
}
}
@media only screen and (max-width: 600px) {
.shoe-details .cover > IMG {
width: 20rem;
height: 20rem;
}
}
Bây giờ khởi động lại máy chủ cục bộ của Gatsby và truy cập lại vào ứng dụng localhost:8000
. Nhấp vào bất kỳ thẻ giày nào; bạn sẽ thấy một trang thanh lịch, hiển thị với các chi tiết giày.
Được rồi, đó là tất cả những gì chúng tôi muốn xây dựng với Gatsby và Strapi: một cửa hàng giày Jamstack với một vài trang được phục vụ tĩnh. Và chúng tôi đã làm được!
Tuy nhiên, đừng lo lắng: bạn có thể đi xa hơn từ đây. Bạn có thể tạo mẫu cho các danh mục và công ty và có các trang cho từng danh mục. Bạn có thể phát triển các chức năng tìm kiếm và tạo các tùy chọn lọc cho giày theo tiêu đề, phạm vi giá, công ty và danh mục. Mã dự án là mã nguồn mở theo giấy phép MIT trên GitHub.
Như một bản tóm tắt nhanh, hãy xem video giới thiệu nhanh bên dưới. Đây là bản demo của shoes
ứng dụng mà chúng tôi đã xây dựng trong bài viết này, cùng với một số chức năng bổ sung được đề cập ở trên.
Liên kết: https://blog.greenTHER.info/build-your-ecommerce-store-using-gatsby-and-strapi
#ecommerce #gatsby #strapi #javascript
1659436105
Узнайте, как создать интернет-магазин Jamstack с помощью Gatsby и Strapi. Мы создадим интернет-магазин обуви поэтапно.
Давайте начнем с вопроса: при создании веб-сайта или приложения в наши дни, что нам нужно учитывать в первую очередь?
Что ж, на этот вопрос есть множество потенциальных ответов, но speed
, cost
, и security
должны занимать видное место независимо от того, что мы строим. Будь то блог-сайт, личный веб-сайт или портал электронной коммерции, наши пользователи ожидают, что он будет быстро загружаться, недорог в обслуживании и безопасен для конечных пользователей.
К счастью, архитектура Jamstack может помочь нам во всех трех аспектах.
Jamstack позволяет нам создавать статические веб-сайты, используя готовые разметки, бессерверные API… даже данные из CMS. Эти статические сайты работают быстрее, чем альтернативные, поскольку разметка предварительно создается и безопасно обслуживается с защищенного CDN (вместо исходного сервера).
И существует целая технологическая экосистема, поддерживающая создание приложений Jamstack. В этой статье мы рассмотрим две самые известные из этих технологий: Gatsby
и Strapi.
мы будем использовать их для создания приложения для электронной коммерции — интернет-магазина обуви под названием « shoes.
Оригинал», верно?
Gatsby — это генератор статических сайтов на основе React, специально разработанный для создания готовых разметки и предлагающий единую облачную платформу для создания, предварительного просмотра и размещения ваших приложений. Он очень быстрый, легко интегрируется с различными источниками данных и поставляется с множеством подключаемых экосистем.
Strapi, с другой стороны, представляет собой настраиваемое приложение с открытым исходным кодом, которое помогает вам быстрее создавать API и легко управлять своим контентом. Любой внешний клиент может использовать API-интерфейсы с помощью REST или GraphQL, и вы можете легко самостоятельно разместить приложение Strapi у поставщика, такого как Heroku.
Эти две программы прекрасно сочетаются друг с другом: в то время как Gatsby обеспечивает более быстрый внешний интерфейс, Strapi устраняет необходимость в внутреннем хранилище данных и системе управления контентом (CMS).
Хорошо, теперь вы знаете, что могут предложить Gatsby и Strapi, давайте посмотрим, как они работают на практике, создав shoes
приложение.
shoes
приложениемМы разделим shoes
приложение на две основные части:
datastore
: для этого требуется Strapi
проект со всем содержимым и API, необходимыми для приложения.client
: это зависит от Gatsby
проекта, который использует API с помощью GraphQL для извлечения контента из Strapi и отображения его в красивых пользовательских интерфейсах.Во-первых, мы datastore
настроим использование Strapi. Обратите внимание, что для локального запуска приложения у вас должен быть установлен Node.js. У вас также есть возможность установить пряжу , но если у вас нет пряжи, используйте npm
вместо нее .
datastore
_Strapi
Strapi предоставляет множество шаблонов для быстрого начала работы с приложением. Поскольку наш обувной магазин является приложением для электронной коммерции, мы будем использовать ecommerce
шаблон для создания файла datastore
.
Для этого просто создайте shoes
папку и откройте командную строку (или терминал) в каталоге обуви.
Теперь используйте следующую команду для создания проекта Strapi:
yarn create strapi-app datastore --template ecommerce
Обратите внимание, что мы указали имя проекта datastore
и шаблон, как ecommerce
в приведенной выше команде.
Команде потребуется некоторое время, чтобы загрузить необходимые зависимости, установить их и настроить для вас. Однако, как только это будет сделано, приложение Strapi будет доступно в вашем браузере по URL-адресу [localhost:1337](http://localhost:1337)
.
Также важно помнить, что вам необходимо зарегистрировать свой профиль в первый раз, чтобы создать свои учетные данные. Эти же учетные данные будут использоваться для аутентификации в Strapi, поэтому, пожалуйста, найдите время, чтобы заполнить обязательные данные и зарегистрироваться.
После регистрации вы попадете на страницу приветствия Strapi. Это даст вам ориентиры, необходимые для создания структуры контента, присоединения к сообществам и выполнения многих других функций.
Теперь приступим к созданию types
в Strapi. Вы можете думать об этих типах как о таблицах со схемой в реляционной базе данных.
Для нашего приложения мы хотим создать данные об обуви как Product
тип. Каждый обувной продукт будет иметь свою собственную метаинформацию, такую как название, цена, описание, акции, категория и компания.
Мы также будем управлять Category
и Company
как независимыми типами, и создавать отношения с Product
типом.
Итак, давайте начнем создавать типы один за другим. Сначала создайте следующие поля для Category
типа:
Точно так же вы можете создать тип компании с полями имени и ярлыка.
А теперь мы создадим тип продукта с полями, показанными на изображении ниже.
Большинство полей выше говорят сами за себя. Однако некоторые поля требуют пояснений.
Media
. В Strapi вы можете загружать активы (изображения, видео, файлы) в медиатеку, чтобы использовать их позже.Поскольку все необходимые типы теперь созданы, мы можем приступить к созданию примеров данных в Strapi. Во-первых, давайте загрузим несколько крутых изображений обуви. Вы можете собирать их с медиа-сайта, например, unsplash
и загружать элементы из Media Library
меню.
Затем просмотрите параметр «Диспетчер содержимого» в левой части навигации и начните создавать записи для типа категории. Вы можете создать категории, упомянутые на изображении ниже, или создать свои собственные.
Аналогичным образом вставьте записи для данных компании.
Наконец, введите данные для типа продукта.
На данный момент мы создали весь необходимый контент в Strapi и собираемся использовать все элементы пользовательского интерфейса с помощью API Strapi. Вы можете получить доступ к API Strapi, используя REST для GraphQL, но помните, что вам необходимо получить токен API для выполнения успешных вызовов API.
Нажмите «Настройки»> «Глобальные настройки»> «Токены API» на левой панели навигации и нажмите Create new API Token
кнопку, чтобы создать токен полного доступа для приложения «Обувь». Пожалуйста, сохраните этот токен при себе, потому что мы будем использовать его в ближайшее время.
client
_Gatsby
Мы успешно настроили datastore
Strapi, и теперь пришло время настроить client
сторону с Gatsby
.
Для этого откройте другую командную строку/терминал в корневой папке проекта и выполните следующую команду.
yarn global add gatsby-cli
Эта команда установит интерфейс командной строки Gatsby (CLI) глобально. Это помогает нам взаимодействовать со структурой Gatsby для выполнения различных задач.
Как и Strapi, Gatsby поставляется с несколькими шаблонами для создания проекта. В мире Гэтсби они называются «начальными шаблонами». Мы будем использовать начальный шаблон по умолчанию для создания проекта и назовем файл client
.
Пожалуйста, выполните следующую команду, чтобы создать проект Gatsby.
npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default
Приведенная выше команда займет некоторое время и создаст для вас структуру проекта. Теперь перейдите в client
каталог и запустите приложение локально с помощью gatsby develop
команды.
cd client
gatsby develop
Приложение Gatsby будет работать по [localhost:8000](http://localhost:8000)
URL-адресу, и вы увидите такой пользовательский интерфейс при доступе к нему с помощью браузера. Это страница по умолчанию из начального шаблона, который мы использовали. Мы изменим его в ближайшее время.
Итак, теперь мы объединим Gatsby и Strapi, чтобы придать форму нашему приложению. Мы будем вызывать API-интерфейсы Strapi из Gatsby и получать данные об обуви во время сборки.
Экосистема подключаемых модулей Gatsby имеет подключаемый модуль источника gatsby-source-strapi
, который помогает получать данные из Strapi с помощью GraphQL. Давайте установим этот плагин и еще несколько зависимостей для обработки изображений и преобразования. Пожалуйста, выполните следующую команду из терминала в client
каталоге.
yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp
Создайте файл с именем .env.development
в корне client
папки со следующим содержимым.
STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337
Вот <STRAPI-API-TOKEN>
токен, который вы скопировали при настройке хранилища данных Strapi. Теперь вы можете импортировать client
проект в свой любимый редактор кода (в моем случае, например, в VS Code).
Теперь откройте gatsby-config.js
файл и замените содержимое приведенным ниже содержимым. Это файл конфигурации, который определяет метаданные сайта и параметры плагинов.
Внимательно изучите параметры, которые мы определили для gatsby-source-strapi
подключаемого модуля: мы указали URL-адрес API Strapi, токен API и имена типов коллекций, с которыми мы хотим взаимодействовать.
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `Shoes`,
description: `The one stop shop for your shoes and footwear needs.`,
author: `@tapasadhikary`,
siteUrl: `https://shoes.io/`,
},
plug-ins: [
"gatsby-plugin-gatsby-cloud",
{
resolve: "gatsby-source-strapi",
options: {
apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
accessToken: process.env.STRAPI_TOKEN,
collectionTypes: [
{
singularName: "product",
},
{
singularName: "company",
},
{
singularName: "category",
},
],
},
},
"gatsby-plugin-image",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
"gatsby-transformer-remark",
],
}
Пожалуйста, остановите и перезапустите gatsby develop
функцию и перейдите по URL-адресу http://localhost:8000/__graphql
, чтобы открыть проводник Gatsby GraphQL.
Gatsby предоставляет проводник GraphQL в качестве инструмента разработчика, поэтому вы можете легко создавать запросы GraphQL. Вы должны найти все типы коллекций Strapi в крайнем левом Explorer
столбце: все они начинаются с текста allStrapi
.
Итак, давайте теперь попробуем построить пример запроса для allStrapiProduct
коллекции. Вы можете расширить коллекцию и выбрать поля, для которых вы хотите получить данные; вы увидите, что запрос GraphQL создается автоматически на основе вашего выбора.
Теперь вы можете запустить запрос, нажав кнопку «Выполнить» в заголовке средней панели. Вы можете найти вывод в самой правой панели.
Я предлагаю вам провести некоторое время с проводником GraphQL и поиграться с запросами, чтобы привыкнуть к нему.
Чтобы построить запросы GraphQL, мы будем использовать их для создания компонентов пользовательского интерфейса. Gatsby основан на React, поэтому вы можете использовать всю мощь библиотеки React в Gatsby. Просто откройте index.js
файл и замените существующее содержимое следующим кодом.
// index.js
import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"
import { useStaticQuery, graphql } from "gatsby"
import '../style/shoes.css'
const IndexPage = () => {
const { allStrapiProduct } = useStaticQuery(graphql`
query {
allStrapiProduct(sort: {order: ASC, fields: title}) {
edges {
node {
image {
url
}
slug
price
title
id
stock
status
}
}
}
}
`)
return (
<Layout>
<Seo title="Home" />
<ShoeList shoes={allStrapiProduct.edges} />
</Layout>
)
}
export default IndexPage
Теперь давайте углубимся в код в index.js
файле. Мы используем запрос GraphQL для получения всех продуктов, отсортированных по названию продукта в порядке возрастания. Gatsby предоставляет нам хук React, вызываемый useStaticQuery
для выполнения запроса GraphQL.
Затем мы передаем полученный массив продуктов (обувь) в качестве реквизита ShoeList
компоненту. Нам нужно создать компонент, который будет перебирать shoes
массив, и начать создавать макет карты для каждой детали обуви.
Для этого создайте файл с именем ShowList.js
в components
папке со следующим содержимым.
// ShoeList.js
import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
console.log(shoes);
return (
<div className="shoe-list">
{shoes.map((shoe) => (
<ShoeCard key={shoe.node.id} shoe={shoe.node} />
))}
</div>
)
}
export default ShoeList
Как вы заметили в приведенном выше коде, мы убираем каждую деталь обуви и передаем ее в качестве реквизита другому компоненту, ShoeCard. Итак, вам нужно создать файл с именем ShoeCard.js
в components
папке со следующим содержимым.
// ShoeCard.js
import * as React from "react"
import { Link } from "gatsby"
const ShoeCard = ({ shoe }) => {
return (
<Link
to={`/${shoe.slug}`}
className="shoe-card" >
<div className="img-container">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="details">
<h2>{shoe.title} - ${shoe.price}</h2>
</div>
</Link>
)
}
export default ShoeCard
Компонент ShoeCard отображает изображение обуви, название и цену. Позже мы будем показывать название и цену только тогда, когда пользователь наведет курсор на изображение обуви, используя стили CSS.
Также обратите внимание, что карточка обуви упакована в файл Link
. Компонент Link принадлежит Gatsby и помогает нам создавать ссылки между страницами в приложении Gatsby. Компонент Link имеет атрибут, который мы используем для ссылки на целевую страницу. В приведенном выше примере значением атрибута является значение slug каждой обуви.
Мы намерены переходить на новую страницу, когда пользователь нажимает на карточку обуви; эта новая страница будет отображать более подробную информацию об обуви и вариантах покупки. Но нам нужно внести некоторые изменения, и мы сделаем это позже. Во-первых, нам нужно сосредоточиться на подготовке страницы списка обуви со всеми стилями.
Давайте немного подправим компоненты Layout и Header. Сначала замените содержимое layout.js
файла следующим содержимым. Он очень похож на существующий файл layout.js, поставляемый с шаблоном, но мы внесли некоторые незначительные изменения стиля.
// layout.js
import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Header from "./header"
import "./layout.css"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<Header siteTitle={data.site.siteMetadata?.title || `Title`} />
<div className="container">
<main className="content">{children}</main>
<footer>
© {new Date().getFullYear()} · Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
Вот содержимое Header.js
файла, который нужно заменить в существующем файле.
// Header.js
import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"
const Header = ({ siteTitle }) => (
<header>
<Link to="/" className="logo">
👠 {siteTitle}
</Link>
</header>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
Теперь давайте создадим style
папку в src
каталоге. Для этого создайте в папке shoes.css
файл style
со следующим содержимым.
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");
*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: border-box;
scroll-behavior: smooth;
}
html {
overflow: auto;
}
body {
height: 100vh;
background-color: rgb(3, 28, 34);
color: #ffffff;
font-family: "Poppins", sans-serif;
}
a {
text-decoration: none;
color: #ffffff;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #282d2e;
padding-left: 0.5rem;
padding-right: 0.5rem;
margin: 0 0 0.5rem 0;
}
header .logo {
font-size: 2rem;
font-weight: 500;
color: #ffffff;
padding: 0.5rem;
}
footer {
width: 100%;
padding: 0.3rem;
background-color: #282d2e;
text-align: center;
}
footer > a {
color: #1af41a;
text-decoration: underline;
}
.btn {
padding: 10px;
cursor: pointer;
font-size: 18px;
border: none;
border-radius: 10px;
}
.btn.btn-primary {
background-color: #40ee10;
color: #000000;
}
.btn.btn-primary:hover {
background-color: #70e007;
color: #000000;
}
.btn.btn-secondary {
background-color: #ffffff;
color: #282d2e;
}
.btn.btn-secondary:hover {
background-color: #282d2e;
color: #ffffff;
}
.container {
height: calc(100vh - 73px);
overflow: hidden;
display: flex;
flex-direction: column;
}
.content {
flex-grow: 1;
overflow: auto;
}
.shoe-list {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.shoe-card {
position: relative;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
width: 15rem;
height: 15rem;
margin: 1.2rem;
}
.shoe-card .img-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
transition: all 0.5s ease-in-out;
}
.shoe-card .img-container > IMG {
width: 15rem;
height: 15rem;
object-fit: cover;
resize: both;
border-radius: 10px;
}
.shoe-card:hover .img-container {
transform: translate(-1rem, -1rem);
}
.shoe-card:hover .details {
transform: translate(1rem, 1rem);
}
.shoe-card .details {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 0.5rem;
display: flex;
background-color: #fff;
z-index: 1;
align-items: flex-end;
transition: 0.5s ease-in-out;
line-height: 1rem;
border-radius: 10px;
}
.shoe-card .details h2 {
display: block;
font-size: 1rem;
color: #000000;
font-weight: 500;
}
Вот и все!
Теперь запустите приложение локально, используя URL-адрес [http://localhost:8000](http://localhost:8000)
, и вы увидите список изображений обуви на странице. Наведите указатель мыши на изображения обуви, и анимация покажет название обуви и цену.
Замечательно. Итак, теперь попробуйте нажать на любую из карточек с обувью.
Ой! вы получаете страницу, как показано ниже, и она выглядит сломанной. Он попытался перейти на страницу, идентифицированную значением слага обуви, но безуспешно.
Но не беспокойтесь, мы можем решить проблему.
Gatsby может создавать страницы во время сборки, используя шаблоны. Они используют ту же структуру пользовательского интерфейса, которую вы хотите использовать для другого набора данных.
Например, в нашем shoes
приложении мы хотим показать детали каждой обуви. Структура страницы сведений будет такой же, но данные обуви будут меняться в зависимости от того, на какое изображение обуви мы нажимаем.
Итак, мы можем создать шаблон shoe-details.js
под названием src/templates
папки со следующим содержимым.
// shoe-details.js
import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
export default function ShoeDetails({ data }) {
const shoe = data.strapiProduct
const [quantity, setQuantity] = useState(1)
return (
<Layout>
<div className="shoe-details">
<div className="cover">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="info">
<div className="info-heading">
<h2>{shoe.title}</h2>
<Link to={`/category/${shoe.categories[0].slug}`}>
<span>{shoe.categories[0].name}</span>
</Link> { ' '}
from {' '}
<Link to={`/company/${shoe.company.slug}`}>
{shoe.company.name}
</Link>
</div>
<div className="info-body">
<p>{shoe.description}</p>
<span>${shoe.price} per unit</span> { ' - '}
<>
{
shoe.stock > 0 ?
<span>{shoe.stock} In Stock</span> :
<span>Out of Stock</span>
}
</>
</div>
<div className="info-purchase">
{
shoe.stock > 0 ?
<>
<p>
I want to purchase {' '}
<input
type="number"
min="1"
max={shoe.stock}
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/> {' '} unit
</p>
<p className="price">Total Price: ${quantity * shoe.price}</p>
<button className="btn btn-primary">Add to Cart</button>
</> :
<>
<p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
<button className="btn btn-secondary">Notify Me!</button>
</>
}
</div>
</div>
</div>
</Layout>
)
}
export const query = graphql`
query($slug: String!) {
strapiProduct(slug: {eq: $slug}) {
id
title
price
status
stock
categories {
name
slug
}
company {
name
slug
}
description
image {
url
}
updatedAt
}
}
`
В приведенном выше коде мы выполняем запрос GraphQL для получения сведений о продукте (обуви) на основе значения слага.
Мы можем использовать сведения о продукте для построения структуры при получении сведений о продукте. В этом случае структура включает в себя фото товара и такую информацию, как категория, компания, цена и наличие на складе. На странице также есть поле ввода числа, чтобы указать необходимое количество обуви и автоматически рассчитать общую сумму для оплаты при оформлении заказа.
Все это здорово, но как нам получить значение slug обуви и сопоставить его с shoe-details
шаблоном? Давайте попробуем сделать это сейчас.
Откройте gatsby-node.js
файл и замените содержимое следующим кодом:
// gatsby-node.js
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allStrapiProduct {
edges {
node {
slug
}
}
}
}
`)
data.allStrapiProduct.edges.forEach(edge => {
const slug = edge.node.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/shoe-details.js`),
context: { slug: slug },
})
})
}
Gatsby запускает gatsby-node.js
файл во время сборки. Здесь мы получаем слаги для всех продуктов, чтобы затем интегрировать слаги и создавать страницы для каждого из них.
Метод createPage
принимает объект в качестве аргумента, где мы предоставляем детали пути, на который ссылается слаг, и сопоставляем с каким компонентом. Обратите внимание, что компонент — это файл шаблона, который мы видели выше. Мы также передаем контекстные данные, которые являются самим слагом.
Таким образом, каждый путь со значением slug теперь сопоставляется с файлом шаблона, а значение slug передается в качестве контекста. Мы уже узнали, как компонент шаблона использует это значение slug и извлекает сведения о продукте. Надеюсь, теперь все точки хорошо связаны.
Теперь откройте shoes.css
файл и добавьте следующие стили ниже существующих. Следующие стили предназначены для страницы сведений об обуви.
.shoe-details {
padding: 1rem;
display: flex;
justify-content: space-around;
align-items: center;
}
.shoe-details .cover {
display: flex;
align-content: center;
justify-content: center;
}
.shoe-details .cover > IMG {
width: 30rem;
height: 30rem;
border-radius: 50%;
}
.shoe-details .info-heading {
margin-bottom: 1rem;
}
.shoe-details .info-heading > a {
color: #1af41a;
text-decoration: underline;
}
.shoe-details .info-heading > H2 {
font-size: 3rem;
}
.shoe-details .info-body > P {
margin: 0;
}
.shoe-details .info-body > SPAN {
font-size: 1.5rem;
}
.shoe-details .info-purchase {
margin: 2rem 0 0 0;
border: 1px solid #4a4545;
border-radius: 5px;
padding: 1rem;
background-color: black;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.shoe-details .info-purchase .price {
font-size: 1.5rem;
font-weight: 500;
color: #ffffff;
}
.shoe-details .info-purchase INPUT {
border: 1px solid #ececec;
padding: 5px;
border-radius: 3px;
font-size: 1rem;
}
.shoe-filtered-list H2 {
font-size: 2rem;
font-weight: 500;
color: #1af41a;
margin: 0 0 1rem 1rem;
}
@media only screen and (max-width: 900px) {
.shoe-details {
padding: 1rem;
display: flex;
flex-direction: column;
justify-content: space-around;
}
}
@media only screen and (max-width: 600px) {
.shoe-details .cover > IMG {
width: 20rem;
height: 20rem;
}
}
Теперь перезапустите локальный сервер Гэтсби и снова войдите в приложение на localhost:8000
. Нажмите на любую из карт обуви; вы должны увидеть элегантную страницу с деталями обуви.
Хорошо, это все, что мы хотели создать с Gatsby и Strapi: обувной магазин Jamstack с парой страниц, обслуживаемых статически. И мы сделали это!
Однако не волнуйтесь: отсюда вы можете пойти гораздо дальше. Вы можете создавать шаблоны для категорий и компаний и иметь страницы для каждой из них. Вы можете разработать функции поиска и создать параметры фильтрации обуви по названию, ценовому диапазону, компании и категории. Код проекта находится в открытом доступе под лицензией MIT на GitHub.
В качестве краткого обзора посмотрите краткое демонстрационное видео ниже. Это демонстрация shoes
приложения, которое мы создали в этой статье, вместе с несколькими дополнительными функциями, упомянутыми выше.
Ссылка: https://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi
#ecommerce #gatsby #strapi #javascript
1659428880
了解如何使用 Gatsby 和 Strapi 創建 Jamstack 電子商務商店。我們將逐步建立一個在線鞋店。
讓我們從一個問題開始:在這個時代構建網站或應用程序時,我們需要考慮的主要事項是什麼?
好吧,這個問題有很多潛在的答案,但是speed
,無論我們正在構建什麼,都應該突出顯示cost
。security
無論是博客網站、個人網站還是電子商務門戶網站,我們的用戶都希望它能夠快速加載、維護成本低廉並且對最終用戶而言是安全的。
值得慶幸的是,Jamstack 架構可以在所有三個方面為我們提供幫助。
Jamstack 允許我們使用預構建的標記、無服務器 API……甚至來自 CMS 的數據來構建靜態網站。這些靜態站點比其他站點更快,因為標記是預先構建的,並從安全的 CDN(而不是原始服務器)安全地提供服務。
還有一個完整的技術生態系統支持創建 Jamstack 應用程序。在本文中,我們將討論其中最知名的兩項技術:Gatsby
我們將使用它們來構建一個電子商務應用程序——一個名為OriginalStrapi.
的在線鞋店,對吧?shoes.
Gatsby是一個基於 React 的靜態站點生成器,專門設計用於創建預構建標記,並為構建、預覽和託管您的應用程序提供統一的雲平台。它超級快速,易於與各種數據源集成,並帶有大量的插件生態系統。
另一方面,Strapi 是一個開源、高度可定制的應用程序,可幫助您更快地構建 API 並輕鬆管理您的內容。任何前端客戶端都可以使用 REST 或 GraphQL 使用 API,並且您可以在 Heroku 等提供程序上輕鬆自託管 Strapi 應用程序。
這兩個程序完美契合:雖然 Gatsby 提供了更快的前端,但 Strapi解決了對後端數據存儲和內容管理系統 (CMS) 的需求。
好的,現在您知道 Gatsby 和 Strapi 可以提供什麼,讓我們通過構建shoes
應用程序來看看它們在實踐中是如何工作的。
shoes
應用程序我們將shoes
應用程序分為兩個主要部分:
datastore
:這需要Strapi
項目,以及應用程序所需的所有內容和 API。client
:這依賴於Gatsby
項目,該項目在 GraphQL 的幫助下使用 API 從 Strapi 獲取內容並將其呈現在漂亮的用戶界面中。首先,我們將設置datastore
使用 Strapi。請注意,您必須安裝Node.js才能在本地運行應用程序。您還可以選擇安裝yarn,但如果您沒有 yarn,請npm
改用。
datastoreStrapi
Strapi 提供了一堆模板來快速開始使用該應用程序。由於我們的鞋店是一個電子商務應用程序,我們將使用ecommerce
模板來創建datastore
.
為此,只需創建一個shoes
文件夾並在 shoes 目錄上打開命令提示符(或終端)。
現在,使用以下命令創建一個 Strapi 項目:
yarn create strapi-app datastore --template ecommerce
請注意,我們在上述命令中提供了項目名稱datastore
和模板。ecommerce
該命令將需要一段時間來下載所需的依賴項、安裝它們並為您設置它們。但是,一旦完成,Strapi 應用程序將可以在您的瀏覽器上使用 URL 訪問[localhost:1337](http://localhost:1337)
。
同樣重要的是要記住,您需要首次註冊您的個人資料以創建您的憑據。這些相同的憑據將用於在 Strapi 中進行身份驗證,因此請花時間填寫強制性詳細信息並進行註冊。
註冊後,您將登陸 Strapi 的歡迎頁面。這將為您提供創建內容結構、加入社區和完成更多功能所需的指導。
現在我們將開始types
在 Strapi 中創建。您可以將這些類型視為關係數據庫中具有架構的表。
對於我們的應用程序,我們希望將鞋子數據創建為一種Product
類型。每個鞋類產品都有自己的元信息,如名稱、價格、描述、庫存、類別和公司。
我們還將管理Category
和Company
作為獨立類型,並創建與Product
類型的關係。
所以,讓我們開始一一創建類型。首先,為該Category
類型創建以下字段:
同樣,您可以使用名稱和 slug 字段創建公司類型。
現在我們將創建 Product 類型,其字段如下圖所示。
上面的大部分字段都是不言自明的。但是,有幾個領域需要解釋。
Media
。在 Strapi 中,您可以將資產(圖像、視頻、文件)上傳到媒體庫以供以後使用。由於現在創建了所有必需的類型,我們可以開始在 Strapi 中創建示例數據。首先,讓我們上傳一些很酷的鞋子圖片。您可以從媒體網站上收集它們,例如從菜單中unsplash
上傳項目。Media Library
接下來,從左側導航瀏覽 Content Manager 選項並開始為 Category 類型創建條目。您可以創建下圖中提到的類別,也可以隨意創建自己的類別。
同樣,為公司數據插入條目。
最後,輸入產品類型的數據。
到目前為止,我們已經在 Strapi 中創建了所有必需的內容,並且即將通過 Strapi API 使用 UI 中的所有元素。您可以使用 REST 到 GraphQL 訪問 Strapi API,但請記住,您需要獲取 API 令牌才能成功調用 API。
單擊左側導航欄中的設置 > 全局設置 > API Tokens,然後單擊Create new API Token
按鈕為鞋子應用程序創建完全訪問令牌。請妥善保管此令牌,因為我們很快就會使用它。
clientGatsby
我們已經成功地設置了datastore
Strapi,所以現在是時候設置client
側邊了Gatsby
。
為此,請在項目的根文件夾中打開另一個命令提示符/終端並執行以下命令。
yarn global add gatsby-cli
此命令將全局安裝 Gatsby 命令行界面 (CLI)。這有助於我們與 Gatsby 框架交互以執行不同的任務。
就像 Strapi 一樣,Gatsby 提供了幾個模板來創建項目。在 Gatsby 世界中,這些被稱為“入門模板”。我們將使用默認的啟動模板來創建項目並將client
.
請執行以下命令創建 Gatsby 項目。
npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default
上面的命令將花費一些時間並為您創建項目結構。現在切換到目錄並使用命令client
在本地啟動應用程序。gatsby develop
cd client
gatsby develop
Gatsby 應用程序將在[localhost:8000](http://localhost:8000)
URL 上運行,當您使用瀏覽器訪問它時,您將看到這樣的 UI。這是我們使用的起始模板的默認頁面。我們很快就會改變它。
所以,現在我們將把 Gatsby 和 Strapi 結合在一起,來塑造我們的應用程序。我們將從 Gatsby 調用 Strapi API 並在構建時獲取鞋子數據。
Gatsby 插件生態系統有一個名為的源插件,gatsby-source-strapi
它有助於使用 GraphQL 從 Strapi 獲取數據。讓我們安裝該插件和一些用於處理圖像和轉換的依賴項。請從目錄中的終端執行以下命令client
。
yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp
.env.development
在文件夾的根目錄創建一個名為的client
文件,其內容如下。
STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337
這<STRAPI-API-TOKEN>
是您在設置 Strapi 數據存儲時復制的令牌。你現在可以client
在你最喜歡的代碼編輯器中導入項目(比如我的 VS Code)。
現在,打開gatsby-config.js
文件並將內容替換為以下內容。這是一個定義站點元數據和插件選項的配置文件。
仔細看看我們為gatsby-source-strapi
插件定義的選項:我們已經指定了 Strapi API URL、API 令牌和我們想要與之交互的集合類型的名稱。
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `Shoes`,
description: `The one stop shop for your shoes and footwear needs.`,
author: `@tapasadhikary`,
siteUrl: `https://shoes.io/`,
},
plug-ins: [
"gatsby-plugin-gatsby-cloud",
{
resolve: "gatsby-source-strapi",
options: {
apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
accessToken: process.env.STRAPI_TOKEN,
collectionTypes: [
{
singularName: "product",
},
{
singularName: "company",
},
{
singularName: "category",
},
],
},
},
"gatsby-plugin-image",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
"gatsby-transformer-remark",
],
}
請停止並重新啟動該gatsby develop
功能並訪問 URLhttp://localhost:8000/__graphql
以打開 Gatsby 的 GraphQL 瀏覽器。
Gatsby 提供 GraphQL explorer 作為開發者工具,因此您可以輕鬆構建 GraphQL 查詢。您應該從最左側的Explorer
列中找到所有 Strapi 集合類型:它們都以 text 開頭allStrapi
。
好的,現在讓我們嘗試為allStrapiProduct
集合構建一個示例查詢。您可以展開集合併選擇要獲取數據的字段;您將看到根據您的選擇自動創建一個 GraphQL 查詢。
現在,您可以通過點擊中間面板標題中的“運行”按鈕來運行查詢。您可以在最右側的面板中找到輸出。
我建議您花一些時間使用 GraphQL 資源管理器並嘗試使用查詢來習慣它。
為了構建 GraphQL 查詢,我們將使用它們來創建 UI 組件。Gatsby 是基於 React 的,因此您可以在 Gatsby 中使用 React 庫的全部功能。只需打開index.js
文件並將現有內容替換為以下代碼即可。
// index.js
import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"
import { useStaticQuery, graphql } from "gatsby"
import '../style/shoes.css'
const IndexPage = () => {
const { allStrapiProduct } = useStaticQuery(graphql`
query {
allStrapiProduct(sort: {order: ASC, fields: title}) {
edges {
node {
image {
url
}
slug
price
title
id
stock
status
}
}
}
}
`)
return (
<Layout>
<Seo title="Home" />
<ShoeList shoes={allStrapiProduct.edges} />
</Layout>
)
}
export default IndexPage
現在讓我們深入研究文件中的代碼index.js
。我們使用 GraphQL 查詢來獲取按產品標題升序排序的所有產品。Gatsby 為我們提供了一個調用useStaticQuery
來執行 GraphQL 查詢的 React 鉤子。
接下來,我們將獲取的產品數組(鞋子)作為道具傳遞給ShoeList
組件。我們需要創建將遍歷shoes
數組的組件,並開始為每個鞋子細節創建卡片佈局。
為此,請在該文件夾ShowList.js
下創建一個名為的components
文件,其內容如下。
// ShoeList.js
import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
console.log(shoes);
return (
<div className="shoe-list">
{shoes.map((shoe) => (
<ShoeCard key={shoe.node.id} shoe={shoe.node} />
))}
</div>
)
}
export default ShoeList
正如您在上面的代碼中註意到的那樣,我們取出每個鞋子的細節並將它們作為道具傳遞給另一個組件 ShoeCard。所以需要在文件夾下創建一個名為ShoeCard.js
的components
文件,內容如下。
// ShoeCard.js
import * as React from "react"
import { Link } from "gatsby"
const ShoeCard = ({ shoe }) => {
return (
<Link
to={`/${shoe.slug}`}
className="shoe-card" >
<div className="img-container">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="details">
<h2>{shoe.title} - ${shoe.price}</h2>
</div>
</Link>
)
}
export default ShoeCard
ShoeCard 組件呈現鞋子圖像、標題和價格。稍後我們將僅在用戶使用 CSS 樣式將鼠標懸停在鞋子圖像上時顯示標題和價格。
另外,請注意鞋牌是用Link
. Link 組件來自 Gatsby,它幫助我們在 Gatsby 應用程序中的頁面之間進行鏈接。Link 組件具有我們用來鏈接到目標頁面的屬性。在上面的例子中,屬性值是每隻鞋子的 slug 值。
我們打算在用戶點擊鞋卡時轉到新頁面;這個新頁面將顯示有關鞋子和購買選項的更多詳細信息。但是我們需要做一些改變,我們稍後會做。首先,我們需要專注於準備所有樣式的鞋子列表頁面。
讓我們稍微調整一下 Layout 和 Header 組件。首先,將layout.js
文件內容替換為如下內容。它與模板附帶的現有 layout.js 文件非常相似,但我們進行了一些小的樣式調整。
// layout.js
import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Header from "./header"
import "./layout.css"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<Header siteTitle={data.site.siteMetadata?.title || `Title`} />
<div className="container">
<main className="content">{children}</main>
<footer>
© {new Date().getFullYear()} · Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
這是Header.js
您需要在現有文件中替換的文件的內容。
// Header.js
import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"
const Header = ({ siteTitle }) => (
<header>
<Link to="/" className="logo">
👠 {siteTitle}
</Link>
</header>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
現在,讓我們在目錄下創建一個style
文件夾src
。為此,請shoes.css
在文件夾下創建一個style
包含以下內容的文件。
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");
*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: border-box;
scroll-behavior: smooth;
}
html {
overflow: auto;
}
body {
height: 100vh;
background-color: rgb(3, 28, 34);
color: #ffffff;
font-family: "Poppins", sans-serif;
}
a {
text-decoration: none;
color: #ffffff;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #282d2e;
padding-left: 0.5rem;
padding-right: 0.5rem;
margin: 0 0 0.5rem 0;
}
header .logo {
font-size: 2rem;
font-weight: 500;
color: #ffffff;
padding: 0.5rem;
}
footer {
width: 100%;
padding: 0.3rem;
background-color: #282d2e;
text-align: center;
}
footer > a {
color: #1af41a;
text-decoration: underline;
}
.btn {
padding: 10px;
cursor: pointer;
font-size: 18px;
border: none;
border-radius: 10px;
}
.btn.btn-primary {
background-color: #40ee10;
color: #000000;
}
.btn.btn-primary:hover {
background-color: #70e007;
color: #000000;
}
.btn.btn-secondary {
background-color: #ffffff;
color: #282d2e;
}
.btn.btn-secondary:hover {
background-color: #282d2e;
color: #ffffff;
}
.container {
height: calc(100vh - 73px);
overflow: hidden;
display: flex;
flex-direction: column;
}
.content {
flex-grow: 1;
overflow: auto;
}
.shoe-list {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.shoe-card {
position: relative;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
width: 15rem;
height: 15rem;
margin: 1.2rem;
}
.shoe-card .img-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
transition: all 0.5s ease-in-out;
}
.shoe-card .img-container > IMG {
width: 15rem;
height: 15rem;
object-fit: cover;
resize: both;
border-radius: 10px;
}
.shoe-card:hover .img-container {
transform: translate(-1rem, -1rem);
}
.shoe-card:hover .details {
transform: translate(1rem, 1rem);
}
.shoe-card .details {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 0.5rem;
display: flex;
background-color: #fff;
z-index: 1;
align-items: flex-end;
transition: 0.5s ease-in-out;
line-height: 1rem;
border-radius: 10px;
}
.shoe-card .details h2 {
display: block;
font-size: 1rem;
color: #000000;
font-weight: 500;
}
而且……就是這樣!
現在使用 URL 在本地運行應用程序[http://localhost:8000](http://localhost:8000)
,您將在頁面上看到鞋子圖像列表。將鼠標移到鞋子圖像上,動畫將顯示鞋子名稱和價格。
那太棒了。所以現在,試著點擊任何一張鞋牌。
哎喲! 你得到一個像下面這樣的頁面,它看起來壞了。它試圖導航到由鞋子的 slug 值標識的頁面,但沒有成功。
不過不用擔心,我們可以解決問題。
Gatsby 可以在構建時使用模板創建頁面。它們利用您想要用於不同數據集的相同 UI 結構。
例如,在我們的shoes
應用程序中,我們想要顯示每雙鞋的詳細信息。詳細信息頁面結構將相同,但鞋子數據會根據我們點擊的鞋子圖片而變化。
shoe-details.js
因此,我們可以在該src/templates
文件夾下創建一個名為的模板,其內容如下。
// shoe-details.js
import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
export default function ShoeDetails({ data }) {
const shoe = data.strapiProduct
const [quantity, setQuantity] = useState(1)
return (
<Layout>
<div className="shoe-details">
<div className="cover">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="info">
<div className="info-heading">
<h2>{shoe.title}</h2>
<Link to={`/category/${shoe.categories[0].slug}`}>
<span>{shoe.categories[0].name}</span>
</Link> { ' '}
from {' '}
<Link to={`/company/${shoe.company.slug}`}>
{shoe.company.name}
</Link>
</div>
<div className="info-body">
<p>{shoe.description}</p>
<span>${shoe.price} per unit</span> { ' - '}
<>
{
shoe.stock > 0 ?
<span>{shoe.stock} In Stock</span> :
<span>Out of Stock</span>
}
</>
</div>
<div className="info-purchase">
{
shoe.stock > 0 ?
<>
<p>
I want to purchase {' '}
<input
type="number"
min="1"
max={shoe.stock}
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/> {' '} unit
</p>
<p className="price">Total Price: ${quantity * shoe.price}</p>
<button className="btn btn-primary">Add to Cart</button>
</> :
<>
<p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
<button className="btn btn-secondary">Notify Me!</button>
</>
}
</div>
</div>
</div>
</Layout>
)
}
export const query = graphql`
query($slug: String!) {
strapiProduct(slug: {eq: $slug}) {
id
title
price
status
stock
categories {
name
slug
}
company {
name
slug
}
description
image {
url
}
updatedAt
}
}
`
在上面的代碼中,我們執行 GraphQL 查詢以根據 slug 值獲取產品(鞋)的詳細信息。
當我們獲取產品詳細信息時,我們可以使用產品詳細信息來構建結構。在這種情況下,結構包括產品照片和類別、公司、價格和庫存等信息。該頁面還包括輸入數字框,以指定所需鞋子的數量,並自動計算結賬時支付的總金額。
這一切都很棒,但是我們如何獲得鞋子的 slug 值並與shoe-details
模板映射呢?讓我們現在嘗試這樣做。
打開gatsby-node.js
文件並將內容替換為以下代碼:
// gatsby-node.js
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allStrapiProduct {
edges {
node {
slug
}
}
}
}
`)
data.allStrapiProduct.edges.forEach(edge => {
const slug = edge.node.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/shoe-details.js`),
context: { slug: slug },
})
})
}
Gatsbygatsby-node.js
在構建時運行該文件。在這裡,我們獲取所有產品的 slug,然後我們可以集成 slug 並為每個產品創建頁面。
該createPage
方法將對像作為參數,我們在其中提供使用 slug 引用的路徑的詳細信息並映射到哪個組件。請注意,該組件是我們在上面看到的模板文件。我們還傳遞了 slug 本身的上下文數據。
因此,每個帶有 slug 值的路徑現在都映射到模板文件,並將 slug 值作為上下文傳遞。我們已經了解了模板組件如何使用這個 slug 值並獲取產品的詳細信息。我希望現在所有的點都連接得很好。
現在打開shoes.css
文件並在現有樣式下方添加以下樣式。以下款式為鞋款詳情頁。
.shoe-details {
padding: 1rem;
display: flex;
justify-content: space-around;
align-items: center;
}
.shoe-details .cover {
display: flex;
align-content: center;
justify-content: center;
}
.shoe-details .cover > IMG {
width: 30rem;
height: 30rem;
border-radius: 50%;
}
.shoe-details .info-heading {
margin-bottom: 1rem;
}
.shoe-details .info-heading > a {
color: #1af41a;
text-decoration: underline;
}
.shoe-details .info-heading > H2 {
font-size: 3rem;
}
.shoe-details .info-body > P {
margin: 0;
}
.shoe-details .info-body > SPAN {
font-size: 1.5rem;
}
.shoe-details .info-purchase {
margin: 2rem 0 0 0;
border: 1px solid #4a4545;
border-radius: 5px;
padding: 1rem;
background-color: black;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.shoe-details .info-purchase .price {
font-size: 1.5rem;
font-weight: 500;
color: #ffffff;
}
.shoe-details .info-purchase INPUT {
border: 1px solid #ececec;
padding: 5px;
border-radius: 3px;
font-size: 1rem;
}
.shoe-filtered-list H2 {
font-size: 2rem;
font-weight: 500;
color: #1af41a;
margin: 0 0 1rem 1rem;
}
@media only screen and (max-width: 900px) {
.shoe-details {
padding: 1rem;
display: flex;
flex-direction: column;
justify-content: space-around;
}
}
@media only screen and (max-width: 600px) {
.shoe-details .cover > IMG {
width: 20rem;
height: 20rem;
}
}
現在重新啟動 Gatsby 的本地服務器並再次訪問應用程序localhost:8000
。點擊任意一張鞋牌;你應該會看到一個優雅的頁面,呈現出鞋子的細節。
好的,這就是我們想要用 Gatsby 和 Strapi 構建的全部內容:一個有幾個靜態頁面的 Jamstack 鞋店。我們做到了!
但是,不要擔心:您可以從這裡走得更遠。您可以為類別和公司創建模板,並為每個類別創建頁面。您可以開發搜索功能並按標題、價格範圍、公司和類別為鞋子創建過濾選項。該項目代碼是在 GitHub 上的 MIT 許可下開源的。
作為快速回顧,請查看下面的快速演示視頻。shoes
這是我們在本文中構建的應用程序的演示,以及上面提到的一些額外功能。
鏈接:https ://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi
#ecommerce #gatsby #strapi #javascript
1659421620
Learn how to create a Jamstack ecommerce store using Gatsby and Strapi. We will build an online shoe store with a step-by-step approach.
Let’s start with a question: When building a website or app in this day and age, what are the primary things we need to consider?
Well there are loads of potential answers to this question, but speed
, cost
, and security
should feature prominently no matter what we’re building. Whether it’s a blogging site, personal website, or e-commerce portal, our users will expect it to be fast to load, inexpensive to maintain and secure for the end-users.
See more at: https://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi
#ecommerce #gatsby #strapi #javascript
1659414317
Apprenez à créer une boutique de commerce électronique Jamstack en utilisant Gatsby et Strapi. Nous allons construire un magasin de chaussures en ligne avec une approche étape par étape.
Commençons par une question : lors de la création d'un site Web ou d'une application de nos jours, quels sont les principaux éléments à prendre en compte ?
Eh bien, il existe de nombreuses réponses potentielles à cette question, mais speed
, cost
, et security
devraient figurer en bonne place, peu importe ce que nous construisons. Qu'il s'agisse d'un site de blogs, d'un site Web personnel ou d'un portail de commerce électronique, nos utilisateurs s'attendent à ce qu'il soit rapide à charger, peu coûteux à entretenir et sécurisé pour les utilisateurs finaux.
Heureusement, l' architecture Jamstack peut nous aider sur les trois plans.
Jamstack nous permet de créer des sites Web statiques à l'aide de balisages prédéfinis, d'API sans serveur… même de données du CMS. Ces sites statiques sont plus rapides que l'alternative, car les balisages sont prédéfinis et servis en toute sécurité à partir d'un CDN sécurisé (au lieu d'un serveur d'origine).
Et il existe tout un écosystème technologique qui prend en charge la création d'applications Jamstack. Dans cet article, nous aborderons deux de ces technologies les plus connues : Gatsby
et Strapi.
Nous les utiliserons pour créer une application de commerce électronique - un magasin de chaussures en ligne appelé, eh bien, shoes.
Original, n'est-ce pas ?
Gatsby est un générateur de site statique basé sur React spécialement conçu pour créer des balisages prédéfinis et offre une plate-forme cloud unifiée pour créer, prévisualiser et héberger vos applications. Il est super rapide, facile à intégrer à diverses sources de données et il est livré avec une pléthore d'écosystèmes de plug-ins.
Strapi, d'autre part, est une application open source hautement personnalisable qui vous aide à créer des API plus rapidement et à gérer facilement votre contenu. Tout client frontal peut consommer les API à l'aide de REST ou de GraphQL, et vous pouvez auto-héberger facilement une application Strapi sur un fournisseur comme Heroku.
Les deux programmes s'accordent parfaitement : tandis que Gatsby fournit un front-end plus rapide, Strapi résout le besoin d'un datastore back-end et d'un système de gestion de contenu (CMS).
Ok, maintenant vous savez ce que Gatsby et Strapi peuvent offrir, voyons comment ils fonctionnent en pratique en créant l' shoes
application.
shoes
applicationNous allons diviser l' shoes
application en deux parties principales :
datastore
: Cela nécessite le Strapi
projet, avec tout le contenu et les API nécessaires à l'application.client
: Cela repose sur le Gatsby
projet, qui utilise des API, avec l'aide de GraphQL, pour récupérer le contenu de Strapi et le restituer dans de belles interfaces utilisateur.Tout d'abord, nous allons configurer l' datastore
utilisation de Strapi. Veuillez noter que vous devez avoir installé Node.js pour exécuter l'application localement. Vous avez également la possibilité d'installer du fil , mais si vous n'avez pas de fil, veuillez utiliser le à la npm
place.
datastore
utilisationStrapi
Strapi fournit un tas de modèles pour démarrer rapidement avec l'application. Comme notre magasin de chaussures est une application de commerce électronique, nous utiliserons le ecommerce
modèle pour créer le fichier datastore
.
Pour cela, il suffit de créer un shoes
dossier et d'ouvrir une invite de commande (ou un terminal) sur le répertoire shoes.
Maintenant, utilisez la commande suivante pour créer un projet Strapi :
yarn create strapi-app datastore --template ecommerce
Veuillez noter que nous avons fourni un nom de projet datastore
et le modèle comme ecommerce
dans la commande ci-dessus.
La commande prendra un certain temps pour télécharger les dépendances requises, les installer et les configurer pour vous. Cependant, une fois cela fait, l'application Strapi sera accessible sur votre navigateur en utilisant l'URL [localhost:1337](http://localhost:1337)
.
Il est également important de se rappeler que vous devez enregistrer votre profil pour la première fois pour créer vos informations d'identification. Ces mêmes informations d'identification seront utilisées pour s'authentifier dans Strapi, veuillez donc prendre le temps de remplir les informations obligatoires et de vous inscrire.
Après votre inscription, vous arriverez sur la page d'accueil de Strapi. Cela vous donnera les indications dont vous avez besoin pour créer la structure de contenu, rejoindre des communautés et remplir de nombreuses autres fonctions.
Nous allons maintenant commencer à créer le types
dans Strapi. Vous pouvez considérer ces types comme des tables avec un schéma dans la base de données relationnelle.
Pour notre application, nous voulons créer des données de chaussures en tant que Product
type. Chaque produit de chaussure aura ses propres méta-informations, comme le nom, le prix, la description, le stock, la catégorie et la société.
Nous allons également gérer Category
et Company
en tant que types indépendants et créer des relations avec le Product
type.
Alors, commençons à créer les types un par un. Tout d'abord, créez les champs suivants pour le Category
type :
De même, vous pouvez créer un type de société avec les champs nom et slug.
Et maintenant, nous allons créer le type de produit, avec les champs indiqués dans l'image ci-dessous.
La plupart des champs ci-dessus sont explicites. Cependant, quelques champs nécessitent des explications.
Media
. Dans Strapi, vous pouvez télécharger des ressources (images, vidéos, fichiers) dans la médiathèque pour les utiliser plus tard.Comme tous les types requis sont maintenant créés, nous pouvons commencer à créer des exemples de données dans Strapi. Tout d'abord, téléchargeons quelques images de chaussures sympas. Vous pouvez les collecter à partir d'un site Web multimédia comme unsplash
et télécharger des éléments à partir du Media Library
menu.
Ensuite, parcourez l'option Content Manager dans la navigation de gauche et commencez à créer des entrées pour le type de catégorie. Vous pouvez créer les catégories mentionnées dans l'image ci-dessous, ou n'hésitez pas à créer les vôtres.
De même, insérez des entrées pour les données de l'entreprise.
Enfin, entrez les données pour le type de produit.
Jusqu'à présent, nous avons créé tout le contenu requis dans Strapi et sommes sur le point d'utiliser tous les éléments de l'interface utilisateur, avec les API Strapi. Vous pouvez accéder aux API Strapi en utilisant REST vers GraphQL, mais n'oubliez pas que vous devez obtenir un jeton d'API pour effectuer des appels d'API réussis.
Cliquez sur Paramètres> Paramètres globaux> Jetons API dans la barre de navigation de gauche, puis cliquez sur le Create new API Token
bouton pour créer un jeton d'accès complet pour l'application chaussures. Veuillez garder ce jeton en sécurité avec vous, car nous l'utiliserons sous peu.
client
utilisationGatsby
Nous avons réussi à configurer le datastore
avec Strapi, et il est maintenant temps de configurer le client
côté avec Gatsby
.
Pour ce faire, ouvrez une autre invite de commande/terminal dans le dossier racine du projet et exécutez la commande suivante.
yarn global add gatsby-cli
Cette commande installera globalement l'interface de ligne de commande (CLI) Gatsby. Cela nous aide à interagir avec le framework Gatsby pour effectuer différentes tâches.
Tout comme Strapi, Gatsby est livré avec plusieurs modèles pour créer un projet. Dans le monde Gatsby, ceux-ci sont appelés "modèles de démarrage". Nous utiliserons le modèle de démarrage par défaut pour créer le projet et nommer le fichier client
.
Veuillez exécuter la commande suivante pour créer le projet Gatsby.
npx gatsby new client https://github.com/gatsbyjs/gatsby-starter-default
La commande ci-dessus prendra un certain temps et créera la structure du projet pour vous. Maintenant, accédez au client
répertoire et démarrez l'application localement à l'aide de la gatsby develop
commande.
cd client
gatsby develop
L'application Gatsby s'exécutera sur l' [localhost:8000](http://localhost:8000)
URL et vous verrez une interface utilisateur comme celle-ci lorsque vous y accéderez à l'aide de votre navigateur. Il s'agit d'une page par défaut du modèle de démarrage que nous avons utilisé. Nous le changerons bientôt.
Nous allons donc maintenant réunir Gatsby et Strapi pour donner forme à notre application. Nous appellerons les API Strapi de Gatsby et récupérerons les données des chaussures au moment de la construction.
L'écosystème de plug-ins Gatsby a un plug-in source appelé gatsby-source-strapi
qui aide à récupérer les données de Strapi à l'aide de GraphQL. Installons ce plug-in et quelques autres dépendances pour gérer les images et la transformation. Veuillez exécuter la commande suivante à partir du terminal dans le client
répertoire.
yarn add gatsby-source-strapi gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-remark gatsby-transformer-sharp
Créez un fichier appelé .env.development
à la racine du client
dossier, avec le contenu suivant.
STRAPI_TOKEN=<STRAPI-API-TOKEN>
GATSBY_STRAPI_API_URL=http://localhost:1337
Voici le <STRAPI-API-TOKEN>
jeton que vous avez copié lors de la configuration du magasin de données Strapi. Vous pouvez maintenant importer le client
projet dans votre éditeur de code préféré (comme VS Code dans mon cas).
Maintenant, ouvrez le gatsby-config.js
fichier et remplacez le contenu par le contenu ci-dessous. Il s'agit d'un fichier de configuration qui définit les métadonnées du site et les options de plug-in.
Examinez de plus près les options que nous avons définies pour le gatsby-source-strapi
plug-in : nous avons spécifié l'URL de l'API Strapi, le jeton d'API et le nom des types de collection avec lesquels nous voulons interagir.
require("dotenv").config({
path: `.env.${process.env.NODE_ENV}`,
})
module.exports = {
siteMetadata: {
title: `Shoes`,
description: `The one stop shop for your shoes and footwear needs.`,
author: `@tapasadhikary`,
siteUrl: `https://shoes.io/`,
},
plug-ins: [
"gatsby-plugin-gatsby-cloud",
{
resolve: "gatsby-source-strapi",
options: {
apiURL: process.env.STRAPI_API_URL || "http://localhost:1337",
accessToken: process.env.STRAPI_TOKEN,
collectionTypes: [
{
singularName: "product",
},
{
singularName: "company",
},
{
singularName: "category",
},
],
},
},
"gatsby-plugin-image",
"gatsby-plugin-sharp",
"gatsby-transformer-sharp",
"gatsby-transformer-remark",
],
}
Veuillez arrêter et redémarrer la gatsby develop
fonction et accéder à l'URL http://localhost:8000/__graphql
pour ouvrir l'explorateur GraphQL de Gatsby.
Gatsby fournit l'explorateur GraphQL en tant qu'outil de développement, ce qui vous permet de créer facilement les requêtes GraphQL. Vous devez localiser tous les types de collection Strapi dans la Explorer
colonne la plus à gauche : ils commencent tous par le texte allStrapi
.
Bon, essayons maintenant de créer un exemple de requête pour la allStrapiProduct
collection. Vous pouvez développer la collection et sélectionner les champs pour lesquels vous souhaitez récupérer les données ; vous verrez une requête GraphQL créée automatiquement, en fonction de votre sélection.
Vous pouvez maintenant exécuter la requête en appuyant sur le bouton "Exécuter" dans l'en-tête du panneau du milieu. Vous pouvez trouver la sortie dans le panneau le plus à droite.
Je vous suggère de passer du temps avec l'explorateur GraphQL et de jouer avec les requêtes pour vous y habituer.
Pour construire les requêtes GraphQL, nous les utiliserons pour créer les composants de l'interface utilisateur. Gatsby est basé sur React, vous pouvez donc utiliser toute la puissance de la bibliothèque React dans Gatsby. Ouvrez simplement le index.js
fichier et remplacez le contenu existant par le code suivant.
// index.js
import * as React from "react"
import Layout from "../components/layout"
import Seo from "../components/seo"
import ShoeList from "../components/ShoeList"
import { useStaticQuery, graphql } from "gatsby"
import '../style/shoes.css'
const IndexPage = () => {
const { allStrapiProduct } = useStaticQuery(graphql`
query {
allStrapiProduct(sort: {order: ASC, fields: title}) {
edges {
node {
image {
url
}
slug
price
title
id
stock
status
}
}
}
}
`)
return (
<Layout>
<Seo title="Home" />
<ShoeList shoes={allStrapiProduct.edges} />
</Layout>
)
}
export default IndexPage
Examinons maintenant le code du index.js
fichier. Nous utilisons une requête GraphQL pour récupérer tous les produits triés par titre de produit dans l'ordre croissant. Gatsby nous fournit un hook React appelé useStaticQuery
pour effectuer une requête GraphQL.
Ensuite, nous passons le tableau de produits récupéré (chaussures) comme accessoire au ShoeList
composant. Nous devons créer le composant qui itérera sur le shoes
tableau et commencer à créer une disposition de carte pour chaque détail de chaussure.
Pour ce faire, veuillez créer un fichier appelé ShowList.js
sous le components
dossier avec le contenu suivant.
// ShoeList.js
import * as React from "react"
import ShoeCard from "./ShoeCard"
const ShoeList = ({shoes}) => {
console.log(shoes);
return (
<div className="shoe-list">
{shoes.map((shoe) => (
<ShoeCard key={shoe.node.id} shoe={shoe.node} />
))}
</div>
)
}
export default ShoeList
Comme vous le remarquez dans le code ci-dessus, nous retirons chaque détail de chaussure et les transmettons comme accessoires à un autre composant, ShoeCard. Vous devez donc créer un fichier appelé ShoeCard.js
sous le components
dossier, avec le contenu suivant.
// ShoeCard.js
import * as React from "react"
import { Link } from "gatsby"
const ShoeCard = ({ shoe }) => {
return (
<Link
to={`/${shoe.slug}`}
className="shoe-card" >
<div className="img-container">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="details">
<h2>{shoe.title} - ${shoe.price}</h2>
</div>
</Link>
)
}
export default ShoeCard
Le composant ShoeCard affiche l'image, le titre et le prix de la chaussure. Plus tard, nous ne révélerons le titre et le prix que lorsque l'utilisateur survolera une image de chaussure en utilisant les styles CSS.
Notez également que la carte de chaussures est enveloppée d'un fichier Link
. Le composant Link provient de Gatsby et nous aide à établir un lien entre les pages d'une application Gatsby. Le composant Lien a un attribut que nous utilisons pour créer un lien vers une page de destination. Dans l'exemple ci-dessus, la valeur de l'attribut est la valeur de slug de chaque chaussure.
Nous avons l'intention d'accéder à une nouvelle page lorsque l'utilisateur clique sur une carte de chaussures ; cette nouvelle page affichera plus de détails sur une chaussure et les options d'achat. Mais nous devons faire quelques changements, et nous le ferons plus tard. Tout d'abord, nous devons nous concentrer sur la préparation de la page de liste de chaussures avec tout le style.
Modifions un peu les composants Layout et Header. Tout d'abord, remplacez le contenu du layout.js
fichier par le contenu suivant. Il est assez similaire au fichier layout.js existant fourni avec le modèle, mais nous avons apporté quelques modifications mineures au style.
// layout.js
import * as React from "react"
import PropTypes from "prop-types"
import { useStaticQuery, graphql } from "gatsby"
import Header from "./header"
import "./layout.css"
const Layout = ({ children }) => {
const data = useStaticQuery(graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
}
`)
return (
<>
<Header siteTitle={data.site.siteMetadata?.title || `Title`} />
<div className="container">
<main className="content">{children}</main>
<footer>
© {new Date().getFullYear()} · Built with ❤️ by <a href="https://www.tapasadhikary.com">Tapas Adhikary</a>
</footer>
</div>
</>
)
}
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
Voici le contenu du Header.js
fichier que vous devez remplacer dans le fichier existant.
// Header.js
import * as React from "react"
import PropTypes from "prop-types"
import { Link } from "gatsby"
const Header = ({ siteTitle }) => (
<header>
<Link to="/" className="logo">
👠 {siteTitle}
</Link>
</header>
)
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
Maintenant, créons un style
dossier sous le src
répertoire. Pour ce faire, créez un shoes.css
fichier sous le style
dossier avec le contenu suivant.
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500&display=swap");
*,
*::after,
*::before {
margin: 0;
padding: 0;
box-sizing: border-box;
scroll-behavior: smooth;
}
html {
overflow: auto;
}
body {
height: 100vh;
background-color: rgb(3, 28, 34);
color: #ffffff;
font-family: "Poppins", sans-serif;
}
a {
text-decoration: none;
color: #ffffff;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #282d2e;
padding-left: 0.5rem;
padding-right: 0.5rem;
margin: 0 0 0.5rem 0;
}
header .logo {
font-size: 2rem;
font-weight: 500;
color: #ffffff;
padding: 0.5rem;
}
footer {
width: 100%;
padding: 0.3rem;
background-color: #282d2e;
text-align: center;
}
footer > a {
color: #1af41a;
text-decoration: underline;
}
.btn {
padding: 10px;
cursor: pointer;
font-size: 18px;
border: none;
border-radius: 10px;
}
.btn.btn-primary {
background-color: #40ee10;
color: #000000;
}
.btn.btn-primary:hover {
background-color: #70e007;
color: #000000;
}
.btn.btn-secondary {
background-color: #ffffff;
color: #282d2e;
}
.btn.btn-secondary:hover {
background-color: #282d2e;
color: #ffffff;
}
.container {
height: calc(100vh - 73px);
overflow: hidden;
display: flex;
flex-direction: column;
}
.content {
flex-grow: 1;
overflow: auto;
}
.shoe-list {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
}
.shoe-card {
position: relative;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
width: 15rem;
height: 15rem;
margin: 1.2rem;
}
.shoe-card .img-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 2;
transition: all 0.5s ease-in-out;
}
.shoe-card .img-container > IMG {
width: 15rem;
height: 15rem;
object-fit: cover;
resize: both;
border-radius: 10px;
}
.shoe-card:hover .img-container {
transform: translate(-1rem, -1rem);
}
.shoe-card:hover .details {
transform: translate(1rem, 1rem);
}
.shoe-card .details {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
padding: 0.5rem;
display: flex;
background-color: #fff;
z-index: 1;
align-items: flex-end;
transition: 0.5s ease-in-out;
line-height: 1rem;
border-radius: 10px;
}
.shoe-card .details h2 {
display: block;
font-size: 1rem;
color: #000000;
font-weight: 500;
}
Et c'est tout!
Exécutez maintenant l'application localement en utilisant l'URL [http://localhost:8000](http://localhost:8000)
et vous verrez la liste des images de chaussures sur la page. Passez votre souris sur les images de chaussures et une animation révélera le nom de la chaussure et le prix.
C'est génial. Alors maintenant, essayez de cliquer sur l'une des cartes de chaussures.
Aie! vous obtenez une page comme ci-dessous, et elle semble cassée. Il a essayé de naviguer vers une page identifiée par la valeur de slug de la chaussure, sans succès.
Mais pas de soucis, nous pouvons résoudre le problème.
Gatsby peut créer des pages au moment de la construction à l'aide de modèles. Ceux-ci exploitent la même structure d'interface utilisateur que vous souhaitez utiliser pour un ensemble de données différent.
Par exemple, dans notre shoes
application, nous souhaitons afficher les détails de chacune des chaussures. La structure de la page de détails sera la même, mais les données de la chaussure changeront en fonction de l'image de la chaussure sur laquelle nous cliquons.
Ainsi, nous pouvons créer un modèle appelé shoe-details.js
sous le src/templates
dossier avec le contenu suivant.
// shoe-details.js
import React, {useState} from "react"
import { Link, graphql } from "gatsby"
import Layout from "../components/layout"
export default function ShoeDetails({ data }) {
const shoe = data.strapiProduct
const [quantity, setQuantity] = useState(1)
return (
<Layout>
<div className="shoe-details">
<div className="cover">
<img src={`${process.env.GATSBY_STRAPI_API_URL}${shoe.image.url}`} alt={shoe.title} />
</div>
<div className="info">
<div className="info-heading">
<h2>{shoe.title}</h2>
<Link to={`/category/${shoe.categories[0].slug}`}>
<span>{shoe.categories[0].name}</span>
</Link> { ' '}
from {' '}
<Link to={`/company/${shoe.company.slug}`}>
{shoe.company.name}
</Link>
</div>
<div className="info-body">
<p>{shoe.description}</p>
<span>${shoe.price} per unit</span> { ' - '}
<>
{
shoe.stock > 0 ?
<span>{shoe.stock} In Stock</span> :
<span>Out of Stock</span>
}
</>
</div>
<div className="info-purchase">
{
shoe.stock > 0 ?
<>
<p>
I want to purchase {' '}
<input
type="number"
min="1"
max={shoe.stock}
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/> {' '} unit
</p>
<p className="price">Total Price: ${quantity * shoe.price}</p>
<button className="btn btn-primary">Add to Cart</button>
</> :
<>
<p>OOPS!!! That's gone. We will let you know when the fresh stock is available.</p>
<button className="btn btn-secondary">Notify Me!</button>
</>
}
</div>
</div>
</div>
</Layout>
)
}
export const query = graphql`
query($slug: String!) {
strapiProduct(slug: {eq: $slug}) {
id
title
price
status
stock
categories {
name
slug
}
company {
name
slug
}
description
image {
url
}
updatedAt
}
}
`
Dans le code ci-dessus, nous effectuons une requête GraphQL pour récupérer les détails d'un produit (chaussure) en fonction de la valeur du slug.
Nous pouvons utiliser les détails du produit pour construire la structure lorsque nous récupérons les détails du produit. Dans ce cas, la structure comprend la photo du produit et des informations telles que la catégorie, l'entreprise, le prix et le stock. La page comprend également la zone de saisie du numéro pour spécifier la quantité de chaussures nécessaires et calculer automatiquement le montant total à payer pour un paiement.
Tout cela est formidable, mais comment obtenir la valeur de slug de la chaussure et la mapper avec le shoe-details
modèle ? Essayons de le faire maintenant.
Ouvrez le gatsby-node.js
fichier et remplacez le contenu par le code suivant :
// gatsby-node.js
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allStrapiProduct {
edges {
node {
slug
}
}
}
}
`)
data.allStrapiProduct.edges.forEach(edge => {
const slug = edge.node.slug
actions.createPage({
path: slug,
component: require.resolve(`./src/templates/shoe-details.js`),
context: { slug: slug },
})
})
}
Gatsby exécute le gatsby-node.js
fichier au moment de la construction. Ici, nous récupérons les slugs pour tous les produits, nous pouvons ensuite intégrer les slugs et créer des pages pour chacun d'eux.
La createPage
méthode prend un objet comme argument où nous fournissons les détails du chemin référencé avec le slug et mappons à quel composant. Veuillez noter que le composant est le fichier de modèle que nous avions vu ci-dessus. Nous transmettons également les données de contexte qui sont le slug lui-même.
Ainsi, chaque chemin avec la valeur slug est maintenant mappé au fichier de modèle, avec la valeur slug transmise comme contexte. Nous avons déjà appris comment le composant de modèle utilise cette valeur de slug et récupère les détails du produit. J'espère que tous les points sont bien connectés maintenant.
Ouvrez maintenant le shoes.css
fichier et ajoutez les styles suivants sous ceux existants. Les styles suivants sont pour la page des détails de la chaussure.
.shoe-details {
padding: 1rem;
display: flex;
justify-content: space-around;
align-items: center;
}
.shoe-details .cover {
display: flex;
align-content: center;
justify-content: center;
}
.shoe-details .cover > IMG {
width: 30rem;
height: 30rem;
border-radius: 50%;
}
.shoe-details .info-heading {
margin-bottom: 1rem;
}
.shoe-details .info-heading > a {
color: #1af41a;
text-decoration: underline;
}
.shoe-details .info-heading > H2 {
font-size: 3rem;
}
.shoe-details .info-body > P {
margin: 0;
}
.shoe-details .info-body > SPAN {
font-size: 1.5rem;
}
.shoe-details .info-purchase {
margin: 2rem 0 0 0;
border: 1px solid #4a4545;
border-radius: 5px;
padding: 1rem;
background-color: black;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
}
.shoe-details .info-purchase .price {
font-size: 1.5rem;
font-weight: 500;
color: #ffffff;
}
.shoe-details .info-purchase INPUT {
border: 1px solid #ececec;
padding: 5px;
border-radius: 3px;
font-size: 1rem;
}
.shoe-filtered-list H2 {
font-size: 2rem;
font-weight: 500;
color: #1af41a;
margin: 0 0 1rem 1rem;
}
@media only screen and (max-width: 900px) {
.shoe-details {
padding: 1rem;
display: flex;
flex-direction: column;
justify-content: space-around;
}
}
@media only screen and (max-width: 600px) {
.shoe-details .cover > IMG {
width: 20rem;
height: 20rem;
}
}
Maintenant, redémarrez le serveur local de Gatsby et accédez à nouveau à l'application sur localhost:8000
. Cliquez sur l'une des cartes de chaussures ; vous devriez voir une page élégante, rendue avec des détails de chaussures.
Ok, c'est tout ce que nous voulions construire avec Gatsby et Strapi : un magasin de chaussures Jamstack avec quelques pages servies statiquement. Et nous l'avons fait !
Cependant, ne vous inquiétez pas : vous pouvez aller bien plus loin d'ici. Vous pouvez créer des modèles pour les catégories et les entreprises et avoir des pages pour chacune. Vous pouvez développer des fonctions de recherche et créer des options de filtrage pour les chaussures par titre, gamme de prix, entreprise et catégorie. Le code du projet est open source sous licence MIT sur GitHub.
Pour un bref récapitulatif, regardez la vidéo de démonstration rapide ci-dessous. Il s'agit d'une démo de l' shoes
application que nous avons construite dans cet article, ainsi que de quelques fonctionnalités supplémentaires mentionnées ci-dessus.
Lien : https://blog.greenroots.info/build-your-ecommerce-store-using-gatsby-and-strapi
#ecommerce #gatsby #strapi #javascript
1658819367
Hace unos meses comencé un proyecto como ingeniero de software en el que usábamos Strapi V3.
Para aquellos que no están familiarizados con Strapi, es un CMS (Sistema de gestión de contenido) de código abierto y autónomo que permite a los usuarios crear, gestionar y exponer datos gracias a un Panel de administración integrado.
En mi proyecto, rápidamente comenzamos a personalizar el Panel de administración de Strapi anulando directamente los archivos en nuestro proyecto: solo teníamos que reproducir la ruta al archivo específico que queríamos modificar.
Puede pensar en ello como si quisiera expulsar un archivo específico que necesita ser modificado. Por ejemplo, si quiero cambiar el color del botón "Publicar/Cancelar publicación" de azul a verde, tengo que:
Luego, al crear el panel de administración de Strapi, Strapi sabría que este archivo se había modificado y usaría este en lugar del anterior. Y así, el botón Publicar/Despublicar es verde.
¡Entonces Strapi V4 estaba en vivo! Y en Strapi V4, esta funcionalidad ya no está disponible.
Así que rápidamente me pregunté si todavía sería posible personalizar la interfaz de nuestro Strapi. En este artículo, le presentaré cuatro formas de personalizar su panel de administración de Strapi, comenzando con la más fácil: el uso de un complemento ya existente. Luego la técnica de opciones de configuración, seguido del método de inyección de archivos, para terminar con el más complejo: la creación de tu propio plugin.
Para ilustrar, estoy tomando el ejemplo de un medio: los escritores necesitan un CMS para escribir, editar y publicar sus artículos y eligieron Strapi V4.
Lo primero y más fácil de hacer cuando desea personalizar algo en la interfaz de su Strapi es intentar encontrar un complemento que haga lo que desea.
Para encontrar complementos, puede buscar en:
En mi caso, los editores no son grandes fans de la sintaxis markdown utilizada en RichText Object de Strapi V4, agradecerían algo más realista para ver directamente el resultado sin tener que usar el modo de vista previa.
Encontré el complemento "strapi-plugin-editorjs", que es un complemento de EditorJS para que Strapi reemplace el campo RichText que ofrece Strapi. La documentación es muy clara sobre cómo instalar y usar el complemento.
Lo único que se debe hacer en este caso es:
yarn add strapi-plugin-react-editorjs
Y después de esto, el objeto RichText en el panel de administración de Strapi usa el de EditorJS:
¿Qué sucede si el complemento que quiero no existe?
Primero, puedes modificar muy fácilmente el panel de administración de Strapi gracias a las opciones de configuración: esto se usa para las traducciones, el logotipo, el favicon, los locales disponibles, el tema, los tutoriales e incluso la notificación (ver la documentación aquí ).
Le mostraré rápidamente cómo usarlo con el archivo de traducción y cómo cambiar todos los textos de la interfaz de su Strapi.
Tienes que encontrar la traducción que quieres cambiar: por ejemplo, si quiero cambiar el título de la página de inicio de ”Bienvenido 👋” a “¡Hola, Chloé!”:
💡 Para encontrar fácilmente el archivo de traducción en la carpeta de github: puede reemplazarlo .com
por .dev
en la URL de Github que abre una pestaña de VisualStudio en su pestaña de Internet. Y luego, encuentre directamente la traducción para cambiar gracias al mensaje anterior 💡
// src/admin/app.js
export default {
config: {
translations: {
en: {
"app.components.HomePage.welcome.again": "Hi Chloé!",
},
},
},
bootstrap() {},
};
Ya verás:
💡Úselo yarn develop —watch-admin
para ver directamente las modificaciones que está aplicando sin tener que reiniciar su servidor. 💡
También es posible personalizar el Panel de administración utilizando la API de zonas de inyección sin tener que generar un complemento con injectContentManagerComponent
.
Voy a tomar un ejemplo simple para mostrarle fácilmente cómo agregar un componente personalizado en la interfaz de su Strapi: Quiero agregar un botón en la interfaz de Strapi que está imprimiendo "Hello World"
Primero cree la /extensions
carpeta src/admin
y luego puede crear su componente:
// src/admin/extensions/components/HelloWorldButton/index.js
import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";
const HelloWorldButton = () => {
return (
<Button
variant="secondary"
startIcon={<Up />}
onClick={() => alert("Hello World")}
>
Hello World
</Button>
);
};
export default HelloWorldButton;
Y luego use el injectContentManagerComponent
archivo app.js para inyectar su nuevo componente directamente en su aplicación:
// src/admin/app.js
import HelloWorldButton from "./extensions/components/HelloWorldButton";
export default {
bootstrap(app) {
app.injectContentManagerComponent("listView", "actions", {
name: "HelloWorldButton",
Component: HelloWorldButton,
});
},
};
Que está haciendo eso:
Puede elegir dónde colocar su componente gracias a los dos primeros parámetros del injectContentManagerComponent
:
Este ejemplo de inyección puede parecer un poco inútil, así que quiero presentarles un caso de uso en el que lo usé.
En mi caso, tengo una página de inicio donde se destacan algunos artículos. Estos artículos son elegidos por mis editores gracias a una relación con mi colección de “Artículos”.
Solo quiero ver en mi página de inicio los artículos que están publicados y no los que están redactados. Desafortunadamente, el selector utilizado para hacer la relación con la colección “Artículo” permite elegir entre todos los artículos (incluso los redactados). Mis redactores piensan que puede ser peligroso porque aunque haya un puntito de color que indique que aún no está publicado, es posible que algún día alguien se equivoque y ponga en portada un borrador de artículo.
En mi proyecto, he creado un componente que usa el selector nativo de Strapi pero he agregado un check para permitir que el usuario seleccione solo los artículos publicados.
NB: también puede usar este método para inyectar un componente de un complemento específico en otro utilizando el métodoinjectComponent()
que funciona de la misma manera queinjectContentManagerComponent()
(documentación aquí )
Si lo que quiere hacer es más complejo que las traducciones o agregar componentes a la interfaz de Strapi, probablemente tendrá que crear su propio complemento. Le recomiendo que lea este artículo o vea este video que son básicamente tutoriales sobre cómo crear su propio complemento.
Esta solución es más compleja y llevará mucho más tiempo que las otras dos soluciones. Si puede, es mejor utilizar la zona de inyección para ahorrar algo de tiempo.
Incluso si era globalmente más fácil y rápido personalizar el panel de administración de Strapi usando Strapi V3, no era muy estable. Este método puede verse como una expulsión de archivos: básicamente se trata de tomar un código de Strapi y reescribirlo en su propio código base, lo que crea una fuerte relación entre una biblioteca externa (Strapi) y su propio código. En cada nueva versión de Strapi, si un archivo cambiaba, también tenía que cambiar su código y encontrar dónde hacerlo y cómo hacerlo. No era muy fácil de mantener y podría romper muchas cosas si hubiera hecho muchas modificaciones.
En Strapi V4, todavía hay una conexión entre Strapi y su base de código si, por ejemplo, está reutilizando el componente de Strapi (como hice en mi ejemplo de inyección). Pero la conexión es mucho más pequeña y sus modificaciones son más estables. La elección de Strapi de eliminar el método de expulsión parece pragmática para mantener su aplicación más fácilmente.
Fuente: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/
1658819177
Há alguns meses, iniciei um projeto como engenheiro de software no qual usávamos o Strapi V3.
Para aqueles que não estão familiarizados com o Strapi, é um CMS (Sistema de Gerenciamento de Conteúdo) de código aberto e headless que permite aos usuários criar, gerenciar e expor dados graças a um painel de administração integrado.
No meu projeto, começamos rapidamente a personalizar o painel de administração do Strapi substituindo diretamente os arquivos em nosso projeto: apenas precisávamos reproduzir o caminho para o arquivo específico que queríamos modificar.
Você pode pensar nisso como se quisesse ejetar um arquivo específico que precisa ser modificado. Por exemplo, se eu quiser mudar a cor do botão “Publicar/Cancelar publicação” de azul para verde, eu tenho que:
Então, ao construir o Strapi Admin Panel, Strapi saberia que este arquivo havia sido modificado e usaria este em vez do antigo. E assim, o botão Publicar/Cancelar publicação fica verde.
Então Strapi V4 fez uma transmissão ao vivo! E no Strapi V4, essa funcionalidade não está mais disponível.
Então eu rapidamente me perguntei se ainda seria possível personalizar a interface do nosso Strapi. Neste artigo, apresentarei quatro maneiras de personalizar seu painel de administração do Strapi, começando pela mais fácil: o uso de um plugin já existente. Em seguida, a técnica de opções de configuração, seguida do método de injeção de arquivos, para finalizar com a mais complexa: a criação do seu próprio plugin.
Para ilustrar, tomo o exemplo de uma mídia: os escritores precisam de um CMS para escrever, editar e publicar seus artigos e escolheram o Strapi V4.
A primeira e mais fácil coisa a fazer quando você deseja personalizar algo na interface do seu Strapi é tentar encontrar um plugin que faça o que você deseja.
Para encontrar plugins, você pode pesquisar:
No meu caso, os editores não são grandes fãs da sintaxe markdown usada no RichText Object do Strapi V4, eles gostariam de algo mais realista para ver diretamente o resultado sem precisar usar o modo de visualização.
Encontrei o plugin "strapi-plugin-editorjs" que é um plugin EditorJS para Strapi para substituir o campo RichText oferecido pelo Strapi. A documentação é muito clara sobre como instalar e usar o plugin.
A única coisa a fazer neste caso é:
yarn add strapi-plugin-react-editorjs
E depois disso, o objeto RichText no Strapi Admin Panel usa o EditorJS:
E se o plugin que eu quero não existir?
Primeiro, você pode modificar muito facilmente o painel de administração do Strapi graças às opções de configuração: isso é usado para as traduções, o logotipo, o favicon, as localidades disponíveis, o tema, os tutoriais e até a notificação (consulte a documentação aqui ).
Vou mostrar rapidamente como usá-lo com o arquivo de traduções e como alterar todas as palavras da interface do seu Strapi.
Você precisa encontrar a tradução que deseja alterar: por exemplo, se eu quiser alterar o título da página inicial de ”Bem-vindo 👋” para “Oi Chloé!”:
💡 Para encontrar facilmente o arquivo de tradução na pasta do github: você pode substituir .com
por .dev
na URL do Github que abre uma guia do VisualStudio na sua guia de internet. E então, encontre diretamente a tradução para mudar graças à mensagem antiga 💡
// src/admin/app.js
export default {
config: {
translations: {
en: {
"app.components.HomePage.welcome.again": "Hi Chloé!",
},
},
},
bootstrap() {},
};
Você verá:
💡Use yarn develop —watch-admin
para ver diretamente as modificações que você está aplicando sem precisar reiniciar seu servidor. 💡
Também é possível personalizar o Painel Administrativo usando a API de zonas de injeção sem precisar gerar um plugin com injectContentManagerComponent
.
Vou dar um exemplo simples para mostrar facilmente como adicionar um componente personalizado na interface do seu Strapi: Eu quero adicionar um botão na interface do Strapi que está imprimindo “Hello World”
Primeiro crie a /extensions
pasta src/admin
e então você pode criar seu componente:
// src/admin/extensions/components/HelloWorldButton/index.js
import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";
const HelloWorldButton = () => {
return (
<Button
variant="secondary"
startIcon={<Up />}
onClick={() => alert("Hello World")}
>
Hello World
</Button>
);
};
export default HelloWorldButton;
E, injectContentManagerComponent
em seguida, use o arquivo app.js para injetar seu novo componente diretamente em seu aplicativo:
// src/admin/app.js
import HelloWorldButton from "./extensions/components/HelloWorldButton";
export default {
bootstrap(app) {
app.injectContentManagerComponent("listView", "actions", {
name: "HelloWorldButton",
Component: HelloWorldButton,
});
},
};
Que está fazendo isso:
Você pode escolher onde colocar seu componente graças aos dois primeiros parâmetros do injectContentManagerComponent
:
Este exemplo de injeção pode parecer um pouco inútil, então quero apresentar um caso de uso em que eu o usei.
No meu caso, tenho uma página inicial que destaca alguns artigos. Estes artigos são escolhidos pelos meus editores graças a uma relação com a minha coleção “Artigos”.
Eu só quero ver na minha página inicial os artigos que são publicados e não os que são redigidos. Infelizmente, o seletor utilizado para fazer a relação com a coleção “Artigo” permite que o usuário escolha entre todos os artigos (mesmo os redigidos). Meus escritores pensam que pode ser perigoso porque mesmo que haja um pequeno ponto de cor indicando que ainda não foi publicado, é possível que um dia alguém cometa um erro e coloque na página inicial um rascunho de artigo.
No meu projeto, criei um componente que usa o seletor nativo do Strapi, mas adicionei uma verificação para permitir que o usuário selecione apenas os artigos publicados.
NB: Você também pode usar este método para injetar um componente de um plugin específico em outro usando o métodoinjectComponent()
que funciona da mesma forma queinjectContentManagerComponent()
(documentação aqui )
Se o que você quer fazer é mais complexo do que traduções ou adicionar componentes na interface do Strapi, você provavelmente terá que criar seu próprio plugin. Eu recomendo que você leia este artigo ou veja este vídeo que são basicamente tutoriais sobre como criar seu próprio plugin.
Esta solução é mais complexa e levará muito mais tempo do que as outras duas soluções. Se puder, é melhor usar a zona de injeção para economizar tempo.
Mesmo que fosse globalmente mais fácil e rápido personalizar o Strapi Admin Panel usando o Strapi V3, não era muito estável. Este método pode ser visto como uma ejeção de arquivo: é basicamente pegar algum código do Strapi e reescrevê-lo em sua própria base de código, o que cria uma forte relação entre uma biblioteca externa (Strapi) e seu próprio código. A cada nova versão do Strapi, se um arquivo fosse alterado, você também precisava alterar seu código e descobrir onde e como fazê-lo. Não era muito fácil de manter e poderia quebrar muitas coisas se você tivesse feito muitas modificações.
No Strapi V4, ainda há uma conexão entre o Strapi e sua base de código se, por exemplo, você estiver reutilizando o componente do Strapi (como fiz no meu exemplo de injeção). Mas a conexão é bem menor e suas modificações são mais estáveis. A escolha do Strapi para remover o método de ejeção parece pragmática para manter seu aplicativo com mais facilidade.
Fonte: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/
1658815500
数ヶ月前、私はソフトウェアエンジニアとしてStrapiV3を使用するプロジェクトを開始しました。
ストラップに慣れていない人のために、それはオープンソースのヘッドレスCMS(コンテンツ管理システム)であり、ユーザーは組み込みの管理パネルのおかげでデータを作成、管理、公開することができます。
私のプロジェクトでは、プロジェクト内のファイルを直接オーバーライドすることで、Strapiの管理パネルのカスタマイズをすぐに開始しました。変更する特定のファイルへのパスを再現するだけで済みました。
変更が必要な特定のファイルを取り出したいと考えることができます。たとえば、「公開/非公開」ボタンの色を青から緑に変更したい場合は、次のことを行う必要があります。
次に、Strapi管理パネルを作成すると、Strapiはこのファイルが変更されたことを認識し、古いファイルの代わりにこのファイルを使用します。そのため、[公開/非公開]ボタンは緑色です。
その後、Strapi V4がライブになりました!また、Strapi V4では、この機能は使用できなくなりました。
それで、私はすぐに、Strapiのインターフェースをカスタマイズすることはまだ可能かどうか疑問に思いました。この記事では、Strapi管理パネルをカスタマイズする4つの方法を紹介します。最も簡単な方法、つまり既存のプラグインの使用から始めます。次に、構成オプションの手法、続いてインジェクションファイル方式を使用して、より複雑な手法である独自のプラグインの作成を完了します。
説明のために、私はメディアの例を取り上げています。ライターは記事を書き、編集し、公開するためにCMSを必要とし、StrapiV4を選択しました。
あなたがStrapiのインターフェースで何かをカスタマイズしたいときに最初にそして最も簡単なことはあなたが望むことをするプラグインを見つけようとすることです。
プラグインを見つけるには、以下を調べることができます。
私の場合、編集者は、Strapi V4のリッチテキストオブジェクトで使用されるマークダウン構文の大ファンではありません。プレビューモードを使用せずに、結果を直接表示するためのより現実的なものを高く評価します。
私は、Strapiが提供するRichTextフィールドを置き換えるStrapi用のEditorJSプラグインであるプラグイン「strapi-plugin-editorjs」を見つけました。プラグインのインストール方法と使用方法については、ドキュメントが非常に明確です。
この場合に行う唯一のことは次のとおりです。
yarn add strapi-plugin-react-editorjs
この後、Strapi管理パネルのRichTextオブジェクトはEditorJSオブジェクトを使用します。
必要なプラグインが存在しない場合はどうなりますか?
まず、構成オプションのおかげで、Strapi管理パネルを非常に簡単に変更できます。これは、翻訳、ロゴ、ファビコン、使用可能なロケール、テーマ、チュートリアル、さらには通知にも使用されます(こちらのドキュメントを参照)。
翻訳ファイルでの使用方法と、Strapiのインターフェイスのすべての文言を変更する方法を簡単に説明します。
変更したい翻訳を見つける必要があります。たとえば、ホームページのタイトルを「Welcome👋」から「HiChloé!」に変更したい場合:
💡githubフォルダー内の翻訳ファイルを簡単に見つけるには:インターネットタブにVisualStudioタブを開くGithubURL.com
のを.dev
に置き換えることができます。そして、古いメッセージのおかげで変更する翻訳を直接見つけてください💡
// src/admin/app.js
export default {
config: {
translations: {
en: {
"app.components.HomePage.welcome.again": "Hi Chloé!",
},
},
},
bootstrap() {},
};
次のように表示されます。
💡yarn develop —watch-admin
サーバーを再起動せずに、適用している変更を直接確認するために使用します。💡
でプラグインを生成せずに、インジェクションゾーンAPIを使用して管理パネルをカスタマイズすることもできますinjectContentManagerComponent
。
簡単な例を使用して、Strapiのインターフェイスにカスタムコンポーネントを追加する方法を簡単に示します。「HelloWorld」を印刷しているStrapiのインターフェイスにボタンを追加します。
最初に/extensions
フォルダをsrc/admin
作成してから、コンポーネントを作成できます。
// src/admin/extensions/components/HelloWorldButton/index.js
import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";
const HelloWorldButton = () => {
return (
<Button
variant="secondary"
startIcon={<Up />}
onClick={() => alert("Hello World")}
>
Hello World
</Button>
);
};
export default HelloWorldButton;
次にinjectContentManagerComponent
、app.jsファイルのを使用して、新しいコンポーネントをアプリに直接挿入します。
// src/admin/app.js
import HelloWorldButton from "./extensions/components/HelloWorldButton";
export default {
bootstrap(app) {
app.injectContentManagerComponent("listView", "actions", {
name: "HelloWorldButton",
Component: HelloWorldButton,
});
},
};
それをしているのは:
injectContentManagerComponent
:の最初の2つのパラメーターのおかげで、コンポーネントを配置する場所を選択できます。
この注入の例は少し役に立たないように思われるかもしれないので、私がそれを使用したユースケースを紹介したいと思います。
私の場合、いくつかの記事を紹介するホームページがあります。これらの記事は、私の「記事」コレクションとの関係のおかげで、私の編集者によって選ばれました。
公開されている記事のみをホームページに表示したいので、ドラフトされた記事は表示しません。残念ながら、「Article」コレクションとの関係を行うために使用されるセレクターでは、ユーザーはすべての記事(ドラフトされた記事も含む)から選択できます。まだ公開されていないことを示す色の点が少しあっても、いつか誰かが間違えてホームページにドラフト記事を載せてしまう可能性があるので、筆者は危険だと思っています。
私のプロジェクトでは、Strapiのネイティブセレクターを使用するコンポーネントを作成しましたが、ユーザーが公開された記事のみを選択できるようにするためにチェックを追加しました。
注意:このメソッドを使用して、 (ここのドキュメント)injectComponent()
と同じように機能するメソッドをinjectContentManagerComponent()
やりたいことが翻訳よりも複雑だったり、Strapiのインターフェースにコンポーネントを追加したりする場合は、おそらく独自のプラグインを作成する必要があります。この記事を読むか、このビデオをご覧になることをお勧めします。これらは基本的に、独自のプラグインを作成する方法についてのチュートリアルです。
このソリューションはより複雑で、他の2つのソリューションよりもはるかに時間がかかります。可能であれば、時間を節約するために注入ゾーンを使用することをお勧めします。
ストラップV3を使用してストラップ管理パネルをカスタマイズすることが世界的に簡単かつ迅速であったとしても、それはあまり安定していませんでした。この方法はファイルの排出と見なすことができます。基本的には、Strapiからコードを取得し、それを独自のコードベースで書き直すことで、externライブラリ(Strapi)と独自のコードの間に強い関係を作成します。新しいバージョンのStrapiごとに、ファイルが変更された場合は、コードも変更して、どこでどのように実行するかを見つける必要がありました。それはあまり維持可能ではなく、あなたがたくさんの修正をしたならばそれは多くのことを壊すかもしれません。
ストラップV4では、たとえば、ストラップのコンポーネントを再利用している場合(インジェクションの例で行ったように)、ストラップとコードベースの間に接続があります。ただし、接続ははるかに小さく、変更はより安定しています。アプリをより簡単に維持するために、排出方法を削除するためのストラップの選択は実用的であるように思われます。
出典:https ://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/
1658815288
Il y a quelques mois, j'ai démarré un projet en tant qu'ingénieur logiciel dans lequel nous utilisions Strapi V3.
Pour ceux qui ne sont pas familiers avec Strapi, il s'agit d'un CMS (Content Management System) open source et sans tête qui permet aux utilisateurs de créer, gérer et exposer des données grâce à un panneau d'administration intégré.
Sur mon projet, nous avons rapidement commencé à personnaliser le panneau d'administration de Strapi en remplaçant directement les fichiers de notre projet : nous n'avions qu'à reproduire le chemin vers le fichier spécifique que nous voulions modifier.
Vous pouvez y penser comme si vous vouliez éjecter un fichier spécifique qui doit être modifié. Par exemple, si je veux changer la couleur d'un bouton « Publier/Dépublier » du bleu au vert, je dois :
Ensuite, lors de la construction du panneau d'administration Strapi, Strapi saurait que ce fichier a été modifié et utiliserait celui-ci à la place de l'ancien. Et donc, le bouton Publier/Dépublier est vert.
Puis Strapi V4 était en direct ! Et dans Strapi V4, cette fonctionnalité n'est plus disponible.
Je me suis donc rapidement demandé s'il serait encore possible de personnaliser l'interface de notre Strapi. Dans cet article, je vais vous présenter quatre façons de personnaliser votre panneau d'administration Strapi, en commençant par la plus simple : l'utilisation d'un plugin déjà existant. Puis la technique des options de configuration, suivie de la méthode du fichier d'injection, pour finir par la plus complexe : la création de votre propre plugin.
Pour illustrer, je prends l'exemple d'un média : les rédacteurs ont besoin d'un CMS pour rédiger, éditer et publier leurs articles et ils ont choisi Strapi V4.
La première et la plus simple chose à faire lorsque vous souhaitez personnaliser quelque chose dans l'interface de votre Strapi est d'essayer de trouver un plugin qui fait ce que vous voulez.
Pour trouver des plugins, vous pouvez consulter :
Dans mon cas, les éditeurs ne sont pas de grands fans de la syntaxe de démarquage utilisée dans l'objet RichText de Strapi V4, ils apprécieraient quelque chose de plus réaliste pour voir directement le résultat sans avoir à utiliser le mode aperçu.
J'ai trouvé le plugin "strapi-plugin-editorjs" qui est un plugin EditorJS pour Strapi pour remplacer le champ RichText proposé par Strapi. La documentation est très claire sur la façon d'installer et d'utiliser le plugin.
La seule chose à faire dans ce cas est :
yarn add strapi-plugin-react-editorjs
Et après cela, l'objet RichText dans le panneau d'administration Strapi utilise celui de EditorJS :
Que faire si le plugin que je veux n'existe pas ?
Tout d'abord, vous pouvez très facilement modifier le panneau d'administration Strapi grâce aux options de configuration : cela sert aux traductions, au logo, au favicon, aux locales disponibles, au thème, aux tutoriels et même à la notification (voir la documentation ici ).
Je vais vous montrer rapidement comment l'utiliser avec le fichier de traductions et comment changer tous les libellés de l'interface de votre Strapi.
Vous devez trouver la traduction que vous voulez changer : par exemple si je veux changer le titre de la page d'accueil de "Bienvenue 👋" à "Salut Chloé !" :
💡 Pour retrouver facilement le fichier de traduction dans le dossier github : vous pouvez remplacer le .com
par .dev
dans l' URL Github qui ouvre un onglet VisualStudio dans votre onglet internet. Et puis, retrouvez directement la traduction à modifier grâce à l'ancien message 💡
// src/admin/app.js
export default {
config: {
translations: {
en: {
"app.components.HomePage.welcome.again": "Hi Chloé!",
},
},
},
bootstrap() {},
};
Tu verras:
💡Utilisez yarn develop —watch-admin
afin de voir directement les modifications que vous appliquez sans avoir à relancer votre serveur. 💡
Il est également possible de personnaliser le panneau d'administration à l'aide de l'API des zones d'injection sans avoir à générer de plugin avec injectContentManagerComponent
.
Je vais prendre un exemple simple pour vous montrer facilement comment ajouter un composant personnalisé dans l'interface de votre Strapi : je veux ajouter un bouton sur l'interface de Strapi qui affiche "Hello World"
Créez d'abord le /extensions
dossier dans src/admin
puis vous pourrez créer votre composant :
// src/admin/extensions/components/HelloWorldButton/index.js
import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";
const HelloWorldButton = () => {
return (
<Button
variant="secondary"
startIcon={<Up />}
onClick={() => alert("Hello World")}
>
Hello World
</Button>
);
};
export default HelloWorldButton;
Puis utilisez le injectContentManagerComponent
dans le fichier app.js pour injecter votre nouveau composant directement dans votre application :
// src/admin/app.js
import HelloWorldButton from "./extensions/components/HelloWorldButton";
export default {
bootstrap(app) {
app.injectContentManagerComponent("listView", "actions", {
name: "HelloWorldButton",
Component: HelloWorldButton,
});
},
};
Qui fait ça :
Vous pouvez choisir où placer votre composant grâce aux deux premiers paramètres du injectContentManagerComponent
:
Cet exemple d'injection peut sembler un peu inutile alors je souhaite vous présenter un cas d'utilisation dans lequel je l'ai utilisé.
Dans mon cas, j'ai une page d'accueil qui met en avant certains articles. Ces articles sont choisis par mes rédacteurs grâce à une relation avec ma collection « Article ».
Je ne veux voir dans ma page d'accueil que les articles qui sont publiés et non ceux qui sont rédigés. Malheureusement, le sélecteur utilisé pour faire la relation avec la collection « Article » permet aux utilisateurs de choisir entre tous les articles (même ceux rédigés). Mes rédacteurs pensent que cela peut être dangereux car même s'il y a un petit point de couleur indiquant qu'il n'est pas encore publié, il est possible qu'un jour quelqu'un se trompe et mette en page d'accueil un brouillon d'article.
Dans mon projet, j'ai créé un composant qui utilise le sélecteur natif de Strapi mais j'ai ajouté une coche afin de permettre à l'utilisateur de ne sélectionner que les articles publiés.
NB : Vous pouvez également utiliser cette méthode pour injecter un composant d'un plugin spécifique dans un autre en utilisant la méthodeinjectComponent()
qui fonctionne de la même manière queinjectContentManagerComponent()
(documentation ici )
Si ce que vous voulez faire est plus complexe que des traductions ou ajouter des composants dans l'interface de Strapi, vous devrez probablement créer votre propre plugin. Je vous recommande de lire cet article ou de voir cette vidéo qui sont essentiellement des tutos sur la façon de créer votre propre plugin.
Cette solution est plus complexe et prendra beaucoup plus de temps que les deux autres solutions. Si vous le pouvez, il est préférable d'utiliser la zone d'injection afin de gagner du temps.
Même s'il était globalement plus facile et plus rapide de personnaliser le panneau d'administration de Strapi avec Strapi V3, ce n'était pas très stable. Cette méthode peut être vue comme une éjection de fichier : il s'agit essentiellement de prendre du code de Strapi et de le réécrire dans votre propre base de code, ce qui crée une relation forte entre une bibliothèque externe (Strapi) et votre propre code. A chaque nouvelle version de Strapi si un fichier changeait il fallait aussi changer son code et trouver où le faire et comment le faire. Ce n'était pas très facile à entretenir et cela pouvait casser beaucoup de choses si vous aviez fait beaucoup de modifications.
Dans Strapi V4, il existe toujours une connexion entre Strapi et votre base de code si, par exemple, vous réutilisez le composant de Strapi (comme je l'ai fait dans mon exemple d'injection). Mais la connexion est beaucoup plus petite et vos modifications sont plus stables. Le choix de Strapi pour supprimer la méthode d'éjection semble pragmatique afin de maintenir plus facilement votre application.
Source : https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/
1658811600
Vài tháng trước, tôi bắt đầu một dự án với tư cách là kỹ sư phần mềm, trong đó chúng tôi đang sử dụng Strapi V3.
Đối với những người không quen thuộc với Strapi, đây là một CMS (Hệ thống quản lý nội dung) mã nguồn mở, không có đầu cho phép người dùng tạo, quản lý và hiển thị dữ liệu nhờ Bảng quản trị tích hợp sẵn.
Trong dự án của mình, chúng tôi nhanh chóng bắt đầu tùy chỉnh Bảng điều khiển quản trị của Strapi bằng cách ghi đè trực tiếp các tệp trong dự án của mình: chúng tôi chỉ cần tạo lại đường dẫn đến tệp cụ thể mà chúng tôi muốn sửa đổi.
Bạn có thể nghĩ về nó như thể bạn muốn đẩy một tệp cụ thể cần được sửa đổi. Ví dụ: nếu tôi muốn thay đổi màu của nút “Xuất bản / Hủy xuất bản” từ xanh lam sang xanh lục, tôi phải:
Sau đó, khi xây dựng Bảng quản trị Strapi, Strapi sẽ biết rằng tệp này đã được sửa đổi và sẽ sử dụng tệp này thay vì tệp cũ. Và do đó, nút Xuất bản / Hủy xuất bản có màu xanh lục.
Sau đó, Strapi V4 đã được phát hành! Và trong Strapi V4, chức năng này không còn nữa.
Vì vậy, tôi nhanh chóng tự hỏi liệu có còn có thể tùy chỉnh giao diện Strapi của chúng tôi hay không. Trong bài viết này, tôi sẽ trình bày cho bạn bốn cách để tùy chỉnh Bảng quản trị Strapi của bạn, bắt đầu với cách dễ nhất: sử dụng một plugin đã có sẵn. Sau đó, kỹ thuật tùy chọn cấu hình, tiếp theo là phương pháp tệp tiêm, để kết thúc với một kỹ thuật phức tạp hơn: tạo plugin của riêng bạn.
Để minh họa, tôi đang lấy ví dụ về một phương tiện truyền thông: người viết cần một CMS để viết, chỉnh sửa và xuất bản các bài báo của họ và họ đã chọn Strapi V4.
Điều đầu tiên và dễ dàng nhất cần làm khi bạn muốn tùy chỉnh một thứ gì đó trong giao diện của Strapi là thử và tìm một plugin thực hiện những gì bạn muốn.
Để tìm các plugin, bạn có thể xem:
Trong trường hợp của tôi, các biên tập viên không phải là người hâm mộ lớn của cú pháp đánh dấu được sử dụng trong Đối tượng RichText của Strapi V4, họ sẽ đánh giá cao thứ gì đó thực tế hơn để xem trực tiếp kết quả mà không cần phải sử dụng chế độ xem trước.
Tôi đã tìm thấy plugin "strapi-plugin-editorjs" là một plugin EditorJS dành cho Strapi để thay thế trường RichText do Strapi cung cấp. Tài liệu hướng dẫn rất rõ ràng về cách cài đặt và sử dụng plugin.
Điều duy nhất cần làm trong trường hợp này là:
yarn add strapi-plugin-react-editorjs
Và sau đó, đối tượng RichText trong Bảng điều khiển quản trị Strapi sử dụng EditorJS một:
Điều gì xảy ra nếu plugin tôi muốn không tồn tại?
Đầu tiên, bạn có thể rất dễ dàng sửa đổi Bảng quản trị Strapi nhờ các tùy chọn cấu hình: tùy chọn này được sử dụng cho các bản dịch, biểu trưng, biểu tượng yêu thích, các ngôn ngữ có sẵn, chủ đề, hướng dẫn và thậm chí cả thông báo (xem tài liệu tại đây ).
Tôi sẽ nhanh chóng chỉ cho bạn cách sử dụng nó với tệp bản dịch và cách thay đổi tất cả các từ ngữ trong giao diện Strapi của bạn.
Bạn phải tìm bản dịch mà bạn muốn thay đổi: ví dụ: nếu tôi muốn thay đổi tiêu đề của trang chủ từ "Chào mừng 👋" thành "Xin chào Chloé!":
💡 Để dễ dàng tìm thấy tệp bản dịch trong thư mục github: bạn có thể thay thế .com
bằng .dev
trong URL Github mở tab VisualStudio trong tab internet của bạn. Và sau đó, tìm trực tiếp bản dịch để thay đổi nhờ tin nhắn cũ 💡
// src/admin/app.js
export default {
config: {
translations: {
en: {
"app.components.HomePage.welcome.again": "Hi Chloé!",
},
},
},
bootstrap() {},
};
Bạn sẽ thấy:
💡Sử dụng yarn develop —watch-admin
để xem trực tiếp các sửa đổi bạn đang áp dụng mà không cần phải khởi chạy lại máy chủ của bạn. 💡
Cũng có thể tùy chỉnh Bảng điều khiển quản trị bằng cách sử dụng API vùng tiêm mà không cần phải tạo một plugin với injectContentManagerComponent
.
Tôi sẽ lấy một ví dụ đơn giản để cho bạn thấy dễ dàng cách thêm một thành phần tùy chỉnh vào giao diện Strapi của bạn: Tôi muốn thêm một nút trên giao diện của Strapi đang in “Hello World”
Đầu tiên hãy tạo /extensions
thư mục trong src/admin
và sau đó bạn có thể tạo thành phần của mình:
// src/admin/extensions/components/HelloWorldButton/index.js
import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";
const HelloWorldButton = () => {
return (
<Button
variant="secondary"
startIcon={<Up />}
onClick={() => alert("Hello World")}
>
Hello World
</Button>
);
};
export default HelloWorldButton;
Và sau đó sử dụng injectContentManagerComponent
trong tệp app.js để đưa thành phần mới của bạn trực tiếp vào ứng dụng của bạn:
// src/admin/app.js
import HelloWorldButton from "./extensions/components/HelloWorldButton";
export default {
bootstrap(app) {
app.injectContentManagerComponent("listView", "actions", {
name: "HelloWorldButton",
Component: HelloWorldButton,
});
},
};
Mà đang làm điều đó:
Bạn có thể chọn nơi đặt thành phần của mình nhờ vào hai tham số đầu tiên của injectContentManagerComponent
:
Ví dụ về tiêm này có vẻ hơi vô dụng vì vậy tôi muốn giới thiệu cho bạn một trường hợp sử dụng mà tôi đã sử dụng nó.
Trong trường hợp của tôi, tôi có một trang chủ làm nổi bật một số bài báo. Những bài báo này được chọn bởi các biên tập viên của tôi nhờ vào mối quan hệ với bộ sưu tập "Bài báo" của tôi.
Tôi chỉ muốn xem trên trang chủ của mình những bài báo đã được xuất bản chứ không phải những bài được soạn thảo. Thật không may, bộ chọn được sử dụng để thực hiện mối quan hệ với bộ sưu tập “Bài báo” cho phép người dùng lựa chọn giữa tất cả các bài báo (ngay cả những bài đã soạn thảo). Người viết của tôi nghĩ rằng nó có thể nguy hiểm vì ngay cả khi có một chút điểm màu cho thấy nó chưa được xuất bản, có thể một ngày nào đó ai đó làm sai và đưa lên trang chủ một bài báo nháp.
Trong dự án của mình, tôi đã tạo một thành phần sử dụng bộ chọn gốc của Strapi nhưng tôi đã thêm dấu kiểm để cho phép người dùng chỉ chọn các bài báo đã xuất bản.
NB: Bạn cũng có thể sử dụng phương pháp này để đưa một thành phần của một plugin cụ thể vào một plugin khác bằng cách sử dụng phương phápinjectComponent()
hoạt động giống nhưinjectContentManagerComponent()
(tài liệu ở đây )
Nếu những gì bạn muốn làm phức tạp hơn là dịch hoặc thêm các thành phần vào giao diện của Strapi, bạn có thể sẽ phải tạo plugin của riêng mình. Tôi khuyến cáo bạn đọc bài viết này hoặc xem video này về cơ bản hướng dẫn cách tạo plugin của riêng bạn.
Giải pháp này phức tạp hơn và sẽ mất nhiều thời gian hơn so với hai giải pháp còn lại. Nếu bạn có thể, tốt hơn là sử dụng vùng tiêm để tiết kiệm thời gian.
Ngay cả khi việc tùy chỉnh Bảng quản trị Strapi bằng Strapi V3 dễ dàng và nhanh chóng hơn trên toàn cầu, nó vẫn không ổn định lắm. Phương pháp này có thể được coi là một loại bỏ tệp: về cơ bản nó là lấy một số mã từ Strapi và viết lại nó trong cơ sở mã của riêng bạn, điều này tạo ra mối quan hệ chặt chẽ giữa thư viện bên ngoài (Strapi) và mã của riêng bạn. Tại mỗi phiên bản mới của Strapi, nếu một tệp thay đổi, bạn cũng phải thay đổi mã của mình và tìm nơi thực hiện và cách thực hiện. Nó không thể bảo trì được và nó có thể làm hỏng rất nhiều thứ nếu bạn đã thực hiện nhiều sửa đổi.
Trong Strapi V4, vẫn có một kết nối giữa Strapi và cơ sở mã của bạn, ví dụ: nếu bạn đang sử dụng lại thành phần của Strapi (như tôi đã làm trong ví dụ tiêm của mình). Nhưng kết nối nhỏ hơn nhiều và các sửa đổi của bạn ổn định hơn. Việc lựa chọn Strapi để loại bỏ phương pháp đẩy có vẻ thực dụng để duy trì ứng dụng của bạn dễ dàng hơn.
Nguồn: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/
1658811600
几个月前,我作为一名软件工程师开始了一个项目,我们在其中使用了 Strapi V3。
对于那些不熟悉 Strapi 的人来说,它是一个开源的无头 CMS(内容管理系统),借助内置的管理面板,它允许用户创建、管理和公开数据。
在我的项目中,我们很快开始通过直接覆盖项目中的文件来自定义 Strapi 的管理面板:我们只需要重现我们想要修改的特定文件的路径。
你可以把它想象成你想弹出一个需要修改的特定文件。例如,如果我想将“发布/取消发布”按钮的颜色从蓝色更改为绿色,我必须:
然后,在构建 Strapi 管理面板时,Strapi 会知道该文件已被修改,并将使用该文件而不是旧文件。因此,发布/取消发布按钮是绿色的。
然后 Strapi V4 上线了!而在 Strapi V4 中,此功能不再可用。
所以我很快想知道是否仍然可以自定义我们的 Strapi 界面。在本文中,我将向您介绍四种自定义 Strapi 管理面板的方法,从最简单的一种开始:使用现有的插件。然后是配置选项技术,然后是注入文件方法,以完成更复杂的方法:创建您自己的插件。
为了说明,我以媒体为例:作者需要一个 CMS 来编写、编辑和发布他们的文章,他们选择了 Strapi V4。
当您想在 Strapi 的界面中自定义某些内容时,要做的第一件事也是最简单的事情是尝试找到一个可以满足您需求的插件。
要查找插件,您可以查看:
在我的例子中,编辑们不是 Strapi V4 的 RichText 对象中使用的 markdown 语法的忠实拥护者,他们会欣赏更真实的东西,直接看到结果而不必使用预览模式。
我找到了插件“strapi-plugin-editorjs”,这是一个用于 Strapi 的 EditorJS 插件,用于替换 Strapi 提供的 RichText 字段。文档非常清楚如何安装和使用该插件。
在这种情况下唯一要做的是:
yarn add strapi-plugin-react-editorjs
在此之后,Strapi 管理面板中的 RichText 对象使用 EditorJS 之一:
如果我想要的插件不存在怎么办?
首先,由于配置选项,您可以非常轻松地修改 Strapi 管理面板:这用于翻译、徽标、网站图标、可用的语言环境、主题、教程甚至通知(请参阅此处的文档)。
我将快速向您展示如何将它与翻译文件一起使用以及如何更改 Strapi 界面的所有措辞。
您必须找到要更改的翻译:例如,如果我想将主页的标题从“Welcome 👋”更改为“Hi Chloé!”:
💡 要在 github 文件夹中轻松找到翻译文件:您可以替换Github URL.com
中的by .dev
,这会在您的 Internet 选项卡中打开一个 VisualStudio 选项卡。然后直接找翻译改感谢老留言💡
// src/admin/app.js
export default {
config: {
translations: {
en: {
"app.components.HomePage.welcome.again": "Hi Chloé!",
},
},
},
bootstrap() {},
};
你会看见:
💡yarn develop —watch-admin
用于直接查看您正在应用的修改,而无需重新启动您的服务器。💡
也可以使用注入区 API 自定义管理面板,而无需使用injectContentManagerComponent
.
我将举一个简单的例子来轻松地向您展示如何在 Strapi 的界面中添加自定义组件:我想在 Strapi 的界面上添加一个打印“Hello World”的按钮
首先在其中创建/extensions
文件夹,src/admin
然后您可以创建组件:
// src/admin/extensions/components/HelloWorldButton/index.js
import React from "react";
import { Button } from "@strapi/design-system/Button";
import Up from "@strapi/icons/Up";
const HelloWorldButton = () => {
return (
<Button
variant="secondary"
startIcon={<Up />}
onClick={() => alert("Hello World")}
>
Hello World
</Button>
);
};
export default HelloWorldButton;
然后使用injectContentManagerComponent
app.js 文件中的 将新组件直接注入到您的应用中:
// src/admin/app.js
import HelloWorldButton from "./extensions/components/HelloWorldButton";
export default {
bootstrap(app) {
app.injectContentManagerComponent("listView", "actions", {
name: "HelloWorldButton",
Component: HelloWorldButton,
});
},
};
这是这样做的:
由于 的前两个参数,您可以选择放置组件的位置injectContentManagerComponent
:
这个注入示例可能看起来有点无用,所以我想向您展示一个我使用它的用例。
就我而言,我有一个主页,其中突出显示了一些文章。这些文章是由我的编辑选择的,这要归功于与我的“文章”收藏的关系。
我只想在我的主页上看到已发布的文章,而不是草稿的文章。不幸的是,用于与“文章”集合建立关系的选择器允许用户在所有文章(甚至是草稿)之间进行选择。我的作者认为这可能很危险,因为即使有一点点颜色表明它还没有发表,也有可能有一天有人犯了错误并在主页上放了一篇文章草稿。
在我的项目中,我创建了一个使用 Strapi 的本机选择器的组件,但我添加了一个检查以允许用户仅选择已发布的文章。
注意:您也可以使用此方法将特定插件的组件注入另一个插件,方法injectComponent()
与(此处injectContentManagerComponent()
的文档)
如果您想要做的比翻译更复杂或在 Strapi 的界面中添加组件,您可能必须创建自己的插件。我建议你阅读这篇文章或观看这个视频,这些视频基本上是关于如何创建自己的插件的教程。
这个解决方案比其他两个解决方案更复杂,并且需要更多的时间。如果可以,最好使用注射区以节省一些时间。
即使使用 Strapi V3 自定义 Strapi 管理面板在全球范围内更容易、更快捷,它也不是很稳定。这种方法可以看作是文件弹出:它基本上是从 Strapi 中获取一些代码并在您自己的代码库中重写它,这在外部库(Strapi)和您自己的代码之间建立了牢固的关系。在 Strapi 的每个新版本中,如果文件发生更改,您还必须更改代码并找到在哪里执行以及如何执行。它不是很容易维护,如果你做了很多修改,它可能会破坏很多东西。
在 Strapi V4 中,Strapi 和您的代码库之间仍然存在连接,例如,如果您正在重用 Strapi 的组件(就像我在注入示例中所做的那样)。但是连接要小得多,您的修改更稳定。选择 Strapi 删除弹出方法似乎很实用,以便更轻松地维护您的应用程序。
来源:https ://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/
1658805136
Few months ago, I started a project as a software engineer in which we were using Strapi V3.
For those who are not familiar with Strapi, it is an open-source, headless CMS (Content Management System) which allows users to create, manage and expose data thanks to a built-in Admin Panel.
On my project, we quickly began to customize the Strapi’s Admin Panel by directly overriding the files in our project: we just had to reproduce the path to the specific file we wanted to modify.
You can think of it as if you wanted to eject a specific file which needs to be modified. For example, if I want to change the color of a the “Publish/Unpublish” button from blue to green, I have to:
See more at: https://blog.theodo.com/2022/06/4-ways-to-build-a-custom-strapi-admin-panel/