SyntaxError: Cannot use import statement outside a module

One way to solve this error

nick3499
1 min readSep 14, 2020

package.json

{
"type": "module"
}

Through the inclusion of a package.json file, a JavaScript module, which contains its own export statement, can be imported into a JavaScript application. Place the package.json file in the root directory of the application, e.g. where the application’s script.js file is stored.

So, for this example, the root directory of the application contains the following:

  • index.js
  • modules/
  • package.json

And the modules/ directory contains:

  • Animals.json

index.js

#!/usr/bin/env nodeimport { Animal } from './modules/Animals.mjs';let dog = new Animal('dog');
console.log(dog.getType());

According to MDN web docs: import:

The static import statement is used to import read only live bindings which are exported by another module.

For this example, the import statement binds the Animal class from the Animals.mjs file to the application.

modules/Animals.mjs

Animals.mjs contains an export statement:

export class Animal {
constructor(type) {
this.type = type;
}
getType() {
return this.type;
}
}

According to MDN web docs: export:

The export statement is used when creating JavaScript modules to export live bindings to functions, objects, or primitive values from the module so they can be used by other programs with the import statement.

So, this example demonstrates how the import and export statements work together, along with the package.json file.

Run the Application

Using a Bash interactive shell in a terminal emulator, run index.js:

$ node index.js

The Bash shell should return:

dog

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet