reactjs - การนำเข้า glob ของ Vite react ไม่ทำงานบนการสร้างในโหมด production
ฉันกำลังโหลดไฟล์มาร์กดาวน์ทั้งหมดภายในไดเรกทอรีโดยใช้การนำเข้าแบบกลอบ:
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;
};
มันทำงานได้อย่างสมบูรณ์แบบเมื่อรันการสร้างสำหรับการพัฒนา แต่ในการผลิตจะแสดงผลดังต่อไปนี้:
<!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:
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 } }
});
ฉันพยายามเพิ่มสิ่งต่อไปนี้ใน rollupOptions ของฉันตามที่แนะนำจาก Vue + Vite + Rollup: การนำเข้าแบบไดนามิกไม่ทำงานใน build โปรดักชัน แต่ดูเหมือนว่าจะไม่ทำงาน
export default defineConfig({
build: {
rollupOptions: {
external: [
"/path/to/external/module.es.js"
]
}
}
})
ความช่วยเหลือใด ๆ จะได้รับความชื่นชมอย่างมาก
คำตอบ #1
ท้ายที่สุดฉันจึงแก้ปัญหาด้วยตัวเอง หลังจากที่เข้าใจการใช้นำเข้าแบบ glob ดีขึ้น ฉันจึงสามารถละทิ้ง hook แบบกำหนดเองและเลือกใช้วิธีแก้ปัญหาที่ง่ายกว่ามาก
const changelogs = Object.values(import.meta.glob("~/changelogs/*.md", { eager: true, as: "raw" }));
วิธีแก้ปัญหานี้ยังมีข้อดีคือไม่ใช้ fetch โดยไฟล์จะถูกนำเข้าในเวลาสร้างแทนที่จะเป็นเวลารัน
ฉันยังสามารถลบ assetsInclude: ["**/*.md"] ออกจากการตั้งค่า Vite ของฉันได้ด้วยวิธีแก้ปัญหานี้
