Измените тему Antd при использовании GatsbyJS

Эта страница плагина GatsbyJS / antd (https://github.com/bskimball/gatsby-plugin-antd/issues/2) кажется, что есть способ редактировать темы ant.design (antd) при использовании GatsbyJS. Предоставляемый код

plugins: [
  {
      resolve: 'gatsby-plugin-antd',
      options: {
        style: true
      }
  }
]

Но дополнительной информации нет. Где можно изменить такие вещи, как основной цвет темы (как описано: https://ant.design/docs/react/customize-theme). Страница ant.design (https://ant.design/docs/react/customize-theme) говорит, что нужно изменить основной цвет, выполнив следующие действия:

"theme": {
  "primary-color": "#1DA57A",
},

Непонятно, в каком файле такая переменная будет установлена ​​в GatbsyJS.


person cannin    schedule 13.08.2018    source источник


Ответы (4)


Репозиторий GitHub с примером: https://github.com/uciska/gatsby-less-v2. Чтобы Antd заработал, необходимо внести изменения в три файла Gatsby.

Пример gastby-config.js:

module.exports = {
  siteMetadata: {
    title: 'My site'
  },
  plugins: [
    {
      resolve: `gatsby-plugin-less`,
      options: {
        javascriptEnabled: true,
        modifyVars: {
          'primary-color': '#da3043',
          'font-family': 'Arial',
          'layout-body-background': '#66ff79'
        }
      }
    }
  ]
}

Пример gastby-node.js:

exports.onCreateBabelConfig = ({ actions }) => {
  actions.setBabelPlugin({
    name: 'babel-plugin-import',
    options: {
      libraryName: 'antd',
      style: true
    }
  })
}

Пример package.json:

{
  "name": "gatsby-starter-hello-world",
  "description": "Gatsby hello world starter",
  "license": "MIT",
  "scripts": {
    "develop": "gatsby develop",
    "build": "gatsby build",
    "serve": "gatsby serve"
  },
  "dependencies": {
    "antd": "^3.6.4",
    "babel-plugin-import": "^1.8.0",
    "gatsby": "next",
    "gatsby-plugin-less": "next",
    "less": "^3.0.4",
    "less-loader": "^4.1.0",
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-apollo": "^2.1.11"
  }
}
person cannin    schedule 18.08.2018
comment
Вам не нужно редактировать gatsby-node, если вы используете gatsby-plugin-antd - person Brian Kimball; 18.09.2018
comment
@cannin Зачем нужно включать less-loader? Разве gatsby-plugin-less это не добавляет за нас? - person Moshe; 05.11.2019
comment
@BrianKimball Я использовал gatsby-plugin-antd, но все же нужно отредактировать gatsby-node.js, чтобы он вступил в силу. - person Alex Xiong; 22.02.2020

Эта конфигурация сработала для меня. Я не добавил babel-plugin-import и не изменил gatsby-node.js файл.

Вот мой package.json файл

{
  "name": "web-master",
  "private": true,
  "description": "Become a fullstack developer",
  "version": "1.0",
  "author": "Vishal Shetty",
  "dependencies": {
    "gatsby": "^2.19.7",
    "gatsby-image": "^2.2.39",
    "gatsby-plugin-manifest": "^2.2.39",
    "gatsby-plugin-offline": "^3.0.32",
    "gatsby-plugin-react-helmet": "^3.1.21",
    "gatsby-plugin-sharp": "^2.4.3",
    "gatsby-source-filesystem": "^2.1.46",
    "gatsby-transformer-sharp": "^2.3.13",
    "prop-types": "^15.7.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-helmet": "^5.2.1"
  },
  "devDependencies": {
    "antd": "^3.26.12",
    "gatsby-plugin-antd": "^2.1.0",
    "gatsby-plugin-less": "^3.0.19",
    "less": "^3.11.1",
    "less-loader": "^5.0.0",
    "prettier": "^1.19.1"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write \"**/*.{js,jsx,json,md}\"",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "clean": "gatsby clean"
  }
}

Мой gatsby-config.js файл

module.exports = {
  siteMetadata: {
    title: `WebMaster`,
    description: `Become a fullstack developer`,
    author: `@gatsbyjs`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
      },
    },
    {
      resolve: "gatsby-plugin-antd",
      options: {
        style: true,
      },
    },
    {
      resolve: "gatsby-plugin-less",
      options: {
        javascriptEnabled: true,
        modifyVars: {
          "primary-color": "#E4572E",
        },
      },
    },
  ],
}

Обратите внимание на конфигурацию плагинов gatsby-plugin-antd и gatsby-plugin-less.

Вот и все, работает.

person Vishal Shetty    schedule 25.02.2020
comment
Я пробовал это, в моем случае это не работает. У вас есть пример этого решения с помощью кодов и ящиков? - person blueseal; 02.02.2021

Я попробовал все вышеперечисленные ответы, которые были написаны несколько лет назад, но это не сработало. После нескольких часов исследований, наконец, я смог изменить antd переменные по умолчанию с помощью gatsby. Вот решение:

gatsby-config.js

[
...
...
   {
      resolve: "gatsby-plugin-antd",
      options: {
        style: true,
      },
    },

    {
      resolve: "gatsby-plugin-less",
      options: {
        lessOptions: {
          modifyVars: { //direct child node of lessOptions
            "primary-color": "#C53333", //your preferred color
          },
          javascriptEnabled: true, //direct child node of lessOptions
        },
      },
    },

]

less и less-loader НЕ требуются для изменения antd переменных по умолчанию.

package.json

"dependencies": {
  "antd": "^4.12.2",
  "gatsby-plugin-antd": "^2.2.0",
  "gatsby-plugin-less": "^4.7.0",
}

примечание: найдите все переменные по умолчанию для ant-design здесь

person blueseal    schedule 04.02.2021
comment
Единственное, что у меня сработало в 2021 году. - person Boomer Rogers; 16.06.2021

Престижность @cannin за его оригинальный ответ. Я обновил его, указав последнее имя библиотеки, и изменил структуру текста.

Чтобы использовать ANTD с Gatsby и перезаписать исходный стиль

  1. Добавить зависимости
    yarn add babel-plugin-import less-loader antd gatsby-plugin-less
  2. Обновите настройку Gatsby:
    gastby-config.js
    добавить в массив plugins

    {
      resolve: `gatsby-plugin-less`,
      options: {
        javascriptEnabled: true,
        modifyVars: {
          'primary-color': '#663399',
          'font-family': 'Arial',
          'layout-body-background': '#66ff79'
        }
      },
    },
    

    gastby-node.js

    exports.onCreateBabelConfig = ({ actions }) => {
      actions.setBabelPlugin({
        name: 'babel-plugin-import',
        options: {
          libraryName: 'antd',
          style: true
        }
      })
    }
    
  3. Пример использования antd в компоненте. Эта primary кнопка будет отображаться фиолетовым цветом Гэтсби #663399

    import React from "react"
    import Layout from '../components/layout'
    import {Button} from 'antd'
    
    export default () => (
      <Layout>
        <div>
          <h1>ANTD</h1>
          <p>Such wow. Very React.</p>
          <Button type="primary">Button</Button>
        </div>
      </Layout>
    )
    
person KuN    schedule 05.12.2018
comment
Зачем устанавливать less-loader? Не должно быть меньше и без плагина gatsby. - person Moshe; 05.11.2019
comment
javascriptEnabled должно быть в lessOptions. - person Dcalsky; 02.12.2020