【问题标题】:What does the export function javascript error mean and how can I fix it?导出函数 javascript 错误是什么意思,我该如何解决?
【发布时间】:2020-10-14 13:17:13
【问题描述】:

所以我试图在另一个脚本 b.js 中调用在 a.js 中创建的函数 jsonToAim()

这是我在 a.js 中定义的:

export function jsonToAim(jsonObj){...}

这就是我在 b.js 中的称呼

const backend = require('./a')`
let aimObj = backend.jsonToAim(jsonObj);

我最终得到了这个错误:

export function jsonToAim(jsonObj){
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:992:16)
    at Module._compile (internal/modules/cjs/loader.js:1040:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:941:32)
    at Function.Module._load (internal/modules/cjs/loader.js:782:14)
    at Module.require (internal/modules/cjs/loader.js:965:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (/create-aims/getAim.js:4:17)
    at Module._compile (internal/modules/cjs/loader.js:1076:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)

有人知道我哪里出错了吗?抱歉,如果这是一个愚蠢的问题,我对 js 很陌生

【问题讨论】:

标签: javascript node.js


【解决方案1】:

在 JS 中有多种export 东西的方法...例如,CommonsJS 与 ES6 导出语法。

NodeJS 出于某种原因目前不支持您使用的 ES6 import/export 语法。

试试 CommonJS 语法 (require/exports):

const jsonToAim = (jsonObj) => {...}

//At the end of your file:
export {
 jsonToAim
}

这是关于 ES6 与 CommonJS 导出语法的really good thread

【讨论】:

  • 嗨!所以我尝试在最后进行导出,但我得到了同样的错误。我目前将 jsonToAim 定义为function jsonToAim(jsonObj) {...}。我也想知道,你为什么要这样定义第一行?非常感谢!
  • 在重试之前是否将函数定义更改为const jsonToAim = (jsonObj) =&gt; {...}?您可以像这样定义一个“匿名”函数:(fooParam) =&gt; {return fooParam},然后像我上面所做的那样将它分配给一个 const 或 var,这要归功于 ES6 的箭头函数。
【解决方案2】:

问题是你使用 ES Modules 而不是 CommonJS

Node.js 默认使用 Common js require()

这意味着:

export function jsonToAim(jsonObj){...}

应该是

function jsonToAim(jsonObj){...}

module.exports.jsonToAim = jsonToAim;

稍后您将其导入:

const { jsonToAim } = require(...);

不过你也可以在 node.js 中使用 ES 模块。

我已经为这类问题写了一个类似的答案:

ES6 imports for JWT

【讨论】:

  • 我这样调用jsonToAim函数吗? jsonToAim(x)jsonToAim.jsonToAim(x) 或其他?我尝试运行时似乎没有进入此功能
  • 只是jsonToAim()。我已经测试过它可以工作@j.doe
猜你喜欢
  • 2013-12-08
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 2012-07-09
  • 2014-07-05
  • 2016-06-17
  • 2018-08-27
相关资源
最近更新 更多