在styled-components中导入Google Web Fonts遇报错,求组件内可行方案
在styled-components内部导入Google Web Fonts的可行方法
官方确实不推荐在createGlobalStyle里使用@import语法,但有两种能在styled component内部处理字体导入的方案,无需依赖额外库或手动修改index.html:
方法1:用@font-face直接引入字体文件
Google Fonts支持直接获取字体文件的资源链接(比如woff2格式),你可以在createGlobalStyle里通过@font-face定义字体,之后就能全局使用:
import { createGlobalStyle } from 'styled-components'; const GlobalStyle = createGlobalStyle` @font-face { font-family: 'Roboto'; font-style: normal; font-weight: 400; src: url('https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxKKTU1Kg.woff2') format('woff2'); unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; } body { font-family: 'Roboto', sans-serif; } `; export default GlobalStyle;
注:字体文件链接可以从Google Fonts的嵌入代码里提取——选择「@import」选项,里面的URL就是字体文件的直接地址,复制过来用即可。
方法2:在单个styled组件内注入字体(仅推荐开发环境用)
如果不需要全局导入,只想给某个组件单独用特定字体,可以结合css辅助函数使用@import,但要注意生产环境可能仍会出现CSSOM解析问题,建议优先用方法1或官方推荐方案:
import styled, { css } from 'styled-components'; const StyledCard = styled.div` ${css` @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); `} font-family: 'Roboto', sans-serif; padding: 1rem; `;
补充:官方禁止createGlobalStyle里用@import的原因
生产环境中styled-components依赖CSSOM API插入样式,@import会触发额外网络请求,且CSSOM对@import的解析顺序和普通样式表不同,容易导致字体加载延迟、样式错乱等问题,因此官方更推荐把字体链接放在HTML的<head>中,或用react-helmet这类库注入。
但如果一定要在styled component内部完成字体导入,方法1是最稳妥的替代方案。
内容的提问来源于stack exchange,提问作者HwanMin
相关产品推荐
相关产品推荐

