为何在Fresh框架handler中返回字面量会触发“Expected a semicolon”错误?
问题场景
使用Fresh框架开发时,原有可正常运行的index.tsx路由代码如下:
import { Handlers, PageProps } from "$fresh/server.ts"; export const handler: Handlers<Data> = { GET(req, ctx) { const a = 'hello' return ctx.render({ a }) }, }; export default function Home({ data }: PageProps<Data>) { return ( <> {JSON.stringify(data) } </> ); }
将handler中的代码从:
const a = 'hello' return ctx.render({ a })
修改为:
return ctx.render({ 'hello' })
后触发如下错误:
error: Uncaught (in promise) TypeError: Expected a semicolon at file:///D:/QC%20supplements/Code/Apps/trankyweb/routes/index.tsx:24:33 return ctx.render({ 'hello' }) ~ const manifest = (await import(toFileUrl(join(dir, "fresh.gen.ts")).href)) ^ at async dev (https://deno.land/x/fresh@1.6.1/src/dev/dev_command.ts:38:21) at async file:///D:/QC%20supplements/Code/Apps/trankyweb/dev.ts:5:1 Watcher Process failed. Restarting on file change...
fresh.gen.ts为框架自动生成文件,dev.ts内容如下:
#!/usr/bin/env -S deno run -A --watch=static/,routes/ import dev from "$fresh/dev.ts"; await dev(import.meta.url, "./main.ts");
错误原因
{ 'hello' }不符合JavaScript/TypeScript的对象字面量语法规则。对象字面量必须以键值对形式存在,比如{ 键名: 值 };或者当键名和变量名一致时,可使用简写{ 变量名 }(等价于{ 变量名: 变量名 })。
单独的字符串'hello'放在对象大括号里没有对应的键名,属于语法错误。Deno解析器处理该错误时,错误提示指向行尾,误以为缺少分号,但实际问题是对象字面量的语法不合法。
如果想传递包含hello值的对象,需要明确键值对,示例如下:
// 方式1:指定键名和对应值 return ctx.render({ msg: 'hello' }) // 方式2:使用变量简写(需先定义同名变量) const hello = 'hello'; return ctx.render({ hello })
内容的提问来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

