我正在尝试在我的 React 项目中使用一些本地网络字体。我将它们包含在我的 main.scss 文件中,并通过 webpack 加载它们。包正确构建,包括 main.scss 样式。我看到 webpack 加载字体文件,并将它们复制到 public/fonts/,但我的包文件找不到字体。
据我了解,您的 @font-face src 应该与 bundle 的位置有关。我将其设置为与在 webpack 中加载字体相同的路径 ’./fonts/’ 。我看到的确切错误是:
file:///Users/myusername/Documents/folder1/folder2/folder3/APP/fonts/FoundersGroteskWeb-Regular.woff net::ERR_FILE_NOT_FOUND
我一直在尝试很多不同的路径配置,并在 webpack 中使用 publicPath 选项,但此时我正在绕圈子,因为这似乎是一个非常简单的参考错误。
文件结构:
APP
├──webpack.config.js
├──src
├──app
├──App.jsx
├──styles
├──main.scss
├──fonts
├──allthefonts.woff
├──public
├──bundle.js
├──fonts
├──allthefonts.woff
应用程序.jsx:
require('./styles/main.scss');
主要.scss:
@font-face {
font-family: FoundersGrotesk;
src: url('./fonts/FoundersGroteskWeb-Bold.eot') format('eot'),
url('./fonts/FoundersGroteskWeb-Bold.woff') format('woff'),
url('./fonts/FoundersGroteskWeb-Bold.woff2') format('woff2');
font-weight: bold;
}
@font-face {
font-family: FoundersGrotesk_Cnd;
src: url('./fonts/FoundersGrotXCondWeb-Bold.eot') format('eot'),
url('./fonts/FoundersGrotXCondWeb-Bold.woff') format('woff'),
url('./fonts/FoundersGrotXCondWeb-Bold.woff2') format('woff2');
font-weight: bold;
}
@font-face {
font-family: FoundersGrotesk;
src: url('./fonts/FoundersGroteskWeb-Regular.eot') format('eot'),
url('./fonts/FoundersGroteskWeb-Regular.woff') format('woff'),
url('./fonts/FoundersGroteskWeb-Regular.woff2') format('woff2');
font-weight: normal;
}
webpack.config.js:
'use strict';
const webpack = require('webpack');
const PROD = JSON.parse(process.env.PROD_ENV || '0');
module.exports = {
entry: './src/app/App.jsx',
output: {
path: './src/public/',
filename: PROD ? 'bundle.min.js' : 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: '/node_modules/',
query: {
presets: ['es2015', 'react', 'stage-1']
}
},
{
test: /\.s?css$/,
loaders: ['style', 'css', 'sass']
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader?name=./fonts/[name].[ext]'
}
]
}
};
原文由 johnjohn 发布,翻译遵循 CC BY-SA 4.0 许可协议
感谢@omerts in this thread 得到了一个可行的解决方案。涉及使用 publicPath 的解决方案。我一直试图将它用作 module.exports 中的一个选项,带有字体文件加载器,而不是输出。
更新 了 webpack.config.js :