2
2

More than 3 years have passed since last update.

GatsbyでScssファイルを作成して読み込む方法

Posted at

GatsbyでSCSSを書いたり、Bootstrap4のような外部ファイルを読み込む方法。

GatsbyでSCSSを読み込むには

Gatsbyの設定

まずは必要なモジュールをインストール。

npm install --save node-sass gatsby-plugin-sass

次にgatsby-config.jsplugin設定を追加。この設定を行うとコンパイルできるようになる。

プラグイン設定で圧縮形式などオプション設定も可能。
https://www.gatsbyjs.org/packages/gatsby-plugin-sass/

module.exports = {
  ...
  plugins: [
    {
      resolve: `gatsby-plugin-sass`,
      options: {
        outputStyle: 'compressed', // nested, expanded, compact, compressed,
      },
    },
  ],
}

SCSSを書く

ファイルの設置場所はsrc以下に置く、例えばこんな感じ。

src
  - styles
    - theme.scss
    - global
      - header.scss
      - footer.scss
    - components
      - card.scss

コンポーネント用スタイルなどはメインのファイルからインポートする。

// src/styles/theme.scss
@import 'global/header';
@import 'global/footer';
@import 'components/card';

GatsbyでSCSSファイルを読み込み

ファイルを読み込む方法はいくつかある。

まず1つはgatsby-browser.jsからグローバルスタイルとして読み込む方法。

// gatsby-browser.js
import "./src/styles/theme.scss"

2つ目はレイアウトコンポーネントで読み込む方法。

// src/components/layout.js
import React from "react"

import "../styles/theme.scss"

const Layout = ({ location, title, children }) => {

  return (
    <div className="wrapper">
      <main id="contents">{children}</main>
    </div>
  )
}

export default Layout

scss以外にもBootstrap4のような外部ファイルを同様にして読み込むことができる。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2