使用Webpack和Styled Components将字体导入React项目

5
我试图从本地资源中导入字体到我的React项目中,该项目使用Webpack和Styled Components。我有一个包含以下代码的字体文件夹:
import { css } from 'styled-components';
import { fontWeight } from './vars';

export const fontFaces = css`
  @font-face {
    font-family: 'OurFont';
    src: url('/resources/fonts/OurFont-Bold.woff2') format('woff2');
    font-weight: ${fontWeight.bold};
    font-style: normal;
  }
`;

然后我有一个全局样式文件:

import { createGlobalStyle } from 'styled-components';
import { fontFaces } from './fonts';

export const GlobalStyles = createGlobalStyle`
  ${fontFaces}
`;

在我的应用程序组件中,我使用styled-components的ThemeProvider,如下所示(为简洁起见,这里省略了一些非相关代码):
import { ThemeProvider } from 'styled-components';

class App extends React.Component {
render() {
  return (
    <ThemeProvider theme={{ theme }}>
      <GlobalStyles />
      <AppHeader />
      <AppNavigator />       
    </ThemeProvider>
  );
}}

以下是webpack相关的代码:

module: {
  rules: [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      use: ['babel-loader'],
    },
    {
      test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
      use: [
        {
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            limit: 10000,
            mimetype: 'application/font-woff',
          },
        },
      ],
    },

我试着按照这个帖子的建议来操作,但是似乎不起作用,因为在控制台中出现了一个错误,显示GET http://localhost:5001/resources/fonts/OurFont-Bold.woff2 net::ERR_ABORTED 404(未找到)。

有人知道我做错了什么或者是否还有其他方法吗?谢谢!

3个回答

7

你可以通过在 JS 中导入字体,并将其传递到你的 styled components css 模板标签中来解决这个问题:

import { css } from 'styled-components';
import { fontWeight } from './vars';

import myFontURL from '../../mypath/fonts/OurFont-Bold.woff2';

export const fontFaces = css`
  @font-face {
    font-family: 'OurFont';
    src: url(${myFontURL}) format('woff2');
    font-weight: ${fontWeight.bold};
    font-style: normal;
  }
`;

请务必不要使用/resources/fonts/OurFont-Bold.woff2,而是使用相对路径到您当前文件所在的目录。

看起来可以工作 :) 快速跟进问题: 你知道这是否适用于生产构建吗? - cbutler
是的,它肯定应该这样做 - 除非您使用某种CDN,那么您需要专门为此配置webpack。 - Buzinas

3
面对同样的问题并尝试了上述解决方案,但它并不起作用,我收到了以下错误信息: Cannot find module '../fonts/Roboto-BlackItalic.ttf' 我正在使用TypeScript,所以我需要添加某种导出来使用这种路径的import语句吗?
编辑: 通过在我的typings.d.ts文件中添加declare module "*.ttf";并在@font-face中删除src: url(${fontUrl}) format("ttf");中的format("ttf")来解决。

基本上TS不会涉及CSS。我通过在TS构建命令中添加目录副本来解决问题。 - Ben G
在我的情况下,诀窍是移除格式("ttf")。 - undefined

0

您可以通过创建一个文件falename.css(在我的情况下是font.css),并使用以下@font-face来解决问题:

@font-face {
    font-family: 'inter-black';
    src: url('../assets/font/Inter-Black.ttf');
    font-display: swap;
}
@font-face {
    font-family: 'inter-light';
    src: url('../assets/font/Inter-Light.ttf');
    font-display: swap;
}

然后您将把它导入到您的项目index.js导入打印font.css的代码

完成后,您可以在styled-component中使用该代码

export const MainTitle = styled.h1`
    font-family: 'inter-black';
`;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接