2

I am loading all markdown files within a directory using a glob import:

const useGetChangelogs = () => {
  const [changelogs, setChangelogs] = useState<string[]>([]);

  useEffect(() => {
    const arr: string[] = [];
    Promise.all(Object.keys(import.meta.glob("~/changelogs/*.md")).sort((a, b) => b.localeCompare(a))
      .map(async (file) => fetch(file)
        .then((res) => res.text())
        .then((str) => arr.push(str))
      )
    ).then(() => setChangelogs(arr)).catch((err) => console.error(err));
  }, []);

  return changelogs;
};

It works perfectly when running a development build, but on production it displays the following:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Error</title> </head> <body> <pre>Cannot GET /changelogs/v0.8.4-alpha.md</pre> </body> </html>

Vite config:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import eslint from "vite-plugin-eslint";
import svgr from "vite-plugin-svgr";
import path from "path";
import autoprefixer from "autoprefixer";

const output = {
  manualChunks: (id: string) => {
    if (id.includes("node_modules")) return id.toString().split("node_modules/")[1].split("/")[0].toString();
  }
};

export default defineConfig({
  server: { host: "0.0.0.0", port: 3000 },
  resolve: { alias: { "~": path.resolve(__dirname, "src") } },
  css: { postcss: { plugins: [autoprefixer()] }, modules: { localsConvention: "camelCase" } },
  plugins: [react(), eslint(), svgr()],
  assetsInclude: ["**/*.md"],
  build: { rollupOptions: { output } }
});

I tried adding the following to my rollupOptions as suggested from Vue + Vite + Rollup: Dynamic import not working on production build, but it did not seem to work

export default defineConfig({
    build: {
        rollupOptions: {
            external: [
                "/path/to/external/module.es.js"
            ]
        }
    }
})

Any help would be very much appreciated.

Chambers
  • 21
  • 3

1 Answers1

0

I ended up solving the problem myself. After gaining a better understanding of glob imports, I was able to ditch the custom hook and opt for a much simpler solution.

const changelogs = Object.values(import.meta.glob("~/changelogs/*.md", { eager: true, as: "raw" }));

This solution also has the benefit of not using fetch, the files are imported at build time rather than at run time.

I was also able to remove assetsInclude: ["**/*.md"] from my Vite config with this solution.

Chambers
  • 21
  • 3