JS module export/import does not work
I need help getting what amounts to a straightforward module export/import to work.
I followed docs/notes online for construction a rudimentary module, with the export statement at the top, then in the calling script, I reference the item within the module in the import statement and the "stupid" error appears
Uncaught SyntaxError: import declarations may only appear at top level of a module
Here's the jist:
project.js looks like:
time_utils.js looks like:
The browser throws and error on the import
line in project.js.
So, what am I missing to make this work? Thanks for any/all substantive contributions! 🙏10 Replies
Your script tag needs a
type=“module”
so the browser knows it’s a module
Otherwise it’s treated as a non-module scriptreferring to the project.js needs to be be in a script tag with a type=module attribute?
Yes
added type="module" to
script
tag, fixed a few other errors, now the page throws "the requested module './time_utils.js' doesn't provide an export named: 'time_utils' " ... grrr 😠Remove the named default export, so the import syntax is Named Default exports are not destructured as part of the
default
in the export statement
Ok, explanation time:
When you export default time_utils;
then it's a import time_utils from ...
. import { ... } from ...
, so you can't use curly braces for default imports/exports.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#default_exports_versus_named_exportsI appreciate the read-in because I'm just getting acquainted with this style of JS coding and it's been rough going for something that ought to be straightforward.
No worries. It’s one of those, “you don’t know what you don’t know” kinda things
Did you mean to say default exports instead of named exports here? Cause
export default time_utils;
is a default export and named exports are the ones that're destructuredYes, you're right. Fixed
👍