gpt4 book ai didi

reactjs - 导入字体以使用 webpack 和样式组件 react 项目

转载 作者:行者123 更新时间:2023-12-03 14:06:42 25 4
gpt4 key购买 nike

我正在尝试从使用 webpack 和样式组件的 React 项目中的本地资源导入字体。我有一个包含以下代码的字体文件夹:

import { css } from 'styled-components';
import { fontWeight } from './vars';

export const fontFaces = css`
@font-face {
font-family: 'OurFont';
src: url('/resources/fonts/OurFont-Bold.woff2') format('woff2');
font-weight: ${fontWeight.bold};
font-style: normal;
}
`;

然后我有一个全局样式文件:

import { createGlobalStyle } from 'styled-components';
import { fontFaces } from './fonts';

export const GlobalStyles = createGlobalStyle`
${fontFaces}
`;

在我的应用程序组件中,我使用来自样式组件的 ThemeProvider,如下所示(为了简洁起见,此处省略了一些不相关的代码):

import { ThemeProvider } from 'styled-components';

class App extends React.Component {
render() {
return (
<ThemeProvider theme={{ theme }}>
<GlobalStyles />
<AppHeader />
<AppNavigator />
</ThemeProvider>
);
}}

以及 webpack 中的相关代码:

module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.(eot|svg|ttf|woff|woff2|otf)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
limit: 10000,
mimetype: 'application/font-woff',
},
},
],
},

我尝试遵循 this 的建议线程,但它似乎对我不起作用,因为我在控制台中收到错误,显示 GET http://localhost:5001/resources/fonts/OurFont-Bold.woff2 net::ERR_ABORTED 404(未找到)。

有谁知道我做错了什么或者是否有其他方法?谢谢!

最佳答案

您可以通过在 JS 中导入字体并将其传递给样式组件 css 模板标记来解决此问题:

import { css } from 'styled-components';
import { fontWeight } from './vars';

import myFontURL from '../../mypath/fonts/OurFont-Bold.woff2';

export const fontFaces = css`
@font-face {
font-family: 'OurFont';
src: url(${myFontURL}) format('woff2');
font-weight: ${fontWeight.bold};
font-style: normal;
}
`;

请务必不要使用 /resources/fonts/OurFont-Bold.woff2,而使用当前文件目录的相对路径。

关于reactjs - 导入字体以使用 webpack 和样式组件 react 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55031674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com