繁体   English   中英

导出函数 javascript 错误是什么意思,我该如何解决?

[英]What does the export function javascript error mean and how can I fix it?

所以我试图在另一个脚本 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 的超级新手

有多种方法可以在 JS 中export内容……例如,CommonsJS 与 ES6 导出语法。

无论出于何种原因,NodeJS 目前都不支持您使用的 ES6 import/export语法。

尝试 CommonJS 语法( require/exports ):

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

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

这是一个关于 ES6 与 CommonJS 导出语法的非常好的线程

问题是你使用 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 模块。

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

JWT 的 ES6 导入

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM