导入字体以使用Webpack和样式化的组件来响应项目

时间:2019-03-06 20:29:55

标签: reactjs webpack-2 styled-components

我正在尝试从我的使用Webpack和样式化组件的react项目中的本地资源导入字体。我有一个带有以下代码的字体文件夹:

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}
`;

在我的应用程序组件中,我从类似样式的组件中使用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',
          },
        },
      ],
    },

我尝试遵循this线程的建议,但是它似乎对我不起作用,因为在控制台中出现错误,提示GET http://localhost:5001/resources/fonts/OurFont-Bold.woff2 net :: ERR_ABORTED 404(未找到)。

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

2 个答案:

答案 0 :(得分:1)

您可以通过将字体导入JS并将其传递给样式化的组件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,而应使用指向当前文件目录的相对路径。

答案 1 :(得分:0)

面对相同的问题,并尝试了上述解决方案,但是它不起作用,并且出现错误消息: Cannot find module '../fonts/Roboto-BlackItalic.ttf'

我正在使用打字稿,所以是否需要添加某种导出功能才能将import语句用于这种路径?

编辑: 通过在我的types.d.ts文件中添加declare module "*.ttf";并在@ font-face

中删除src: url(${fontUrl}) format("ttf");中的format(“ ttf”)来解决