Expose Node.js modules installed from npm to ActionScript
By creating type definitions with special metadata, developers can use Node.js modules from ActionScript code.
Let's try to use the boxen module from npm in ActionScript.
Create a file named boxen.as and add the following code:
package { /** * @externs */ [JSModule(name="boxen")] public function boxen(message:String, options:Object = null):void {} }
This file will tell the Apache Royale compiler how to access the “boxen” module in the generated JavaScript. Let's look in more detail at each part of this file.
All type definitions must include the @externs
asdoc tag.
/** * @externs */
Additionally, type definitions for Node.js modules must include [JSModule]
metadata.
[JSModule(name="boxen")]
Set the name
field inside [JSModule]
to the string that should be passed to a require()
call in JavaScript to load the module.
The default export of a module should either be a class, a function, or a variable. In this case, the default export of the “boxen” module is a function.
public function boxen(message:String, options:Object = null):void {}
The name of the default export should be derived from the name of the module. In this case, the name of the module and the name of the function
are both boxen
.
If the module name contains dashes, the symbol name should be converted to camel case. For example,
[JSModule(name="my-example-module")]
would require the symbol to be namedmyExampleModule
.
Create a file named MyScript.as, and add the following content:
package { public class MyScript { public function MyScript() { boxen("I loaded a module!"); } } }
Using Apache Royale's asnodec compiler, compile our project into JavaScript that can be run with Node.js:
asnodec MyScript.as
Use the following command to run the compiled project:
node bin/js-release/index.js
The following output will appear in the console:
┌────────────────────────┐ │ │ │ I loaded a module! │ │ │ └────────────────────────┘