-1

I'm getting mad with module import/export syntax...

Say on a file I want to import a module like this:

import { AccordionMenu } from '../node_modules/lr-js-modules/accordion-menu';

Now, how should I export from accordion-menu? My current code is an old school js class like this:

AccordionMenu = function(options){
[...]
}

AccordionMenu.prototype = { ... }

Then I was exporting like this:

export { AccordionMenu as default };

It doesn't work. Compiler says

export 'AccordionMenu' (imported as 'AccordionMenu') was not found in '../node_modules/lr-js-modules/accordion-menu' (possible exports: default)

I then tried several variants, but none worked to me. From mdn docs, as far as I can tell, all teh variants should work, but it's evident that I'm doing something wrong.

Can you help please?

2
  • did you try export { AccordionMenu }? Commented Mar 22, 2022 at 11:57
  • Try this: const AccordionMenu = function(options) { ... }; then at the end of the file export default AccordionMenu;. To import you can then import AccordionMenu from '...'; - you don't need { ... } as it's the default export Commented Mar 22, 2022 at 12:01

1 Answer 1

2

The error message is quite clear: you exported default but your import tries to access an export AccordionMenu.

You should use either

export function AccordionMenu(options) { … }
// same as:
// function AccordionMenu(options) { … }
// export { AccordionMenu as AccordionMenu }

AccordionMenu.prototype = { … };

with

import { AccordionMenu } from '../node_modules/lr-js-modules/accordion-menu';
// same as:
// import { AccordionMenu as AccordionMenu } from '../node_modules/lr-js-modules/accordion-menu';

or, if that function is the only (or main) export of that module, use a default export

export default function AccordionMenu(options) { … }
// same as:
// function AccordionMenu(options) { … }
// export { AccordionMenu as default }

AccordionMenu.prototype = { … };

with

import AccordionMenu from '../node_modules/lr-js-modules/accordion-menu';
// same as:
// import { default as AccordionMenu } from '../node_modules/lr-js-modules/accordion-menu';

but the mix doesn't work.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, the first solution is what I was looking for. It's quite comic that I'm programming es6 since at least 1 year and still I didn't fully understand import/export syntax, and above all, the reason under every variant. Still didn't find a really clear (to me) online documentation. I don't even fully get the reason why there are so many ways of doing this kind of things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.