so I'm trying to call the function jsonToAim(), which is created in a.js, in another script b.js
this is how I defined it in a.js:
export function jsonToAim(jsonObj){...}
this is how I called it in 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
There are multiple ways to export
stuff in JS... eg, the CommonsJS vs ES6 export syntax.
NodeJS for whatever reason doesn't support at this time the ES6 import/export
syntax you're employing.
Try the CommonJS syntax ( 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.
The problem is that you use ES Modules instead of CommonJS
Node.js uses by default 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.
I have written an similar answer for this type of problem:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.