ES6 Modules not working in nodejs?

I use nodejs to run js files in command prompt.
When I ran import.js by typing

node import.js

in command prompt it says "
(node:2952) 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)" and "
import { uppercaseString, lowercaseString } from ‘./export.js’;
^^^^^^

SyntaxError: Cannot use import statement outside a module" and as you can see I use console.log() in import.js so the output should be

HELLO world!

I also tried it in a html file too and nothing shows up.

Your code so far


// export.js
// Use export to Share a Code Block
export const uppercaseString = (string) => {
    return string.toUpperCase();
  }
  
export const lowercaseString = (string) => {
    return string.toLowerCase()
  }

//import.js
//Reuse JavaScript Code Using import
import { uppercaseString, lowercaseString } from './export.js';

console.log(uppercaseString("hello"));      
console.log(lowercaseString("WORLD!"));      

//test.html
<html>
  <body>
    <script type="module" src="import.js"></script>
  </body>
</html>

Challenge: Reuse JavaScript Code Using import

Link to the challenge:

Hello, The solution is provided at the following link:

Solved - SyntaxError Cannot use import statement outside a module | N Kaushik

Hope this helps. All you have to really do is add "type": "module" to your package.json file.

Hey there,

ESM (import) works with NodeJS 12.

For older versions, you use CommonJS syntax (require).

You can read more about it in the NodeJS docs.

Your example works for me:

In the console of codesandbox you can see the console logs.

Thanks… I found the package.json file under C:\Program Files\nodejs and tried to add

“type”: “module”

and it said I don’t have access or something like that so I copied all the code in package.json file and created a new file called package.json with code added

“type”: “module”

under the folder I put my js files (export.js, import.js …) and it worked. I’m a bit confused I mean there’s two package.json files … however it worked the code worked.
THANKS!

Thanks for the help! It worked now. :grinning:

It’s a good idea to think in projects.
One project lives in one project folder.
So this means that each project has its own package.json in its own project folder.

Okay I get it now, Thanks :smiley:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.