Carane ndandani Node JS “SyntaxError: ngimpor koin sing ora dikarepke” nalika nggunakake modul JavaScript

Supaya node modul kaca sampeyan kudu nemtokake saben fungsi, obyek utawa global, sing mbutuhake kanggo diekspor, minangka sifat modules.exports obyek.

 

Ngèkspor

In this example the module file is robot.js. Each function, obyek utawa global kita kaya kanggo nggawe kasedhiya kanggo file liyane kita nggawe wong sifat obyek kaca.

robot.js (file modul)

exports.sayHello =

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


exports.hello = "Halo!"


exports.greetings =

  { english : "Halo!",

    french : "Hello!",

    spanish: "Ola!"

  }

 

Importing

Node ora ndhukung statement ngimpor, Mulane lawas sing fungsi perlu kanggo digunakake nalika ngimpor.

Kene kita ngimpor robot.js (cathetan: .JS bisa optionally kiwa metu ing fungsi sing) 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

Kita bisa nggunakake minangka nderek…

app.js (file utama)

= Robot const mbutuhake('./robot')


robot.sayHello()

console.log(robot.hello)

console.log(robot.greetings.french)

Elinga nggunakake jeneng obyek sing milih ing baris pisanan nalika nggunakake global modul Panjenengan, fungsi utawa obyek.

Wigati: 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.

ReferenceError Uncaught - mbutuhake ora ditetepake ing Opera Browser v51

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

Ninggalake a Reply