1

I wrote a Javascript module called module.js that does the following

export default function myModule() {
    return new Promise((resolve) => {
        // do a bunch of stuff
    });
};

I have the following Javascript code, test.js, that uses myModule() in module.js

import {myModule} from "module";
myModule().then((retVal) => {
    console.log(retVal);
});

Unfortunately, my browser console is telling me I have the following syntax error:

Uncaught SyntaxError: Unexpected identifier

The console says the syntax error on line 1 of test.js but I can't see what's wrong with it. Any insight is much appreciated.

Brinley
  • 561
  • 10
  • 25

2 Answers2

3

Since you are only importing a single function, you should remove the {} from the import. Also, you should change from, to a "path syntax". You should end up with this:

import myModule from "./module";
Leffe
  • 116
  • 1
  • 6
1

When exporting with default you don't use the braces `. Try this instead:

import myModule from "module"

See here: When should I use curly braces for ES6 import?

Edit

As mentioned, if you are importing this from a file in your project rather than a node module then you will to specify the path to the file you are exporting from. I have tested the below code in my project and do receive the expected result test resolve in the console. Let me know if this still doesn't work for you.

module.js

export default function myModule() {
    return new Promise((resolve) => {
        // do a bunch of stuff
        resolve('test resolve');
    });
};

index.js

import myModule from "./module"; // Notice there are no braces (as we are exporting default) and that we are specifying the path
myModule().then((retVal) => {
    console.log(retVal);
});

Specifying the path

./ will search in the current directory of the file you are importing with.

../ will search the directory one level up from the file you are importing with

../../ will search the directory two levels up from the file you are importing with

Community
  • 1
  • 1
TPHughes
  • 1,126
  • 10
  • 12
  • Now I'm getting: Uncaught SyntaxError: Unexpected identifier – Brinley May 23 '18 at 19:17
  • and again, the source of the error is line 1 of test.js – Brinley May 23 '18 at 19:17
  • test.js is the second code chunk in my original post – Brinley May 24 '18 at 11:52
  • And that is what I was asking you to change. Also note that you need to use path syntax as mentioned by MBehemam, I didn't include this in case may have been importing directly from a node module. See the updated code with `./` in the import path. – TPHughes May 24 '18 at 13:05