gatsby.js 架构静态网站技术要点
程序员文章站
2022-07-12 17:40:31
...
gatsby.js 架构静态网站技术要点
静态资源加载
通过 gatsby / gatsby-image / gatsby-plugin-sharp 实现图片静态资源的加载以及渲染,支持 fluid | fixed 两种 type。
使用实例如下:
import { graphql, useStaticQuery } from 'gatsby';
import Img from 'gatsby-image';
// 加载资源
const imagesData = useStaticQuery(graphql`
query {
fixedImg: file(relativePath: { eq: "index/banner.png" }) {
childImageSharp {
fixed(width: 125, height: 125) {
...GatsbyImageSharpFixed
}
}
}
fluidImg: file(relativePath: { eq: "index/banner-desktop.png" }) {
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid
}
}
}
images: allFile(filter: { relativePath: { regex: "/index/banner/desktop/" } } sort: { fields: name }) {
edges {
node {
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid
}
}
}
}
}
`);
使用
<Img fixed={imagesData.fixedImg.childImageSharp.fixed} />
<Img fluid={imagesData.fluidImg.childImageSharp.fluid} />
{
imagesData.images.edges.map(({ node }, index) => (
<Img fluid={node.childImageSharp.fluid} key={index} />))
}
媒体查询
break-points media-size
{children} // PC 端展示
{children} // 移动端展示
@Media
css-in-js(vw布局)
styled-components / styled-px2vw
// 全局样式 覆盖 | css-reset
import { createGlobalStyle } from 'styled-components';
const GlobalStyle = createGlobalStyle``;
<Layout>
<GlobalStyle />
<OtherComponent />
</Layout>
锚点跳转缓动效果
gatsby-plugin-anchor-links
gatsby-config.js
{
resolve: `gatsby-plugin-anchor-links`,
options: {
offset: 0,
},
},
react 百度地图
import { APILoader, Map, Marker } from '@uiw/react-baidu-map';
import CustomIcon from '../../images/index/location.png';
const CustomMapIcon = props => {
const { position } = props; const icon = new window.BMap.Icon(
CustomIcon, new window.BMap.Size(38 / 3, 50 / 3)
);
return (
<Map zoom={18} center={position} enableScrollWheelZoom={true}>
<Marker position={position} icon={icon} />
</Map>
);
};
<APILoader akay="hwNeVg8yPDmLLHcwFq0iE7l5S09akIdu">
<CustomMapIcon position={{ lng: 116.410436, lat: 39.915209 }}/>
</APILoader>
轮播
import Swiper from 'react-id-swiper';
const params = {
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
slidesPerView: 1,
spaceBetween: 0,
centeredSlides: true,
freeMode: false,
grabCursor: true,
mousewheel: {
forceToAxis: true,
invert: true,
},
slideToClickedSlide: true,
};
<Swiper {...params}> {data.desktopBanner.edges.map(({ node }, index) => (
<Img fluid={node.childImageSharp.fluid} key={index} /> ))}
</Swiper>
code style
通过 prettier 统一前端代码格式。
.prettierrc 文件配置:
{
"endOfLine": "lf",
"semi": true,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "es5"
}
下一篇: poj3263 Tallest Cow