The Simplest Plugin

Quick Start

Boilerplate

Start with a basic TypeScript node package boilerplate. If you've never done that before, we recommend using aqu:

If you don't have aqu installed, you can install it globally with npm i -g aqu.

pnpm dlx aqu create simple-plugin

? Pick package manager: pnpm
? Specify package description: ()
? Package author:
? Git repository (only for package.json information):
? Pick license: MIT
? Pick template: typescript

cd simple-plugin

If you'd like to publish your plugin to npm for others to use, please see our documentation on publishing plugins

Install @learncard/core

Using your preferred package manager, install @learncard/core

pnpm i @learncard/core

Create the Types

To ease plugin development, it's best to start by defining the interface for your plugin. This can be done quite easily using the Plugin type:

src/types.ts
import { Plugin } from '@learncard/core';

export type MyPluginMethods = {
    getFavoriteNumber: () => number;
};

export type MyPluginType = Plugin<'MyPluginName', any, MyPluginMethods>;

The preceding file defines a plugin named MyPluginName that exposes one method: getFavoriteNumber

Create the Plugin

src/index.ts
import { MyPluginType } from './types';

export const MyPlugin: MyPluginType = {
    name: 'MyPluginName',
    methods: { getFavoriteNumber: () => 4 },
};

Create a Test for Your Plugin

It's important to write tests for your plugins, so others can rely on them 👍

pnpm i --save-dev jest @types/jest

Then, write your test:

test/index.test.ts
import { initLearnCard } from '@learncard/core';
import { MyPlugin } from '../src/index';

describe('MyPlugin', () => {
	it('should return my favorite number', async () => {
		const learnCard = await initLearnCard();
		const learnCardWithMyPlugin = await learnCard.addPlugin(MyPlugin);

		const favoriteNumber = learnCardWithMyPlugin.invoke.getFavoriteNumber();
		
		expect(favoriteNumber).toBe(4);
	});
});

If all looks good, you should be able to pnpm test and successfully pass the test:

That's it—you've got a simple plugin! 🎉

Now you can add it to a LearnCard object:

const learnCard = await initLearnCard();
const learnCardWithMyPlugin = await learnCard.addPlugin(MyPlugin);

console.log(learnCard.invoke.getFavoriteNumber()); // 4

For more info on adding plugins to a LearnCard:

pageAdding Plugins

For more info on constructing the LearnCard object:

pageConstruction

To see how to publish this plugin to NPM for others to use:

pagePublishing a Plugin to NPM

Last updated