我使用的是create-react-app和一些外部模块,比如react-markdown。我如何“要求”一个动态生成的文件名?我有数以千计的markdown文件,我需要动态加载它们。如果我提供一个静态路径,我的组件工作得很好,但是当我尝试连接这个路径时就不能工作了。我不能静态导入,因为文件太多。
示例:
import React, { useState, useEffect } from "react";
import ReactMarkdown from "react-markdown/with-html"
const MarkdownServer = ({myMarkdownFilename}) => {
const [markdown, setValue] = useState([]);
useEffect(() => {
async function fetchData() {
// this works...
// const p = require("../../assets/markdown/mymarkdown.md")
// this does not.
const p = require("../../assets/markdown/" + myMarkdownFilename);
const markdown = await fetch(p).then(res => res.text());
setValue(markdown);
}
fetchData();
}, []);
return (
<p>
<ReactMarkdown source={ markdown } escapeHtml={false} />
</p>
);
};
export default MarkdownServer;错误:
Unhandled Rejection (Error): Cannot find module '../../assets/markdown/mymarkdown.md'发布于 2019-11-06 09:39:31
发布于 2019-11-06 23:18:01
解决方案是使用Webpack context module API创建一个上下文模块。通过使用一些正则表达式,我能够请求markdown文档。
在标准导入之后:
const cache = {};
function importAll (r) {
r.keys().forEach(key => cache[key] = r(key));
}
importAll(require.context("../../assets/markdown/", true, /\.md$/)); 缓存对象现在包含所需的文件及其作为名称:值对的散列名称。在我的代码中,我只是构建了文件名,并使用它来访问属性:
useEffect(() => {
async function fetchData() {
filepath = "../../assets/markdown/" + myMarkdownFilename
const p = cache[filepath]
const markdown = await fetch(p).then(res => res.text());
setValue(markdown);
}
fetchData();
}, []);话虽如此,确实应该有一种更明智的方式来导入静态资产。
https://stackoverflow.com/questions/58721827
复制相似问题