react应用程序的 XML 站点地图

IT技术 reactjs xml xml-sitemap
2021-05-12 13:10:09

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

import XML from './sitemap.xml';    
<Route component={XML} path={'/sitemap.xml'} />

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

You may need an appropriate loader to handle this file type.

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

3个回答

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

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

查看文档:Route - React Router


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


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

// file: get-xml.js
let transformXMLToString = () => {

  // read the target XML fiel and transform it to String
  
  // return the string
  return XMLasString;
};

export transformXMLToString;

// then you could import the XML like this in another file:

import transformXMLToString from 'get-xml.js';

// then pass it to <Route> like:

<Route component={transformXMLToString()}/>

一个简单的解决方案是添加 <a href="XML_PATH" style={{display:"none"}}>xml</a> 然后检查您的 google chrome 开发控制台,搜索 anchor(a) 标签。并按照路径