0

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

j. doe
  • 163
  • 3
  • 11

2 Answers2

0

There are multiple ways to export stuff in JS... e.g., 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.

10110
  • 2,353
  • 1
  • 21
  • 37
  • hi! so I tried doing the export at the end, but I got the same error. I currently have jsonToAim defined as `function jsonToAim(jsonObj) {...}`. I was also wondering, why did you define the first line like that? thank you so much! – j. doe Oct 14 '20 at 05:16
  • Did you change the function definition to `const jsonToAim = (jsonObj) => {...}` before trying again? You can define an 'anonymous' function like this: `(fooParam) => {return fooParam}` and then assign it to a const or var like I did above thanks to ES6 's arrow functions. – 10110 Oct 14 '20 at 05:24
0

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:

ES6 imports for JWT

bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • Do I call the jsonToAim function like this? `jsonToAim(x)` or `jsonToAim.jsonToAim(x)` or something else? It doesn't seem to enter this function when i tried running it – j. doe Oct 14 '20 at 06:16
  • just `jsonToAim()`. i have tested it it works @j.doe – bill.gates Oct 14 '20 at 06:19