Some common code can be extracted into a separate JS file as a module. A module can only expose its API through module.exports
or exports
.
Note:
exports is a reference to module.exports, so changing the reference of exports within the module can cause unexpected errors. Therefore, it is recommended to use module.exports to expose module APIs unless you clearly understand the relationship between the two.
function sayHello(name) {
console.log(Hello $
{
name
}
!
)
}
function sayGoodbye(name) {
console.log(Goodbye $
{
name
}
!
)
}
module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye
File scope
Variables and functions declared in a JavaScript file are only effective within that file. Different files can declare variables and functions with the same name without affecting each other.
Global object
Similar to the window
object in browsers and the global object in NodeJS , mini games have a global object called GameGlobal
. You can use GameGlobal
to pass variables between multiple files.
GameGlobal.globalData = 1
console.log(GameGlobal.globalData)