preact-render-to-string 用于快速返回意外标记 <

preact-render-to-string for express returning Unexpected token <

我是第一次使用 preact 并尝试在 express 服务器中呈现 JSX 代码。

我知道 express 不理解 JSX 语法并且需要 babel。

我已经安装了 babel 和 transform-react-jsx,但我仍然遇到未定义的错误。

错误:

/Users/akarpov/Downloads/test_preact_node/app.js:9
  <div class="fox">
  ^

SyntaxError: Unexpected token <

.babelrc

{
  "presets": ["@babel/preset-env"],
  "plugins": ["transform-react-jsx"]
}

package.json

{
  "name": "test_preact_node",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "@babel/core": "^7.17.10",
    "@babel/node": "^7.17.10",
    "@babel/preset-env": "^7.17.10",
    "body-parser": "^1.20.0",
    "cors": "^2.8.5",
    "express": "^4.18.1",
    "nodemon": "^2.0.16",
    "preact": "^10.7.1",
    "preact-render-to-string": "^5.2.0"
  },
  "devDependencies": {
    "babel-plugin-transform-react-jsx": "^6.24.1"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel app.js",
    "start": "npm run build && nodemon — exec babel-node app.js"
  },
  "author": "",
  "license": "ISC"
}

app.js

const express = require("express");
const { h } = require("preact");
const render = require("preact-render-to-string");

/** @jsx h */

// silly example component:
const Fox = ({ name }) => (
  <div class="fox">
    <h5>{name}</h5>
    <p>This page is all about {name}.</p>
  </div>
);
const app = express();

app.listen(3200);

// on each request, render and return a component:
app.get("/:fox", (req, res) => {
  let html = render(<Fox name={req.params.fox} />);
  // send it back wrapped up as an HTML5 document:
  res.send(`<!DOCTYPE html><html><body>${html}</body></html>`);
});

几个问题:

  1. 标志是--exec,不是- exec
  2. 您的命令需要引号,即 'babel-node app.js'
-"start": "npm run build && nodemon — exec babel-node app.js"
+"start": "nodemon --exec 'babel-node app.js'"

不确定你为什么 运行 Babel 超过你的项目一次,然后立即使用 babel-node。可能只是您在调试时所做的事情?无论哪种方式,都不需要。