React 应用程序的 XML 站点地图

aii*_*iwa 6 xml xml-sitemap reactjs

我有一个反应应用程序,我想为其添加一个 sitemap.xml。我已添加此路由以链接到文件(XML 是我的 sitemap.xml):

import XML from './sitemap.xml';    
<Route component={XML} path={'/sitemap.xml'} />
Run Code Online (Sandbox Code Playgroud)

我一直收到这个错误,我明白这意味着我需要向我的 webpack 添加一个 xml 加载器:

You may need an appropriate loader to handle this file type.
Run Code Online (Sandbox Code Playgroud)

不知道如何选择 xml 加载器,因为我主要可以找到解析器(xml 到 json),我不确定在 json 中是否可以使用站点地图。另外,是否有任何其他本机方式可以在不添加任何加载程序的情况下显示 xml 文件?

San*_*tas 7

如果您使用的是 create-react-app,只需将您的 XML 文件放在公共文件夹(node_modules 和 src 文件夹旁边的文件夹)中,然后通过{base_url}/{XML_file_name.xml}(例如localhost:3000/sitemap.xml)访问它

  • 在本地主机上,我的 sitemap.xml 可以通过 http://localhost:3000/sitemap,XML 访问,但是当我将此应用程序部署到 AWS amplify 上时,无法通过 {baseURL}/{sitemap.xml} 访问它有什么建议吗? (3认同)

Rob*_*hen 1

在 中,关键字组件应该是一个 React 组件。

\n\n

查看文档\xef\xbc\x9a路由 - React Router

\n\n
\n\n

如果你想将 XML 作为变量传递,你应该将 XML 格式更改为字符串并使用另一个 prop,但是component={}。要将 XML 转换为字符串,请escape(XML)在传递给 Route 之前!检查转义(str)

\n\n
\n\n

使用import关键字,你可以尝试这样:

\n\n

\r\n
\r\n
// file: get-xml.js\r\nlet transformXMLToString = () => {\r\n\r\n  // read the target XML fiel and transform it to String\r\n  \r\n  // return the string\r\n  return XMLasString;\r\n};\r\n\r\nexport transformXMLToString;\r\n\r\n// then you could import the XML like this in another file:\r\n\r\nimport transformXMLToString from \'get-xml.js\';\r\n\r\n// then pass it to <Route> like:\r\n\r\n<Route component={transformXMLToString()}/>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n