You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Gatsby项目中配置Bootstrap与Google字体(Amatic SC)的问题

在Gatsby项目中配置Bootstrap和Google字体Amatic SC的完整指南

嘿,我来帮你搞定这个配置问题!Gatsby作为静态站点生成器,确实没有传统的HTML文件让你直接插CDN链接,但咱们有更贴合Gatsby生态的方法,分两部分给你讲清楚:

一、Bootstrap的配置(你已经走对一半啦)

你已经通过npm install bootstrap装好了Bootstrap,接下来只需要把它导入全局样式就行:

  1. 先在项目里创建(如果还没有)src/styles/global.css文件,在里面添加:
@import 'bootstrap/dist/css/bootstrap.min.css';
  1. 打开gatsby-browser.js(没有就新建一个),导入这个全局样式文件:
import './src/styles/global.css';

这样Bootstrap的样式就会全局生效,比直接用CDN更符合Gatsby的打包逻辑。

二、Google字体Amatic SC的配置(两种方法任你选)

方法1:完善你尝试的google-fonts-webpack-plugin配置(注意Gatsby版本兼容)

如果你想继续用这个webpack插件,得补全配置,还要注意Gatsby版本的API差异:

针对Gatsby v1版本:

gatsby-node.js里补全代码:

const GoogleFontsPlugin = require("google-fonts-webpack-plugin")

exports.modifyWebpackConfig = ({ config, stage }) => {
  // 给webpack添加Google字体插件
  config.plugin('google-fonts', GoogleFontsPlugin, [{
    fonts: [
      { family: 'Amatic SC', variants: ['400', '700'] } // 按需指定字体粗细变体
    ],
    // 可选:设置字体加载时的显示策略,优化用户体验
    display: 'swap'
  }])
  return config
}

针对Gatsby v2及以上版本(现在更常用):

因为v2之后modifyWebpackConfig被废弃了,要改用onCreateWebpackConfig API:

const GoogleFontsPlugin = require("google-fonts-webpack-plugin")

exports.onCreateWebpackConfig = ({ actions }) => {
  actions.setWebpackConfig({
    plugins: [
      new GoogleFontsPlugin({
        fonts: [
          { family: 'Amatic SC', variants: ['400', '700'] }
        ],
        display: 'swap'
      })
    ]
  })
}

别忘了先确保插件已安装:npm install google-fonts-webpack-plugin --save-dev

方法2:用Gatsby专用插件gatsby-plugin-google-fonts(更简单推荐)

这个是Gatsby社区专门做的插件,配置更省心,步骤如下:

  1. 安装插件:npm install gatsby-plugin-google-fonts --save-dev
  2. 打开gatsby-config.js,在plugins数组里加配置:
module.exports = {
  plugins: [
    // 其他已有的插件...
    {
      resolve: `gatsby-plugin-google-fonts`,
      options: {
        fonts: [
          `Amatic SC\:400,700` // 格式:字体名\:变体1,变体2
        ],
        display: 'swap' // 优化字体加载时的显示效果
      }
    }
  ]
}

最后验证配置是否生效

启动你的Gatsby项目(gatsby develop),然后:

  • 打开浏览器开发者工具,切换到「网络」标签,搜索fonts.gstatic.com,看看有没有Amatic SC字体的请求
  • 在组件CSS里测试字体:
.your-text-class {
  font-family: 'Amatic SC', cursive;
}

内容的提问来源于stack exchange,提问作者user2047485

火山引擎 最新活动