- Create a temporary directory and
cd
into 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
.mjs
files to.js
- Edit index.js and index.mjs to update the name of the imported file to
"./hello.js"
- Attempt to run
index.js
andindex_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.js
andindex_dynamic.js
. This time they should work.
- Revert back to the original
git reset --hard git clean -f
- Rename
index_dynamic.mjs
toindex_dynamic.js
- Edit
index_dynamic.js
to 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.