【问题标题】:How to use @font-face with webpack's css-loader?如何在 webpack 的 css-loader 中使用@font-face?
【发布时间】:2017-07-18 07:44:06
【问题描述】:

我正在尝试使用 webpack 在我的项目中导入一些字体(如 Roboto),但它们都不起作用。

我的文件结构如下:

+-src---fonts-+-Roboto---Roboto.ttf
|             |
|             +-fonts.css
|
+-webpack.config.js

我的fonts.css 文件:

@font-face {
    font-family: 'Roboto';
    src: url(/Roboto/Roboto.ttf) format('truetype');
}

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

//...
loaders: [
  {
    test: /\.css/,
    loaders: [
      'style-loader',
      `css-loader?${JSON.stringify({
        sourceMap: isDebug,
        localIdentName: isDebug ? '[name]_[local]_[hash:base64:3]' : '[hash:base64:4]',
        modules: true,
        minimize: !isDebug,
        importLoaders: 1
      })}`,
      'postcss-loader',
    ],
  },
  {
    test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
    loader: 'url-loader',
  },
  {
    test: /\.(wav|mp3|eot|ttf)$/,
    loader: 'file-loader',
  },
],
//...

当我运行 webpack 时,没有出现错误。但是 Roboto 字体没有加载(文本仍然是默认字体系列,虽然我已经将 font-family: 'Roboto' 设置为文本元素)。

我尝试过的:

  1. 将.css文件的url()s中的路径更改为相对路径: 出现错误:

    ./~/css-loader 中的错误?{"sourceMap":true,"localIdentName":[name][local][hash:base64:3]","modules": true,"minimize":false,"importLoaders": 1}!./~/postcss-loader!./fonts/fonts.css Module not found: Error: Cannot resolve module 'Roboto/Roboto.ttf' in /Users/ EnixCoda/projectName/fonts @ ./~/css-loader?{"sourceMap":true,"localIdentName":"[name][local][hash:base64:3]","modules ":true,"minimize":false,"importLoaders":1}!./~/postcss-loader!./fonts/fonts.css 6:135-163

谁能帮帮我?

【问题讨论】:

    标签: css fonts webpack css-loader


    【解决方案1】:

    当我完成此操作之前,您需要将 @font-face url 指向 dist 文件夹或 webpack 输出文件的任何位置,相对于请求它们的 dist 文件夹中的文件。例如:

    dist/
      assets/
        fonts/
          font-file.ttf
      css/
        style.css
      index.html
    

    这意味着@font-face 路径将是../assets/fonts/font-file.ttf,完全与 src 目录无关。

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 2018-12-27
      • 1970-01-01
      • 2013-02-05
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 2018-01-11
      相关资源
      最近更新 更多