我试图将 ReactDOMServer.renderToString() 与 Babel/Register 一起使用。ReactComponent 的 JSX 有几个图像引用。ReactDOMServer.renderToString 方法在没有图像引用时有效,但在有图像引用时无效。它会引发意外的令牌错误。所以我的问题是:这种方法是否支持使用图像引用对 React 组件进行字符串化?还是我需要做一些 webpack 配置?ReactDomServer.renderToString 和 Next.js 有什么区别?
Server.js
require("@babel/register")({
extensions: [".tsx", ".es6", ".es", ".jsx", ".js"],
// presets: ["es2015", "react"],
});
var test = require("./test");
Test.js
import React from "react";
import Test1 from "./test1";
var ReactDOMServer = require("react-dom/server");
module.exports = function () {
var str = ReactDOMServer.renderToString(<Test1 />);
console.log(str);
return str;
};
Test1.js
import React from "react";
export default function Test(props) {
return (
<div>
<h1>this is some JSX</h1>
<p>this is a para element</p>
</div>
);
}
Not working
Test1.js
import React from "react";
export default function Test(props) {
return (
<div>
<h1>this is some JSX</h1>
<img src = "../images/ico.png">
<p>this is a para element</p>
</div>
);
}