SyntaxError: Cannot use import statement outside a module
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 theimport
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