- Create a temporary directory and
cdinto it - Clone the gist
- Run the examples
cd "$(mktemp -d)"
git clone [email protected]:4ba7867a771de384b66b512d1847de61.git .
node index.mjs
node index_dynamic.mjs
- Change the extension of all three
.mjsfiles to.js - Edit index.js and index.mjs to update the name of the imported file to
"./hello.js" - Attempt to run
index.jsandindex_dynamic.js. Note the warning and error message:Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension. SyntaxError: Cannot use import statement outside a module - Add
"type": "module"topackage.json - Run
index.jsandindex_dynamic.js. This time they should work.
- Revert back to the original
git reset --hard git clean -f - Rename
index_dynamic.mjstoindex_dynamic.js - Edit
index_dynamic.jsto use the alternative code.- Comment out the top code
- Uncomment the bottom code
- Run
index_dynamic.js
It should work.node index_dyanmic.js
Using an .mjs extension or adding "type": "module" is required, except if you use dynamic import within an async function.