Fix – Cannot use import statement outside module

Cannot use import statement outside a module node: When we use the ES6 Modules syntax in a script that wasn’t loaded as a module, we get the “SyntaxError: Cannot use import statement outside a module” error. Set the type property to the module when loading a script or in your package to fix the error. For Node apps, package.json is used.

Cannot use import statement outside module(Fix)

Cannot use import statement outside a module javascript: Below are some of the fixes for Cannot use import statement outside module error:

Fix #1: Adding type=”module” in index.html(main Page)

Nodejs cannot use import statement outside a module: Set the type attribute to the module when loading the script in your HTML code to fix the problem.

Solution:

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- adding type as module in the script   -->
    <script type="module" src="index.js"></script>
</body>
</html>

In our JavaScript code, we can now use the syntax of the ES6 module.
It’s important to remember that any JavaScript files that use the syntax of the ES6 module must have the type attribute set to the module.

index.js

// importing from the loadash module
import _ from 'lodash';

// printing the unique values in the array by passing the array as an argument to the uniq() function
console.log(_.uniq([4,2,5,8,4,4]));

Output:

[4,2,5,8]

Fix #2: Adding type=module in Node.js

Cannot use import statement outside a module: When working with Node.js, you must set the type property in your package to the module. To use ES6 module imports, you’ll need a package.json file.

If your project doesn’t have a package.json file, create one with the npm init -y command in the project’s root directory.

npm init --y

package.json:

{
  "name": "btechgeeks",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type":"module"
}

In your Node.js application, you can now use the syntax of the ES6 module.

index.js

// importing from the loadash module
import _ from 'lodash';

// printing the unique values in the array by passing the array as an argument to the uniq() function
console.log(_.uniq([4,2,5,8,4,4]));

Output:

[4,2,5,8]

Importing from another user created module:

You must add the .js extension when importing local files with the type attribute set to module.

btechgeeks.js

function mySum(a, b) {
  return a + b; 
}
export default mySum;

index.js

// importing mysum function from btechgeeks.js module using the import keyword
import mysum from './btechgeeks.js';

// passing some random two values to the mysum() function of the btechgeeks module and printing the summ
console.log('sum is:',mysum(11,17));

Output:

sum is: 28

If we remove the .js from the import then:

index.js

// importing mysum function from btechgeeks.js module using the import keyword
import mysum from './btechgeeks';

// passing some random two values to the mysum() function of the btechgeeks module and printing the summ
console.log('sum is:',mysum(11,17));

Output:

node:internal/process/esm_loader:94
internalBinding('errors').triggerUncaughtException(
^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\cirus\Desktop\LinkedIn\btechgeeks' imported from C:\Users\cirus\Desktop\LinkedIn\index.js
Did you mean to import ../btechgeeks.js?
at new NodeError (node:internal/errors:371:5)
at finalizeResolution (node:internal/modules/esm/resolve:418:11)
at moduleResolve (node:internal/modules/esm/resolve:983:10)
at defaultResolve (node:internal/modules/esm/resolve:1080:11)
at ESMLoader.resolve (node:internal/modules/esm/loader:530:30)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:251:18)
at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:79:40)
at link (node:internal/modules/esm/module_job:78:36) {
code: 'ERR_MODULE_NOT_FOUND'
}

Fix #3: Using require()

If none of the above options worked, try substituting require() for the import/export syntax.

// Using the require() function to import some random package
const myRandomFunction = require('some-package');

// For named exports enclosed the function in {}
const {someRandomFunction} = require('some-package')

Note:

If you try to run your source files that use ES6 module import/export syntax instead of your compiled files from your build directory, you’ll get the “Cannot use import statement outside module” error. Make sure that your compiled files are only executed from the build/dist directory.