Daydreamer-riri / vite-react-ssg

Static-site generation for React on Vite.
https://vite-react-ssg.netlify.app/
MIT License
97 stars 4 forks source link

How to import json file? #17

Closed widiu7omo closed 3 months ago

widiu7omo commented 3 months ago

Hello, could you explain to me how to import json file?

Already test with this, but the result still null.

import { useLoaderData } from "react-router-dom";
export async function loader() {
  const blocks = await import("../../generated/article/blocks.json")
  return { blocks }
}
export default function GeneratorPage() {
  const data = useLoaderData()
  console.log(data)
  return (
    <div>
      <a href="/">Back</a>
    </div>
  );
}
Daydreamer-riri commented 3 months ago

Hi @widiu7omo, in Vite, to dynamically import a JSON file, you need to access its default property.

I have updated the example; you can review the code or clone it to try it out: https://github.com/Daydreamer-riri/vite-react-ssg/blob/main/examples/with-loader/src/pages/json.tsx

If there are still any issues, please let me know, and I will respond as soon as possible.

widiu7omo commented 3 months ago

Thank you. It's working.