Registering custom functions
If you have JavaScript functions in your codebase that you would like to use in Plasmic Studio, you can register them from your custom host.
Once registered, the functions can be accessed in the code editor with the $$
prefix, like: $$.myFunc()
or $$.funcNamespace.otherFunc()
.
Function registration
import { parseData } from '../data-utils';// Basic usagePLASMIC.registerFunction(parseData, {name: 'parseData'});import { isEven } from 'some-utility-package';// Register with param and return value documentation (types, description)PLASMIC.registerFunction(isEven, {name: 'isEven',params: [{name: 'x',type: 'number',description: 'The value to test its evenness'}],returnValue: {type: 'boolean',description: 'Whether `x` is an even number'}});import { filterData } from '../data-utils';// Add custom typescript declaration for complex typesPLASMIC.registerFunction(filterData, {name: 'filterData',description: `Filters the data.@param data The data to filter@param opts The options for filtering`,typescriptDeclaration: `<T>(data: T[],opts?: {/** Maximum number of elements to return */limit?: number;/** Options for sorting the data */sort?: {field: string;order: "asc" | "desc";}}): T[]`});
registerFunction
API
registerFunction()
is called with the function to be registered, along with an object with these fields:
Field | Required? | Description |
---|---|---|
name | Yes | The JavaScript name of the function. |
namespace | No | A namespace for organizing groups of functions. It’s also used to handle function name collisions. If a function has is registered with a namespace, it’ll be used whenever accessing the function. |
description | No | Documentation for the registered function. |
params | No | An array containing the list of parameters names the function takes. Optionally they can also be registered with the expected param types. |
returnValue | No | An object with the return value information. It can include the return value type and description . |
typescriptDeclaration | No | Typescript function declaration. If specified, it ignores the types provided by params and returnValue . |
importPath | Yes if using codegen | The path to be used when importing this function in the generated code. It can be the name of the npm package that contains the component (like lodash ), or the path to the file in the project (relative to the root directory, where the plasmic.json file is located). |
isDefaultExport | No | If true, then this function is the default export from importPath . |
Was this page helpful?
Have feedback on this page? Let us know on our forum.