Open46

Gatsby+TypeScript+ChakraUI+MicroCMS

0Yu0Yu

add Plugin

MicroCMS
https://www.gatsbyjs.com/plugins/gatsby-source-microcms/

yarn add gatsby-source-microcms
// .env
API_KEY=
// gatsby-config.ts
const path = require('path');

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`
});
...

const config: GatsbyConfig = {
  plugins: [
    {
      resolve: 'gatsby-source-microcms',
      options: {
      apiKey: process.env.API_KEY,
      serviceId: 'serviceId',
      apis: [
        {
          endpoint: 'endpoint',
          },
        ],
      },
    },
  ],
  jsxRuntime: `automatic`,
  graphqlTypegen: true, // In the last v4.14 release we’ve added GraphQL Typegen as an experimental feature.
};

https://www.gatsbyjs.com/docs/reference/release-notes/v4.15/#graphql-typegen

0Yu0Yu

http://localhost:8000/___graphql
からクエリを叩いてみる

query MyQuery {
  allMicrocmsWorks(limit: 10) {
    edges {
      node {
        worksId
      }
    }
  }
  microcmsWorks {
    productUrl
    productImage {
      height
    }
  }
}
0Yu0Yu

Chakra UI

https://chakra-ui.com/guides/getting-started/gatsby-guide
に従ってプラグインを導入する

インストール

yarn add @chakra-ui/gatsby-plugin @chakra-ui/react @emotion/react @emotion/styled framer-motion
// gatsby-config.ts
const config: GatsbyConfig = {
  plugins: [
    {
      resolve: '@chakra-ui/gatsby-plugin',
      options: {
        /**
         * @property {boolean} [resetCSS=true]
         * if false, this plugin will not use `<CSSReset />
         */
        resetCSS: true,
        /**
         * @property {boolean} [isUsingColorMode=true]
         * if false, this plugin will not use <ColorModeProvider />
         */
        isUsingColorMode: true,
      },
    },
  ],
  ...
}
0Yu0Yu

下記のように使う
https://chakra-ui.com/docs/components/layout/box

// index.tsx
import Header from '@/components/organisms/Header';
import { ChakraProvider } from "@chakra-ui/react"
import { Box } from "@chakra-ui/react"

export default function Home({}) {
  return (
    <ChakraProvider>
      <Header />
      <Box
        background={"blue.100"} borderColor={"teal.300"} color={"green.800"}
        borderBottomWidth={4}
        p={2}
      >
        background={"blue.100"} borderColor={"teal.300"} color={"green.800"}
      </Box>
    </ChakraProvider>
  );
}
0Yu0Yu

FigmaのデザインデータをStorybookに埋め込む

Storybookのアドオンをインストール&登録

yarn add storybook-addon-designs

https://github.com/pocka/storybook-addon-designs

main.js
module.exports = {
  addons: ['storybook-addon-designs'],
}

storiesディレクトリのButton.tsxに適用する例
parametersにFigmaのリンクを指定する

import { withDesign } from 'storybook-addon-designs'

export default {
  title: 'My stories',
  component: Button,
  decorators: [withDesign],
}

export const myStory = () => <Button>Hello, World!</Button>

myStory.parameters = {
  design: {
    type: 'figma',
    url: 'https://www.figma.com/file/LKQ4FJ4bTnCSjedbRpk931/Sample-File',
  },
}

参考

https://code-log.hatenablog.com/entry/2020/08/31/161537

0Yu0Yu

themeの当て方

themes.tsxexportしてindex.tsxで下記のように指定する

import theme from './../../theme';

export default function Home() {
  return (
    <ChakraProvider theme={theme}>
    </ChakraProvider>
...
0Yu0Yu
yarn add -D esbuild-register
// gatsby-config.ts
import type { GatsbyConfig } from 'gatsby'
import { resolve } from 'path'

const plugins: GatsbyConfig['plugins'] = [
  'gatsby-plugin-image',
  {
    resolve: 'gatsby-source-filesystem',
    options: {
      name: 'posts',
      path: resolve(__dirname, 'posts')
    }
  },
  ...
]

const siteMetadata: GatsbyConfig['siteMetadata'] = {
  siteUrl: 'https://miyauchi.dev/',
}

const config: GatsbyConfig = {
  siteMetadata,
  plugins
}

export default config
// gatsby-config.js
// トランスパイル用
const { register } = require('esbuild-register/dist/node')

register({
  target: 'node16'
})

module.exports = require('./gatsby-config.ts')
yarn add esbild

下記よりesbuildが必要と判断しinstall

// esbuild-register/dist/node.js 
src/node.ts
var import_source_map_support = __toModule(require_source_map_support());
var import_pirates = __toModule(require_lib());
var _path2 = require('path');
var _esbuild = require('esbuild');
0Yu0Yu

Gatsby config

https://www.gatsbyjs.com/docs/how-to/custom-configuration/typescript/
https://miyauchi.dev/ja/posts/gatsby-typescript/

gatsby-config が最も最初に読み込まれるため、gatsby-config.js をエントリーポイントにしています。 gatsby-config.js で esbuild-register を登録することで、以降のファイルでは TypeScript がトランスパイルされます。ただ、残念ながら gatsby-config.js をなくす方法はわかりません。 これをなくすには gatsby コマンド時に esbuild-register を登録しなければなりません。

0Yu0Yu

任意のgoogleフォントは

yarna dd @fontsource/open-sans @fontsource/raleway
// theme.fonts
import { extendTheme } from '@chakra-ui/react'

const theme = extendTheme({
  fonts: {
    heading: `'Open Sans', sans-serif`,
    body: `'Raleway', sans-serif`,
  },
})

export default theme
// ChakraProviderのpropsに渡す
import '@fontsource/raleway/400.css'
import '@fontsource/open-sans/700.css'

import {
  ChakraProvider,
  Container,
  Stack,
  Heading,
  Text,
} from '@chakra-ui/react'
import theme from './theme'

const App = () => (
  <ChakraProvider theme={theme}>
    <Container>
      <Stack>
        <Heading>The spectacle before us was indeed sublime.</Heading>
        <Text>
          Apparently we had reached a great height in the atmosphere, for the
          sky was a dead black, and the stars had ceased to twinkle. By the same
          illusion which lifts the horizon of the sea to the level of the
          spectator on a hillside, the sable cloud beneath was dished out, and
          the car seemed to float in the middle of an immense dark sphere, whose
          upper half was strewn with silver. Looking down into the dark gulf
          below, I could see a ruddy light streaming through a rift in the
          clouds.
        </Text>
      </Stack>
    </Container>
  </ChakraProvider>

などとして使う
https://chakra-ui.com/docs/styled-system/recipes/using-fonts