[英]What's the correct way to load .otf font files in webpack?
使用webpack時加載.otf字體文件的適當方法是什么? 我已經多次嘗試在我的webpack.config.js
包含一條規則,沒有任何成功,基於我在以下幾行中看到的許多示例:
{ test: /\.(eot|svg|ttf|otf|woff)$/, use: 'file-loader' }
//or
{ test: /\.(eot|svg|ttf|otf|woff)$/, use: 'url-loader' }
//or
{ test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, use: 'file-loader' }
//...etc
我已經在我的webpack.config.js
設置了以下其他文件類型,這些文件類型正在成功運行:
module.exports = {
//...
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]},
{ test: /\.(jpe?g|png|gif|svg|xml)$/i, use: 'file-loader'}
]
},
//...
}
盡管我嘗試為.otf文件添加另一個規則/案例,但我總是遇到以下錯誤:
模塊解析失敗:... / fonts / [name-of-my-font] .otf意外字符''(1:4)您可能需要一個合適的加載程序來處理此文件類型。
我已經將.otf文件添加到我的根目錄中的fonts
文件夾中,並且在我的index.css中我有:
@font-face {
font-family: 'name-of-my-font';
src: url('fonts/name-of-my-font.otf'),
format('opentype');
}
有沒有人遇到類似的問題,並為此找到了解決方案?
謝謝,奧斯汀
對於我的webpack.config.js
文件的更多評論請求,這是我的整個webpack.config.js
:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]},
{ test: /\.(jpe?g|png|gif|svg|xml)$/i, use: 'file-loader' }
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
我補充道
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
loader: "file-loader"
}
到我的webpack.config.js。 我想我需要明確地將類型鏈接到文件加載器。 我使用的是默認的VS2017 Angular項目。
在我的webpack.config.js中我有:
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: "file-loader"
}
然后在我的index.js文件中,我有:
import React from 'react';
import ReactDOM from 'react-dom';
import { injectGlobal } from 'styled-components';
import avenir from '../font/AvenirLTStd-Light.otf';
injectGlobal`
@font-face {
font-family: 'Avenir';
src: url(${avenir}) format('opentype');
font-weight: normal;
font-style: normal;
}
* {
font-family: 'Avenir', sans-serif;
}
`;
import App from './components/App';
ReactDOM.render(
<App />
, document.querySelector('#root')
);
使用styled-components庫中的injectGlobal helper會自動將樣式注入到css文件中。 你可以將樣式組件的東西移動到一個單獨的.js文件然后導入它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.