Scripting in AR Studio might be difficult sometimes, having all the code in one file is not ideal, hard for collaboration and quite likely to be messy. Here is a simple guide to have a super simple web-like JavaScript build that allows you to have the all files and the structure you want.
Get the sample project from this page (Mug.zip), unzip it and go to the Mug Finished Effect folder. Or, use your own project.
Create a folder js-build inside Mug Finished Effect for the JavaScript build.
Start a new npm project in ./js-build with default options, and add Webpack and Babel. (you can use yarn or npm)
npm init -ynpm install -D @babel/core @babel/preset-env babel-loader webpack webpack-cliAdd a watch script to package.json, it should look something like this:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch --mode production"
}Create a webpack.config.js configutation file.
A few important notes:
- Entry file
./src/index.js, this is going to be your main file for all your code for AR Studio, now you can create the structure you want, import diferent files or even integrate something like redux. outputis the path to the script file AR Studio uses.- In order to tell webpack which modules are AR Studio modules (and not Node modules) you need to add the AR Studio modules you use as
externals, otherwise webpack will complain it can't find those modules innode_modules. Thecommonjstells webpack it should keep theimport/requireon the bundle file, as AR Studio needs that.
const path = require("path");
module.exports = {
entry: { main: "./src/index.js" },
output: {
path: path.resolve(__dirname, "../scripts/"),
filename: "script.js"
},
externals: {
Scene: "commonjs Scene",
Reactive: "commonjs Reactive",
TouchGestures: "commonjs TouchGestures",
Diagnostics: "commonjs Diagnostics"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
}
]
}
};Add a .babelrc with the env preset:
{
presets: ["@babel/env"]
}npm run watchEverytime you save a file it's going to update the script AR Studio uses
Thanks for this great guide! I'm getting an error when running
webpack.Module not found: Error: Can't resolve 'Time' in ../physar/srcMy project is organized this way:
Project >
-- scripts >
---- script.js
---- babel.config.json
-- js-build >
---- node_modules >
-------- physar >
------------ src >
---------------- index.js
-------- cannon >
The
Timemodule is called inscript.jswithimport Physar from 'physar'andconst Time = require('Time').Timeis called inindex.jsat line 74 asI'm also getting a javaScript error inside the Spark AR console:
JavaScript error: Cannot find module 'physar'
Any advice would be much appreciated!