JavaScript Project
Introduction
This document provides information on some advanced functionality for the use of JavaScript files for Cloud Code.
JavaScript projects for Cloud Code work by turning the Unity project into a NodeJS project. That is used as a bridge and allows us to control the editor that is being used for JavaScript.
NodeJS
In order to support more tooling for developers, we require devs to install NodeJS. This will allow support for AutoComplete and other expected features of a dev environment.
Navigate to Preferences > Cloud Code > Javascript development environment
to validate that your NodeJS and NPM paths are properly set. You can verify that everything is working correctly by clicking the Initialize JS project
button. Read more on how NodeJS works under the Structure section.
Structure
.
├── Assets
│ └── CloudCode
│ └── cloud_script.js
├── node_modules
├── package.json
└── package-lock.json
The root of the structure sits at the root of the Unity Project.
package.json
stores the project configuration. This is used by JS editors and NPM. It operates similar to how CSProj is used by C# to define info for the editor. Note that these package.json
files used within the JavaScript Project system are not Unity packages. They are NPM Packages. It is a coincidence that Unity and NodeJS use the same package management system under the hood.
package-lock.json
is generated by npm and used for dependency resolution. It is recommended to keep this file in source control so that dependencies will always be resolved the same way.
AutoComplete
The majority of autocomplete for JS is handled by the typings project. Any JavaScript file can be augmented using a .d.ts
files to define the typed API. Most public JS libraries either include their own .d.ts
files or have some defined within typings.
In order for an editor to enable autocomplete for a dependency, it needs to be able to locate the type definitions for the dependency. It does this by looking in node_modules
. So in order to enable autocomplete you need to use the package.json
to install the correct files to node_modules
.
Bundling
Authoring JS scripts from the editor supports bundling if you decide to opt in. JS scripts may refer to other local scripts or external modules when using the require
or import
keywords.
The bundling process will use your script as input and send the bundled result to the Unity Dashboard when deploying from the editor.
Your local files will not be modified by this process, but the result will be visible on the dashboard.
Activating JS Bundling
JS Bundling is opt-in and requires the correct definition in each script for which you want bundling to be done.
To opt-in a script for bundling, simply export the bundling
value.
The module.exports
property must have been assigned before setting the parameters.
By default, the script will not be bundled.
lib.js
export const helloWorld = "Hello world!";
scriptToBundle.js
const lib = require("./lib.js");
module.exports = async ({ params, context, logger }) => {
return {
"value": lib.helloWorld
};
};
module.exports.bundling = true;
ES modules
The addition of bundling allows the use of ES Modules when authoring JS scripts from the editor. If you plan on using ES Modules to write your scripts, we recommend this signature to make the bundler result as lean as possible.
lib.js
export const someNumber = 42;
cloudCodeScript.js
import { someNumber } from './lib.js'
function handler(params, context, logger) {
/*your Cloud Code function logic here*/
return {
'value': someNumber, /*example use of the someNumber from the lib.js script*/
};
}
handler.bundling = true
handler.params = {
/*your params here*/
};
export default handler;
External Tools
External tools can be added by running the appropriate npm install ...
command from within the JS project. The tools can then be setup normally following the official tool guidelines.
ESLint
- Run
npm i -D eslint
. This will add it to the project dependencies. - Create an
.eslint.json
file at the project root containing:json { "env": { "commonjs": true, "es2021": true }, "extends": "eslint:recommended", "parserOptions": { "ecmaVersion": 13 }, "rules": { } }
- Configure your IDE to run eslint. This is automatic for VSCode but may need additional settings depending on the IDE.
- Eslint should now be configured and working
To test that eslint is working, add some code that is valid but breaks the eslint:recommended
ruleset. For example if (something == -0)
should now show a eslint warning in your IDE.
Jest
Jest is a framework for JavaScript testing. This is one example of how you can create unit tests for your cloud code scripts.
Official website: https://jestjs.io/
Setup
- Run
npm install --save-dev jest
. This will install the jest package. - Configure jest to run with
.es10
scripts.- Add this code snippet to your
package.json
- The
moduleFileExtensions
entry will makejs
andes10
files valid for testing. - The
testMatch
entry will make files ending in.test.es10
valid as test files.
- Add this code snippet to your
"jest": {
"moduleFileExtensions": ["es10", "js"],
"testMatch": ["**/*.test.es10"]
}
Example
Here's a simple example for JS unit testing. We are returning an object and want to make sure the result in the test script is the same. More advanced options are available with mocking.
The script to be tested
Cloud code expects this signature.
module.exports = async ({ params, context, logger }) => {
return {value: "1"};
};
The test script
const test = require("./jest_01.es10")
it("test",async () =>{
expect(await test({})).toMatchObject({value:"1"});
});
Running your tests
Your tests can be run in command line with the following command npm run test