javascript - 浏览器无法识别用 Node 文件系统编写的 html 文件

标签 javascript html node.js ejs server-side-rendering

<分区>

我正在使用 React 和 Apollo 2 构建一个应用程序,我正在尝试编写一个脚本来生成用于服务器端呈现的静态 html 文件。

我目前正在使用此逻辑在服务器上呈现我的 React 组件并且它工作正常:

export default (Page) => (req, res) => {
    const App = (
        <ApolloProvider client={client(fetch)}>
            <Main>
                <Page />
            </Main>
        </ApolloProvider>
    );

    getDataFromTree(App).then(() => {
        const data = {
            html: ReactDOMServer.renderToString(App),
            seo: { title: "Home", description: "" }
        };
        res.render("index", { data });
    });
}

但我想生成 .html 文件,这样我就可以静态地提供它们,而不用每次都运行这个方法。我尝试将 renderToString 的结果编译为 .ejs 文件,然后使用 fs 写入文件,但没有成功。这是代码:

const component = ReactDOMServer.renderToString(App);
const template = ejs.compile(fs.readFileSync(path.join(__dirname, 'landing_template.ejs'), 'utf-8'));
const html = template({ component });

fs.writeFile(
    path.join(__dirname, "../views/landing.ejs"),
    html, 
    err => {
        if(err) console.log(err);
        else console.log("done.");
});

文件写入成功,但如果我打开我的页面源代码,编译方法添加的部分显示为灰色,似乎被忽略了:

enter image description here

我也试过只读取文件并使用 .replace 替换字符串并插入一个虚拟 div,但结果始终相同。

// using compile
const template = ejs.compile(fs.readFileSync(path.join(__dirname, 'landing_template.ejs'), 'utf-8'));
const html = template({ component });

const template = ejs.compile(fs.readFileSync(path.join(__dirname, 'landing_template.ejs'), 'utf-8'));
const html = template({ component: "<div>teste</div>" });

// using readFile
const template = fs.readFileSync(path.join(__dirname, 'landing_template.ejs'), 'utf-8');
const html = template.replace("<%- component %>", component);

const template = fs.readFileSync(path.join(__dirname, 'landing_template.ejs'), 'utf-8');
const html = template.replace("<%- component %>", "<div>teste</div>");

// maybe this is the problem?
fs.writeFile(
    path.join(__dirname, "../views/landing.ejs"),
    html,
    { encoding: "utf8" },
    err => {
        if(err) console.log(err);
        else console.log("done.");
});

enter image description here

我猜浏览器没有将这个新文本识别为 HTML 并且无法解析它。有谁知道我可以用什么方法来完成这项工作?

谢谢!

最佳答案

<script />是错的。你必须使用这个:

<script src="URL"></script>

关于javascript - 浏览器无法识别用 Node 文件系统编写的 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49835223/

相关文章:

javascript - 与 parent 一起点击两下功能

javascript - 并非所有坐标都使用平行坐标 (d3) 绘制

javascript - Bootstrap 表特定列的最后一行

node.js - Mongoose 填充对子文档的引用

javascript - Angular Leaflet - GeoJson 隐藏在图层更改上

javascript - 单击时可调整大小的侧边导航展开

android - 在 Android 4.4.4 的 webview 中使用 contenteditable-Tag 跳转光标

node.js - Microsoft bot 旧版本警告消息即使在更新后仍然存在

javascript - 异步函数与javascript中的类

php - 如何使用 Adob​​e AIR HTML/JS/jQuery 访问 Web 服务器上的 PHP 文档