问题
I have a react app for which I want to add a sitemap.xml. I have added this route to link to the file (XML is my my sitemap.xml):
import XML from './sitemap.xml';
<Route component={XML} path={'/sitemap.xml'} />
I keep getting this error, which I understand it means that I need to add an xml loader to my webpack:
You may need an appropriate loader to handle this file type.
Not sure how to pick an xml loader as I could mostly find parsers (xml to json) and I am not sure if it's ok to have the sitemap in json. Also, is there any other native way of displaying the xml file without adding any loader?
回答1:
If you are using create-react-app, just put your XML file in public folder (a folder beside node_modules and src folders), then access it through {base_url}/{XML_file_name.xml}
(e.g. localhost:3000/sitemap.xml
)
回答2:
In , keyword component should be a React Component.
Check the documentation:Route - React Router
If you want to pass XML as a variable, you should change XML format to string and with another prop but component={}
.To transform XML to String, ry escape(XML)
before passing to Route! Check escape(str)
with import
keyword, youcan try like this:
// 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()}/>
来源:https://stackoverflow.com/questions/42382193/xml-sitemap-for-react-app