43

I am trying to learn ES6 imports and exports but I ran into an error that is not letting me import my module. I also tried import .. from 'add.js' without ./ but still no luck.

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

My folder structure looks like this

C:\xampp\htdocs\es6\import.export\
- index.html
- app.js
- add.js

index.html

<html>
    <head>
        <script type="module" src="app.js"></script>
    </head>

    <body>

    </body>
</html>

app.js

import { add } from './add.js'

console.log(add(2,3))

add.js

export default function add (a, b) {
// export default function (a, b) { <-- does not work either, same error
    return a + b;
}
Liga
  • 3,291
  • 5
  • 34
  • 59

2 Answers2

49

Option 1

Name your export instead of using default. It should look like this

// add.js
export const add =  (a, b) =>  a + b;
// OR
// export const add = function(a, b) { return a+b };

// app.js
import { add } from './add';

Option 2

Use the export default syntax. It looks like this

// add.js
export default function add(a, b) {
  return a + b;
}

// app.js
import add from './add';
molamk
  • 4,076
  • 1
  • 13
  • 22
36

There are two kinds of exports: named exports (several per module) and default exports (one per module). It is possible to use both at the same time, but usually best to keep them separate.

If you want to import the module's default, the curly braces '{}' are not needed :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Using_the_default_export

You can use curly braces '{}' for named exports :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export#Using_named_exports

Zak
  • 1,005
  • 10
  • 22
  • 7
    This answer is misleading. You use the phrase "If you have a default export", but the "export" happens in the module's code, not in the importer's code. The presence or absence of a "default" in the module doesn't impact whether "you should not use {}." What matters is the intention of the importer. Therefore, this should read more like: "If you want to import the module's default, the curly braces '{}' are not used, since they would indicate you want to import by name." – IAM_AL_X Mar 28 '20 at 18:20
  • You're right! I didn't thought of classes with multiple exports. Updating my answer. Thanks @IAM_AL_X – Zak Mar 28 '20 at 21:10
  • Well.. we've noticed a very inconsistent behaviour with imports on Chromium. Sometimes it wouldn't accept an import with braces and sometimes require these all other things held constant. – Vega4 Aug 27 '21 at 13:52
  • 1
    it actually gets so ridiculous that import with same syntax does not work from another module within the same directory without any tangible reason so one ends up toggling through possibilities and seeing which one turns out to work in a particular file. Sounds crazy but true it is. – Vega4 Aug 29 '21 at 07:50