使用 Webpack 和 font-face 加载字体

Load fonts with Webpack and font-face

我正在尝试使用 @font-face 在我的 CSS 文件中加载字体,但字体从未加载。这是我的目录结构。

然后在 webpack.config.js 我有加载器来获取字体。

var path = require('path');
var webpack = require('webpack');

module.exports = {
  devtool: 'eval',
  entry: [
    "./index.js"
  ],
  output: {
    path: __dirname+"/build",
    filename: "main.js"
  },
  plugins: [
    new webpack.NoErrorsPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  module: {
      loaders: [
          { test: /\.js$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/ },
          { test: /\.jsx?$/, loaders: ['react-hot', 'babel-loader'], exclude: /node_modules/ },
          { test: /\.svg$/, loader: "raw" },
          { test: /\.css$/, loader: "style-loader!css-loader" },
          { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=src/css/[name].[ext]'}

      ]
  }
};

在我的 CSS 文件中我有这个:

@font-face {
  font-family: 'Darkenstone';
  src: url('./Darkenstone.woff') format('woff');
}

body {
  background-color: green;
  font-size: 24px;
  font-family: 'Darkenstone';
}

最后,我在我的 index.js 中调用我的 CSS 文件:

import './src/css/master.css';

一切正常,但从未加载字体。

尝试将加载程序更改为

{test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file?name=[name].[ext]'}

并将 publicPath: 'build/' 添加到您的 output 密钥。

在尝试了很多东西之后,下一个装载机成功了。我没有使用文件加载器,而是使用了 url-loader 。您需要安装 url-loader。

{ test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }

使用 webpack 4 这就是为我解决问题的方法(差异):

       {
         test: /\.svg$/,
         use: ['svg-loader']
       },
       {
         test: /\.(eot|woff|woff2|svg|ttf)([\?]?.*)$/,
         use: ['file-loader']
       }
       { test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: ['url-loader?limit=100000'] }

我不得不删除 svg-loaderfile-loader 以支持 url-loader

我的 app.scss 文件如下所示:

$fa-font-path: '~font-awesome/fonts';
@import '~font-awesome/scss/font-awesome';

$icon-font-path: "~bootstrap-sass/assets/fonts/bootstrap/";
@import '~bootstrap-sass/assets/stylesheets/bootstrap';

然后在我的 app.js 中导入 app.scss:

import './app.scss';

所以,在更改之后,我的 webpack 配置如下所示:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpackConfig = require('./webpack.config');

module.exports = {
  entry: {
    app: './client/app/app.js'
  },
  devtool: 'source-map',
  mode: 'development',
  plugins: [
    new HtmlWebpackPlugin({
      title: 'Development',
      template: 'client/index.html'
    })
  ],
  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  module: {
    rules: [
      {
        test: /\.(sa|sc|c)ss$/,
        use: [
          'style-loader',
          'css-loader',
          'sass-loader',
        ],
      },
      { test: /\.(png|woff|woff2|eot|ttf|svg)$/, use: ['url-loader?limit=100000'] }
    ]
  }
};

我遇到了同样的问题。 在我的例子中,字体的 'src' 变成了 src="[object Module]".

在 webpack 上禁用 esModule 是解决方案:

{
  test: /\.(png|jpe?g|gif|svg|ttf|woff|otf)$/,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[name].[contenthash].[ext]',
        outputPath: 'static/img',
        esModule: false // <- here
      }
    }
  ]
}

更多信息here

我将 webpack 版本从 4.20.2 升级到 4.42.0,我的代码开始加载我想要的字体。

const URL_LOADER_LIMIT = 8192

module.exports = () => ({
  module: {
    rules: [
      {
        test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'fonts/',
              limit: URL_LOADER_LIMIT
            }
          }
        ]
      },
      {
        test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'fonts/',
              limit: URL_LOADER_LIMIT,
              mimetype: 'application/font-woff'
            }
          }
        ]
      },
      {
        test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              name: '[name].[ext]',
              outputPath: 'fonts/',
              limit: URL_LOADER_LIMIT,
              mimetype: 'application/octet-stream'
            }
          }
        ]
      },
      {
        test: /\.mp3$/,
        use: ['file-loader']
      },
      {
        test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              outputPath: 'images/',
              name: '[name].[ext]',
              limit: URL_LOADER_LIMIT,
              mimetype: 'image/svg+xml'
            }
          }
        ]
      },
      {
        test: /\.(png|jpg|gif)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              outputPath: 'images/',
              name: '[name].[ext]',
              limit: URL_LOADER_LIMIT
            }
          }
        ]
      }
    ]
  }
})

根据 Webpack's Documentation,您需要更新 webpack.config.js 来处理字体文件。查看最后一个加载程序,即

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

我们将为 webpack 包含各种文件格式。最终的 webpack.config.js 文件看起来像这样。

const path = require('path');
module.exports = {
       entry: './src/index.js',
       output: {
         filename: 'bundle.js',
         path: path.resolve(__dirname, 'dist'),
       },
       module: {
         rules: [
           {
             test: /\.css$/i,
             use: ['style-loader', 'css-loader'],
           },
           {
             test: /\.(png|svg|jpg|jpeg|gif)$/i,
             type: 'asset/resource',
           },
          {
            test: /\.(woff|woff2|eot|ttf|otf)$/i,
            type: 'asset/resource',
          },
         ],
       },
     };

然后,您必须将字体导入您的条目文件。在这种情况下 ./src/index.js。配置好加载程序和适当的字体后,您可以通过 @font-face 声明合并它们。本地 url(...) 指令将被 webpack 拾取,就像图像一样。

当我从 Webpack 4.x.x 更新到最新的 5.52.1

时,我的字体出现了一些问题

我导出的内容 .woff / .woff2 / .ttf ... 看起来像这样:

export default __webpack_public_path__ + "glyphicons-halflings-regular.woff2";

我的解决方案是完全删除我以前的 file-loader。似乎文件被处理了多次,这导致了错误。

之前:

...
module: {
    rules: [
        {
            test: /\.(png|jpg|gif|ico|woff|woff2|ttf|svg|eot)$/,
            use: {
                loader: 'file-loader',
                options: { 
                    name: '[name].[ext]',
                    useRelativePath: true
                }
            }
        },
        {
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: 'css-loader',
                    options: { url: false }
                }
            ]
        }
    ]
}
...

之后:

...
module: {
    rules: [
        {
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: 'css-loader',
                    options: { url: false }
                }
            ]
        }
    ]
}
...

更多信息:https://webpack.js.org/guides/asset-modules/

我花了一些时间才弄清楚,所以我在这里发帖以防将来对任何人有所帮助。 如果您在节点 js / webpack 上使用常规 css 构建此解决方案对我有用:

module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: "babel-loader",
        options: {
          presets: ["@babel/preset-env"],
        },
      },
    },
    {
      test: /\.html$/,
      exclude: /node_modules/,
      use: "html-loader",
    },
    {
      test: /\.(png|svg|jpg|jpeg|gif)$/i,
      type: "asset/resource",
      generator: {
        filename: "assets/[name][ext][query]",
      },
    },
    {
      test: /\.(woff|woff2|eot|ttf|otf)$/i,
      type: "asset/resource",
      generator: {
        filename: "fonts/[name][ext][query]",
      },
    },
  ],
},

在您的 .js 文件中添加所需的导入语句:

// images references in the manifest
import "../../assets/icon-16.png";
import "../../assets/icon-32.png";
import "../../assets/icon-64.png";
import "../../assets/icon-80.png";
import "../../assets/icon-25.png";
import "../../assets/icon-48.png";
//fonts referenced in the css
import "../../Fonts/opensans-regular-webfont.eot";
import "../../Fonts/opensans-regular-webfont.svg";
import "../../Fonts/opensans-regular-webfont.ttf";
import "../../Fonts/opensans-regular-webfont.woff";
import "../../Fonts/opensans-regular-webfont.woff2";
import "../../Fonts/OpenSans-Regular.ttf";

然后您需要做的就是更新您的 .css 文件以指向创建的 dist/fonts 文件:

  @font-face {
  font-family: 'open_sansregular';
  src: url('fonts/opensans-regular-webfont.eot');
  src: url('fonts/Fonts/opensans-regular-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/opensans-regular-webfont.woff2') format('woff2'), url('fonts/opensans-regular-webfont.woff') format('woff'), url('fonts/opensans-regular-webfont.ttf') format('truetype'), url('fonts/opensans-regular-webfont.svg#open_sansregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

html,
body {
    font-family: open_sansregular !important
}

然后构建项目。