How to fix the Node JS “SyntaxError: Unexpected token import” when using JavaScript modules

In order for node to export modules you have to assign each function, object or variable, that requires to be exported, as properties of the modules.exports object.

 

Exporting

In this example the module file is robot.js.  Each function, object or variable we would like to make available to other files we make them properties of the export object.

robot.js (module file)

exports.sayHello=

(msg) => console.log('Hello peeps!')


exports.hello = "Hello!"


exports.greetings=

  { english : "Hello!",

    french : "Bonjour!",

    spanish: "Ola!"

  }

 

Importing 

Node does not support the import statement, therefore the old require function needs to be used when importing.

Here we import robot.js (note: .js can optionally be left out in the require function) and assign it to an object that we can name anything.  We name it robot.  Our robot object now holds our exported modules from robot.js

We can use it as follows…

app.js (main file)

const robot = require('./robot')


robot.sayHello()

console.log(robot.hello)

console.log(robot.greetings.french)

Remember to use the object name that you chose on the first line when using your module variable, function or object.

Note: Browsers do not support the require statement.  Therefore you cannot use the require import module function with browsers without using a transpiler such as Babel or a bundler such as Browserify.

Uncaught ReferenceError - require is not defined in Opera Web browser v51

Require module import function in JavaScript is not supported in Web Browsers

Leave a Reply