Webpack无法加载字体(ttf)

gre*_*enN 6 fonts font-face reactjs webpack webpack-3

目前,我有3种字体要添加到我的React项目中:a,浅色,粗体。
我的文件结构:

/src
??? /fonts/
?   ??? /A.ttf
?   ??? /A-light.ttf
?   ??? /A-bold.ttf
?  
??? /styles/
?   ??? /base/
?   ?   ??? /__base.scss
?   ??? styles.scss
? 
??? app.jsx
??? webpack.config.js
Run Code Online (Sandbox Code Playgroud)

_base.scss:

@font-face {
  font-family: "A";
  font-style: normal;
  font-weight: 400;
  src: url("../../fonts/A.ttf") format("truetype");
}

@font-face {
  font-family: "A";
  font-style: normal;
  font-weight: 800;
  src: url("../../fonts/A-bold.ttf") format("truetype");
}
@font-face {
  font-family: "A";
  font-style: normal;
  font-weight: 300;
  src: url("../../fonts/A-light.ttf") format("truetype");
}
body {
  font-family: A, Helvetica, Arial, sans-serif;
}
Run Code Online (Sandbox Code Playgroud)

_base.scss由styles.scss导入,styles.scss由app.jsx导入。

我的webpack配置看起来像这样:
webpack.config.js

const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const StyleLintPlugin = require('stylelint-webpack-plugin');

process.env.NODE_ENV = process.env.NODE_ENV || 'development';
console.log(process.env.NODE_ENV);
if (process.env.NODE_ENV === 'development') {
  require('dotenv').config({path: '.env.development'});
}

module.exports = env => {
  const isProduction = env === 'production';
  const CSSExtract = new ExtractTextPlugin('styles.css');

  return {
    entry: ['babel-polyfill', './src/app.jsx'],
    output: {
      path: path.join(__dirname, 'public', 'dist'),
      filename: 'bundle.js'
    },
    resolve: {
      extensions: ['.js', '.jsx', '.json', '.css', '.scss']
    },
    module: {
      rules: [
        {
          exclude: /(node_modules|bower_components)/,
          test: /\.jsx?$/,
          use: ['babel-loader', 'eslint-loader']
        },
        {
          test: /\.s?css$/,
          use: CSSExtract.extract({
            use: [
              {
                loader: 'css-loader',
                options: {
                  sourceMap: true
                }
              },
              {
                loader: 'sass-loader',
                options: {
                  sourceMap: true
                }
              }
            ]
          })
        },
        {
          test: /\.(png|jpg|svg)$/,
          use: {
            loader: 'url-loader'
          }
        },
        {
          test: /\.(ttf|eot|woff|woff2)$/,
          loader: 'file-loader',
          options: {
            name: 'fonts/[name].[ext]'
          }
        }
      ]
    },
    plugins: [
      CSSExtract,
      new webpack.DefinePlugin({
        'process.env.API_AUTH_TOKEN': JSON.stringify(process.env.API_AUTH_TOKEN),
        'process.env.API_EMAIL': JSON.stringify(process.env.API_EMAIL),
        'process.env.API_PASSWORD': JSON.stringify(process.env.API_PASSWORD)
      }),
      new StyleLintPlugin({})
    ],
    devtool: isProduction ? 'source-map' : 'inline-source-map',
    devServer: {
      overlay: {
        warnings: true,
        errors: true
      },
      contentBase: path.join(__dirname, 'public'),
      historyApiFallback: true,
      publicPath: '/dist/'
    }
  };
};
Run Code Online (Sandbox Code Playgroud)

但是,Webpack无法编译。

错误:

./src/styles/styles.scss
Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve '../../fonts/A.ttf'
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

小智 9

关于 Webpack 5:如果这对其他人有帮助,这里是使用 Webpack 5 加载 truetype 字体时遇到的常见问题的解决方案。这实际上是一个 CSS 问题。

在文档的 Webpack 5 资源管理部分的“加载字体”标题下,style.css 文件具有以下示例 @font-face 声明:

@font-face {
   font-family: 'MyFont';
    src: url('./my-font.woff2') format('woff2'),
    url('./my-font.woff') format('woff');
}
Run Code Online (Sandbox Code Playgroud)

为了使此声明能够与其他字体类型(例如 truetype 或 opentype 字体)一起使用,需要format正确指定。以下任何format类型均有效:

“woff”、“woff2”、“truetype”、“opentype”、“嵌入式 opentype”、“svg”。

例如,如果将format类型设置为“ttf”或“otf”,则不会导入该字体。该format类型是为了告诉浏览器字体的格式,但不是强制性的,因此,如果您省略它,您的字体仍应正确加载。

假设您已正确设置字体的路径,则此示例应按预期工作:

@font-face {
   font-family: 'MyFont';
   src: url('./my-font.ttf') format('truetype');
}
Run Code Online (Sandbox Code Playgroud)

这也应该有效:

@font-face {
   font-family: 'MyFont';
   src: url('./my-font.ttf');
}
Run Code Online (Sandbox Code Playgroud)


sun*_*tzu 5

使用npm的“ ttf-loader”对我来说非常合适。

https://www.npmjs.com/package/ttf-loader

module: {
  rules: [
    {
      test: /\.ttf$/,
      use: [
        {
          loader: 'ttf-loader',
          options: {
            name: './font/[hash].[ext]',
          },
        },
      ]
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)


Lak*_*ula 5

从 webpack 5 开始,您可以改用内置的资产模块。从此处的官方 Webpack 指南中,将其添加module.rules到加载 .ttf 文件中:

{
  test: /\.(woff|woff2|eot|ttf|otf)$/i,
  type: 'asset/resource',
},

Run Code Online (Sandbox Code Playgroud)

  • 这对我有用 (2认同)

Tri*_*hra 2

Webpack 需要一个字体加载器来加载项目中存在的字体文件。您正在使用文件加载器来加载字体。改变

{
      test: /\.(ttf|eot|woff|woff2)$/,
      loader: 'file-loader',
      options: {
      name: 'fonts/[name].[ext]'
 }
Run Code Online (Sandbox Code Playgroud)

 {
      test: /\.ttf$/,
      use: [
        {
          loader: 'ttf-loader',
          options: {
            name: './font/[hash].[ext]',
          },
        },
      ]
  }
Run Code Online (Sandbox Code Playgroud)

通过在项目中安装字体加载器,例如 NPMTTF Loader