0

So I have these two files:

foo1

const a = 2;
export {a};

and

foo2

import a from "./foo1.js";
console.log(a);

both files have been made module files with the html:

    <script src='./scripts/foo2.js' type='module'></script>
    <script src='./scripts/foo1.js' type='module'></script>

As soon as the script runs it throws this error:

Uncaught SyntaxError: The requested module './foo2.js' does not provide an export named 'default'

  • Check out what [export default](https://stackoverflow.com/questions/21117160/what-is-export-default-in-javascript) means. – Vikram Negi Sep 06 '21 at 16:44
  • Perhaps this can help: https://stackoverflow.com/questions/49338193/how-to-use-code-from-script-with-type-module – tromgy Sep 06 '21 at 16:46
  • 1
    If `import a from "./foo1.js";` is how you want to import it, then you need to export it as `export default a;` – Nicholas Tower Sep 06 '21 at 16:47

2 Answers2

0

The way you are importing works only with default export/import. So there are two ways you can fix your code:

  1. changing the import statement

import a from "./foo1.js";

(Not using default exports)

  1. changing the export statement

export default a;

Then while importing you can do anything, because the default export is still a:

import a from "./foo1.js"; import aWithNewName from "./foo1.js";

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • The second solution worked but could you elaborate on what you mean by "The way you are importing works only with default export/import"? –  Sep 07 '21 at 00:27
  • Also, with the second solution, I then ran into the issue where if I make a different variable and export that, it will only export the default instead. –  Sep 07 '21 at 00:35
  • You are doing `import a from ...` . Here `a` will be the default import only because there are no curly braces. Now since there **was no default export**. Hence the issue – Tushar Shahi Sep 07 '21 at 05:26
  • In the second situation if you want to import more than one variable you will have to do `import aDefault , { bNotDefault, cNotDefault }`. Note how the default variable can be without braces, rest all have to be inside. Check : https://stackoverflow.com/questions/57723020/how-to-import-both-default-and-named-from-an-es6-module – Tushar Shahi Sep 07 '21 at 05:29
  • The first solution also worked thank you, I had no idea that the curly braces made a difference. –  Sep 07 '21 at 07:07
0

If you to export from foo1 there's no need to add both js files, you need only the file where you want to import. Try this way:

// foo1.js
export const a = 2;

// foo2.js
import { a } from "./foo1.js";
console.log(a);
 <script src='./scripts/foo2.js' type='module'></script>
John Shot
  • 296
  • 3
  • 11