如何在我的项目中插入本地字体?

时间:2019-07-28 22:49:51

标签: reactjs fonts font-face styled-components

我使用IconMoon创建自定义图标字体。

在它生成的.html中,它可以完美运行。但是,当我尝试在我的React和Styled-Components项目中使用它时,图标并未显示,而是显示为HTML格式。

我的字体在路径中:src / assets / fonts / icons

浏览器正在下载字体,并且不会显示任何错误: enter image description here

很快,我正在尝试为我的字体创建一个类似于FontAwesome的组件,并且会发生这种情况:

enter image description here

我的组件:

import React from "react";

import styled from "styled-components";

const Tst = styled.i`
  font-family: "spotify" !important;
  font-style: normal;
  font-weight: normal;
  font-variant: normal;
  text-transform: none;
  line-height: 1;

  ::before {
    content: "\e900";
    color: red;
  }
`;

const SaveFavorite = () => {
  return <Tst />;
};

export default SaveFavorite;

我的全球风格:

import { createGlobalStyle } from "styled-components";

const GlobalStyle = createGlobalStyle`
    @font-face {
        font-family: "spotify";
        font-weight: normal;
        font-style: normal;
        src: url("../assets/fonts/spotify.eot?") format("embedded-opentype"),
            url("../assets/fonts/spotify.ttf?") format("truetype"),
            url("../assets/fonts/spotify.woff?") format("woff"),
            url("../assets/fonts/spotify.svg?") format("svg");
    }

    * {
        box-sizing: border-box;
        padding: 0;
        margin: 0;
        outline: 0;
    }

    body {
        font-family: 'CircularSpUIv3T', sans-serif;
        color: white;
        text-rendering: optimizeLegibility !important;
        -webkit-font-smoothing: antialiased !important;
        -moz-osx-font-smoothing: grayscale !important;
        user-select: none;
    }

    img {
        width: 100%;
        max-width: 100%;
        height: auto;
    }
`;

export default GlobalStyle;

1 个答案:

答案 0 :(得分:0)

如果您查看由样式化组件生成的css,您会发现字体路径根本无法解析,它们正是您键入它们的方式。没有Babel的帮助,浏览器将无法在src目录中找到相对路径,而现在您拥有这些路径的方式将按原样传递。

您有两种选择,尽管我不确定这两种方法是否都可以。

选项1:将字体移动到public目录

与任何旧的HTML页面一样,浏览器可以找到公共目录中的文件。在您的全局样式中,您将必须使用相对于public/index.html的路径。

您的文件结构将类似于:

project
|-- public
  |-- index.html
  |-- fonts
    |-- spotify.eot
    |-- spotify.ttf
    |-- spotify.woff
    |-- spotify.svg
|-- src
  |-- global.style.js
  |-- (...)

还有您的global.style.js

const GlobalStyle = createGlobalStyle`
    @font-face {
        font-family: "spotify";
        src: url("fonts/spotify.eot?") format("embedded-opentype"),
            url("fonts/spotify.ttf?") format("truetype"),
            url("fonts/spotify.woff?") format("woff"),
            url("fonts/spotify.svg?") format("svg");
    }

选项2:将字体保留在src中,但让Babel为您解决路径

要使Babel解析路径,我们需要将文件导入global.style.js中,然后使用解析的路径而不是静态路径:

import SpotifyEOT from '../assets/fonts/spotify.eot';
// etc

const GlobalStyle = createGlobalStyle`
    @font-face {
        font-family: "spotify";
        src: url(${SpotifyEOT}?) format("embedded-opentype"),
            // [etc]
    }

我不知道问号的实际用途,但我想您可以像我一样将其放置在解析的路径之后。