6

我正在尝试使用 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()相对路径:出现错误:

    ./~/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

有人可以帮我吗?

4

1 回答 1

2

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

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

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

于 2018-07-20T18:58:08.463 回答