1.安装必要的插件
npm install --save next-compose-plugins expo-font
或者
yarn add next-compose-plugins expo-font
2. 设置
next.config.js
const { withExpo } = require('@expo/next-adapter');
const withFonts = require('next-fonts');
const withImages = require('next-optimized-images');
const withPlugins = require("next-compose-plugins");
module.exports = withPlugins([
withFonts,
withImages,
[
withExpo,
{ projectRoot: __dirname }
]
]);
3.类型声明
创建以下文件以便能够import
为您的字体使用该语句。
declarations.d.ts
将以下内容粘贴到文件中。
declare module '*.ttf' {}
4.加载字体
我创建了以下自定义挂钩来异步加载资源。
useResources.ts
import * as Font from 'expo-font';
import { useEffect, useState } from 'react';
import YOUR_FONT_FILE_HERE from '/path/to/fonts/FONT_NAME.ttf';
export const useResources = () => {
const [isFontReady, setIsFontReady] = useState(false);
const loadFontAsync = async () => {
try {
await Font.loadAsync({
HindRegular: {
uri: YOUR_FONT_FILE_HERE as any,
display: Font.FontDisplay.SWAP,
}
});
} catch (error) {
console.log('Font Load Error:', error)
} finally {
setIsFontReady(true);
}
}
useEffect(() => {
loadFontAsync();
}, []);
return {
isFontReady
}
};
5. 用法
在这里,我们在尝试使用资源之前确保资源可用。
export default function App() {
const { isFontReady } = useResources();
if (!isFontReady) {
return (
<View>
<Text>Resources are loading...</Text>
</View>
)
}
return (
<View style={styles.container}>
<Text style={styles.text}>Welcome to Expo + Next.js </Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 16,
fontFamily: 'YOUR_FONT_NAME_HERE' <----- HERE
},
});
供进一步阅读的资源。
已关闭问题回复(大开眼界)
世博字体
Expo-NextJS