3

There is something I fail to understand with ES6 modules in the context of node.js.

Let's say I have this simple node app. It is based on an iisnode example but I added an import at the top.

hello.js:

import mod1 from './module1'; var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end(mod1.data); }).listen(process.env.PORT); 

This will result in SyntaxError: Cannot use import statement outside a module

However if I rename hello.js to hello.mjs I get the following error: Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Program Files\iisnode\www\hellomodules\hello.mjs

Seems like a catch to me, what is the way out?

(iisnode version is 0.2.26, node version is v13.8.0)

3
  • github.com/nodejs/node/issues/17063#issuecomment-344782748 Commented Feb 12, 2020 at 15:06
  • @Hogan, I do not see how that applies in my case. The issue you linked to was a case of misleadingly worded error message which was fixed way back then. Furthermore, std/esm or esm should not be needed at all since nodejs 12. Commented Feb 12, 2020 at 15:57
  • ok -- it is the same error message you posted. Commented Feb 12, 2020 at 16:13

1 Answer 1

3

Solving this issue:

  1. If the file format is .js, or if the Node version < 13, add "type": "module" in package.json
  2. To allow debug, add "runtimeArgs": ["--experimental-modules"] in .vscode/launch.json
  3. Always use the flag --experimental-modules to run: node --experimental-modules hello.mjs

In the newer Node versions it isn't necessary to take these steps

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.