​
See Code Editors for more information on composing code in WayScript.
WayScript's JS editor lets you reference Variables that exist in your program. To do this, you can reference them through the variables dictionary.
As an example, let's create a variable called "Location" and set a value of "Brooklyn, NY"
You can reference the Location variable in your JavaScript with this code:
location = variables[ "Location" ];​// Or, as a JS objectlocation = variables.Location;
More abstractly, you reference any variable with the format:
const my_var = variables[ "<var_name>" ];
You can also output data from your JS code and turn these into variables that can be used by other Modules in your program.
You can do this with the variables dictionary in the following format:
variables[ "<Var Name>" ] = variable;​// exampleconst currentTime = new Date();variables[ "Date" ] = currentTime.toISOString();
You can output the raw JavaScript code from the code editor by enabling the "JavaScript Code" output. This is useful when building a website using WayScript and inserting JavaScript into HTML.
If you are building JS for a webpage, you might only want to output the code as text and not run it at all. This can be achieved by disabling the "Run Code" setting.
While working on your code, you can press the "Run Code" button inside the module to run the JavaScript and see updated results.
If you would like to use an npm module in your code, you can declare those dependencies in the "Requirements.txt" file.
Declare these dependencies on separate lines, using the format you would for an npm-install command.
You can then consume these packages in your code:
const wayscript = require( 'wayscript' );​wayscript.apiKey = 'YOUR_API_KEY';​let programId = 1234;wayscript.runProgram( programId );
You can import code from the other JavaScript files in your File Browser. For example, suppose you have a file called foo.js
, which has an exported function bar
.
You can import and use the bar
method in scratch.js
by using a relative import:
const foo = require('./foo');