简体   繁体   English

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

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

so I'm trying to call the function jsonToAim(), which is created in a.js, in another script b.js所以我试图在另一个脚本 b.js 中调用在 a.js 中创建的函数 jsonToAim()

this is how I defined it in a.js:这是我在 a.js 中定义它的方式:

export function jsonToAim(jsonObj){...}

this is how I called it in b.js这就是我在 b.js 中调用它的方式

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

I ended up getting this error:我最终收到此错误:

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)

does anyone know where I went wrong?有谁知道我哪里出错了? sorry if this is a stupid question i'm super new to js抱歉,如果这是一个愚蠢的问题,我是 js 的超级新手

There are multiple ways to export stuff in JS... eg, the CommonsJS vs ES6 export syntax.有多种方法可以在 JS 中export内容……例如,CommonsJS 与 ES6 导出语法。

NodeJS for whatever reason doesn't support at this time the ES6 import/export syntax you're employing.无论出于何种原因,NodeJS 目前都不支持您使用的 ES6 import/export语法。

Try the CommonJS syntax ( require/exports ):尝试 CommonJS 语法( require/exports ):

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

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

Here's a really good thread about the ES6 vs CommonJS export syntax.这是一个关于 ES6 与 CommonJS 导出语法的非常好的线程

The problem is that you use ES Modules instead of CommonJS问题是你使用 ES Modules 而不是 CommonJS

Node.js uses by default Common js require() Node.js 默认使用 Common js require()

That means that:这意味着:

export function jsonToAim(jsonObj){...}

should be应该

function jsonToAim(jsonObj){...}

module.exports.jsonToAim = jsonToAim;

Later you import it with:稍后您使用以下命令导入它:

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

However you can use ES modules in node.js too.但是你也可以在 node.js 中使用 ES 模块。

I have written an similar answer for this type of problem:我为这类问题写了一个类似的答案:

ES6 imports for JWT JWT 的 ES6 导入

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

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