How to write a custom jsep plugin
masterA plugin is an object containing a name and an init function. The init function receives the jsep instance and is used to register hooks.
Plugin Structure
const plugin = {
name: 'my-plugin',
init(jsep) {
// Use jsep methods or hooks here
},
};Using Hooks
Hooks are used to modify parsing behavior. They are called with a single argument (often an object containing the node or env) and return void. The this context of a hook provides access to internal parsing methods like gobbleSpaces, gobbleExpression, etc.
Available Hook Types
before-all: Called before starting all expression parsing.after-all: Called after parsing is complete. Can read/writearg.node.gobble-expression: Called before attempting to parse an expression. Can setarg.node.after-expression: Called after parsing an expression. Can read/writearg.node.gobble-token: Called before attempting to parse a token. Can setarg.node.after-token: Called after parsing a token. Can read/writearg.node.gobble-spaces: Called when gobbling whitespace.
const plugin = {
name: 'the plugin',
init(jsep) {
jsep.addIdentifierChar('@');
jsep.hooks.add('gobble-expression', function myPlugin(env) {
if (this.char === '@') {
this.index += 1;
env.node = {
type: 'MyCustom@Detector',
};
}
});
},
};