-1

I started learning node.js recently. I was using vs code and going through url module and got this error.

PS G:\node js> node "g:\node js\urlmodule.js"
(node:1964) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
g:\node js\urlmodule.js:1
import url from 'url';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

the code was-

import url from 'url';

const myURL = new URL('https://example.org');
myURL.pathname = '/a/b/c';
myURL.search = '?d=e';
myURL.hash = '#fgh';

console.log(myURL)
console.log(myURL.href)
  • 3
    Does this answer your question? ["Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6](https://stackoverflow.com/questions/58211880/uncaught-syntaxerror-cannot-use-import-statement-outside-a-module-when-import) – Abir Taheer May 24 '22 at 15:38

3 Answers3

0

Looks like you don't have setup to support es6 imports. Try using commonJS imports:

Eg: const url = require('url'); If you wanna use es6 import please follow this.

Archit Gargi
  • 634
  • 1
  • 8
  • 24
  • the other way around is to change your file name from .js to .mjs or in your package.json file add property "type": "module", – U.Aasd May 24 '22 at 17:24
0

You have to include "type": "module" in package.json file.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 25 '22 at 07:09
0

Try to set:

"type": "module"

In your package.json file.