solve cannot use import statement outside module

How to solve cannot use import statement outside module?

In this tutorial, you will learn how to solve the JavaScript “Uncaught SyntaxError: Cannot use import statement outside a module“.

Cannot use import statement outside a module error.

1. Add type=”module” to the <script> tag

<!DOCTYPE html>
<html>
<head>
  <title>Document</title>
</head>
<body>

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

2. How to use ES6 import statement in Node JS

You have to add "type": "module" in the package.json file to use the es6 import statement in Node JS to import bindings that are exported by another module.

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.1"
  }
}
import express from 'express';

const app = express();

app.get('/', (req, res) => {
    res.send('Hello World!');
})

app.listen(3000, () => console.log('App is running on port 3000'));
PS C:\Users\user\Desktop\node\test> nodemon index
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json  
[nodemon] starting `node index index.js`    
App is running on port 3000
localhost:3000