プリレンダリング時に静的ファイルを読み込む
SSG 想定で書いてます。SSR でやると fs.readFileSync()
がブロッカーになってレンダリング処理の速度が死にます
確認環境
Env |
Ver |
next |
10.1.3 |
react |
17.0.1 |
node |
14.15.5 |
typescript |
4.2.4 |
サンプルコード
公開ファイルの読み込み
public/
に読む込むファイルを置いて、getStaticProps()
で事前読み込みしてレンダー時にデータが渡るようにしてやる
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 | import * as fs from 'fs';
const Biography = ({ data }: { data: string }) => {
console.log(data);
return <p>aaa</p>;
};
export const getStaticProps = async () => {
const data = fs.readFileSync('public/data.yaml').toString();
if (!data) {
return {
notFound: true,
};
}
return {
props: { data },
};
};
export default Biography;
|
非公開ファイルの読み込み
ファイルのフルパスを渡して読んでやればいけます
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 | import * as fs from 'fs';
const Biography = ({ data }: { data: string }) => {
console.log(data);
return <p>aaa</p>;
};
export const getStaticProps = async () => {
const filePath = path.join(process.cwd(), 'contents/data.yaml');
const data = fs.readFileSync(filePath).toString();
if (!data) {
return {
notFound: true,
};
}
return {
props: { data },
};
};
export default Biography;
|