6

我有一个反应应用程序,我想为其添加一个 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 文件而不添加任何加载程序?

4

3 回答 3

7

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

于 2017-09-07T10:33:03.407 回答
1

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

查看文档:<a href="https://github.com/ReactTraining/react-router/blob/master/docs/guides/RouteConfiguration.md" rel="nofollow noreferrer">Route - React Router


如果您想将 XML 作为变量传递,您应该将 XML 格式更改为字符串并使用另一个属性,但是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()}/>

于 2017-02-22T03:39:54.787 回答
0

一个简单的解决方案是添加 <a href="XML_PATH" style={{display:"none"}}>xml</a> 然后检查您的谷歌浏览器开发控制台,搜索锚(a)标签。并遵循路径

于 2020-12-28T16:49:24.337 回答