我正在尝试从我的使用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',
},
},
],
},
我尝试遵循此线程的建议,但对我来说似乎不起作用,因为在控制台中出现错误,提示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
,而使用当前文件目录的相对路径。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句