为什么我的本地字体未应用情感全局样式?



我正在尝试在利用 Emotional 及其全局组件的 React 项目中使用本地托管的字体。此方法适用于网络字体,例如Google字体,但是当我下载相同的字体并尝试使用@font-face将其作为本地.ttf文件应用时,我无法获得相同的结果。

这是重要的文件,App.js

import React from "react";
import { Global, css } from "@emotion/core";
import styled from "@emotion/styled";
const GlobalStyles = css`
@import url("https://fonts.googleapis.com/css?family=Dancing+Script&display=swap");
@font-face {
font-family: "Local Font";
src: url("fonts/DancingScript-Regular.ttf");
}
* {
text-align: center;
}
`;
const FromGoogle = styled.h1`
font-family: "Dancing Script";
`;
const FromLocal = styled.h1`
font-family: "Local Font";
`;
function App() {
return (
<div className="App">
<Global styles={GlobalStyles} />
<FromGoogle>This text's font family is from Google.</FromGoogle>
<FromLocal>
This text's font family should be the same, except it comes from a local
font file, and it's not working.
</FromLocal>
</div>
);
}
export default App;

出于某种原因,FromGoogle中的文本使用 Google 字体很好,而FromLocal中的文本则不使用。我的第一个想法是这是路径的问题,但如果是,我就说不出来了。

这是GitHub上的完整项目。我使用了Create React App,并删除了所有不相关的样板文件。

在我的Next.js应用程序中,我在以下版本中使用了情感:

"@emotion/react": "^11.1.1",
"@emotion/styled": "^11.0.0",

我的全局样式是:

export const GlobalStyles = () => (
<Global
styles={css`
@font-face {
font-family: 'Faustina';
font-style: normal;
font-weight: 700;
src: local(''), 
url('/fonts/Faustina/Faustina.woff') format('woff'),
url('/fonts/Faustina/Faustina.ttf') format('truetype');
}
* {
box-sizing: border-box;
font-family: Faustina;
}
html,
body {
width: 100%;
height: 100%;
min-height: 100%;
padding: 0;
margin: 0;
}
`}
/>
);

我的字体在

project_root/public/fonts/Faustina
// explicitly
project_root/public/fonts/Faustina/Faustina-Bold.ttf
project_root/public/fonts/Faustina/Faustina-Bold.woff

为了查看字体更改,我需要重新启动开发服务器,例如yarn dev.在重新启动之前,我遇到了同样的问题,即字体未显示(甚至在开发工具"网络"选项卡中下载(。

在我的盖茨比项目中使用这些版本;

"@emotion/react": "^11.8.1",
"gatsby": "^4.8.0"

index.html 文件不可用,因此您无法添加 HTML 标记<style>并在其中嵌入@font面。

将下载的字体托管在 src/myfonts 目录中,然后使用静态导入语句导入任何字体。

import font1 from './myfonts/font1.ttf';

然后使用 font1 调用url(font1)CSS 函数


const globalStyle =  css`
@font-face {
font-family: 'font1';
src: url(${font1}) format('truetype');
};
`;  

它在我的情况下有效;

就我而言,解决方案就像这个答案一样。

我需要在导入到index.html中的 css 文件中定义字体,如下所示:

<link rel="stylesheet" type="text/css" href="/styles/fonts.css" />

然后,我能够在我的情感主题中引用字体系列名称并正确加载它们。

最新更新