如何修复JS导出函数时出现的Declaration or statement expected. ts(1128)错误?
修复导出函数的ts(1128)错误
你遇到的Declaration or statement expected. ts(1128)错误,是因为导出语法不符合ES模块规范,TypeScript不支持直接export close_sidebar;这种写法。下面是两种可行的修复方案:
方案1:命名导出
有两种写法可选:
写法一:定义函数时直接导出
export function close_sidebar() { $("div#sidebar").css("display", "none"); $("div#rest").css("margin-left", "4px"); $("div#rest").css("width", "100%"); $("li#opensidebar").css("display", "block"); }
写法二:单独导出函数
function close_sidebar() { $("div#sidebar").css("display", "none"); $("div#rest").css("margin-left", "4px"); $("div#rest").css("width", "100%"); $("li#opensidebar").css("display", "block"); } export { close_sidebar };
方案2:默认导出
如果这个模块主要用于导出该函数,可以用默认导出:
function close_sidebar() { $("div#sidebar").css("display", "none"); $("div#rest").css("margin-left", "4px"); $("div#rest").css("width", "100%"); $("li#opensidebar").css("display", "block"); } export default close_sidebar;
React组件中的导入方式
- 命名导出对应的导入(需带花括号):
import { close_sidebar } from './你的文件相对路径';
- 默认导出对应的导入(无需花括号):
import close_sidebar from './你的文件相对路径';
额外提醒:代码中用到了jQuery的$,要确保React项目已正确引入jQuery,否则会出现$ is not defined的错误。
内容的提问来源于stack exchange,提问作者douaa ghelis
相关产品推荐
相关产品推荐

