目前,我想添加到我的 React 项目中的 3 种字体:a、a light、bold。
我的文件结构:
/src
├── /fonts/
│ ├── /A.ttf
│ ├── /A-light.ttf
│ └── /A-bold.ttf
│
├── /styles/
│ ├── /base/
│ │ └── /__base.scss
│ └── styles.scss
│
├── app.jsx
└── webpack.config.js
_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;
}
_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/'
}
};
};
但是 Webpack 无法编译。
错误:
./src/styles/styles.scss Module build failed: ModuleNotFoundError: Module not found: Error: Can't resolve '../../fonts/A.ttf'
任何帮助将不胜感激!
最佳答案
使用 npm 中的“ttf-loader”对我来说效果非常好。
https://www.npmjs.com/package/ttf-loader
module: {
rules: [
{
test: /\.ttf$/,
use: [
{
loader: 'ttf-loader',
options: {
name: './font/[hash].[ext]',
},
},
]
}
]
}
关于reactjs - Webpack 无法加载字体(ttf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49877149/