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

Copy
import { parseData } from '../data-utils';
// Basic usage
PLASMIC.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 types
PLASMIC.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:

FieldRequired?Description
nameYesThe JavaScript name of the function.
namespaceNoA 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.
descriptionNoDocumentation for the registered function.
paramsNoAn array containing the list of parameters names the function takes. Optionally they can also be registered with the expected param types.
returnValueNoAn object with the return value information. It can include the return value type and description.
typescriptDeclarationNoTypescript function declaration. If specified, it ignores the types provided by params and returnValue.
importPathYes if using codegenThe 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).
isDefaultExportNoIf 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.