[Related learning recommendations: javascript video tutorial]
WordPress has plug-ins, jQuery has plug-ins, and the same goes for Gatsby, Eleventy, and Vue.
Plugins are a common feature of libraries and frameworks, and for a good reason: they allow developers to add functionality in a safe, extensible way. This makes the core project more valuable and builds a community - all without adding additional maintenance burden. Very good!
So how to build a plug-in system? Let's build our own plugin in JavaScript to answer this question.
Let’s start with a sample project called BetaCalc. BetaCalc aims to be a minimalist JavaScript calculator to which other developers can add "buttons". Here is some basic getting started code:
// 计算器const betaCalc = { currentValue: 0, setValue(newValue) { this.currentValue = newValue; console.log(this.currentValue); }, plus(addend) { this.setValue(this.currentValue + addend); }, minus(subtrahend) { this.setValue(this.currentValue - subtrahend); } };// 使用计算器betaCalc.setValue(3); // => 3betaCalc.plus(3); // => 6betaCalc.minus(2); // => 4复制代码
We define a calculator as an objective thing to keep things simple, a calculator works by console.log
printing the results.
The current functionality is indeed very limited. We have a setValue
method that accepts a number and displays it on the "screen". We also have addition (plus
) and subtraction (minus
) methods that will perform an operation on the currently displayed value.
Now it’s time to add more features. First create a plugin system.
We will start by creating a registration (register
) method that other developers can use to register plugins with BetaCalc. The job of this method is simple: get the external plugin, get its exec
function, and attach it to our calculator as a new method:
// 计算器const betaCalc = { // ...其他计算器代码在这里 register(plugin) { const { name, exec } = plugin; this[name] = exec; } };复制代码
Here is an example plugin for Our calculator provides a "squared(squared
)" button:
// 定义插件const squaredPlugin = { name: 'squared', exec: function() { this.setValue(this.currentValue * this.currentValue) } };// 注册插件betaCalc.register(squaredPlugin);复制代码
In many plug-in systems, the plug-in is usually divided into two parts:
In our plugin, the exec
function contains Our code, name
is our metadata. Once the plugin is registered, the exec
function will be attached directly to our betaCalc
object as a method, giving access to BetaCalc's this
.
Now, BetaCalc has a new "square" button that can be called directly:
betaCalc.setValue(3); // => 3betaCalc.plus(2); // => 5betaCalc.squared(); // => 25betaCalc.squared(); // => 625复制代码
This system has many advantages. The plugin is a simple object literal that can be passed to our functions. This means that plugins can be downloaded via npm and imported as ES6 modules. Ease of distribution is super important!
But our system has some flaws.
By giving plugins this
access to BetaCalc, they can have read/write access to all of BetaCalc's code. While this is useful for getting and setting currentValue
, it can also be dangerous. If a plugin were to redefine internal functions (such as setValue
), it might produce unexpected results for BetaCalc and other plugins. This violates the open-closed principle, which states that a software entity should be open to extension, but closed to modification.
Also, the "squared" function works by producing side effects. This is not uncommon in JavaScript, but it doesn't feel good - especially when other plugins may be in the same internal state. A more practical approach would go a long way toward making our systems more secure and predictable.
Let’s take a look at a better plug-in architecture. The next example changes both the calculator and its plugin API:
// 计算器const betaCalc = { currentValue: 0, setValue(value) { this.currentValue = value; console.log(this.currentValue); }, core: { 'plus': (currentVal, addend) => currentVal + addend, 'minus': (currentVal, subtrahend) => currentVal - subtrahend }, plugins: {}, press(buttonName, newVal) { const func = this.core[buttonName] || this.plugins[buttonName]; this.setValue(func(this.currentValue, newVal)); }, register(plugin) { const { name, exec } = plugin; this.plugins[name] = exec; } }; // 我们得插件,平方插件const squaredPlugin = { name: 'squared', exec: function(currentValue) { return currentValue * currentValue; } }; betaCalc.register(squaredPlugin);// 使用计算器betaCalc.setValue(3); // => 3betaCalc.press('plus', 2); // => 5betaCalc.press('squared'); // => 25betaCalc.press('squared'); // => 625复制代码
We've made some notable changes here.
First, we separate the plugin from the "core" calculator methods (such as plus and minus) by putting them into their own plugin objects. Storing our plugins in plugins
objects makes our system more secure. Now, plugins accessing this plugin will not see the BetaCalc properties, but only the properties of betaCalc.plugins
.
Second, we implemented a press
method that looks up the button's function by name and then calls it. Now, when we call the plugin's exec
function, we pass the current calculator value (currentValue
) to the function and expect it to return the new calculator value.
Essentially, this new press
method converts all of our calculator buttons into pure functions. They take a value, perform an operation, and return the result. This has many benefits:
This new architecture is more limited than the first example, but works well. We basically put guardrails in place for plugin authors, limiting them to only making the changes we want them to make.
Actually, it might be too strict! Right now, our calculator plugin can only operate on currentValue
. If a plugin author wants to add advanced functionality (such as a "remember" button or a way to track history), there's not much they can do.
Maybe this is good. The power you give plugin authors is a delicate balance. Giving them too much power may affect the stability of your project. But give them too little power and it will be difficult for them to solve their own problems - in which case you might as well not plug in.
We still have a lot of work to do to improve our system.
We can add error handling to notify the plugin author if he forgets to define a name or return value. It's good to think like a QA developer and imagine how our systems might break so that we can proactively handle these situations.
We can expand the functional scope of the plug-in. Currently, a BetaCalc plugin can add a button. But what if it could also register callbacks for certain lifecycle events (such as when the calculator is about to display a value)? Or, what if there was a dedicated place to store a piece of state across multiple interactions? Will this open up some new use cases?
We can also expand the function of plug-in registration. What if a plugin could be registered with some initial setup? Does this make the plugin more flexible? What if a plugin author wanted to register a whole set of buttons instead of a single button - like "BetaCalc Stats Package"? What changes need to be made to support this?
BetaCalc and its plug-in system are very simple. If your project is larger, you'll want to explore some other plugin architectures.
A good starting point is to look at existing projects for examples of successful plugin systems. For JavaScript, this might mean jQuery, Gatsby, D3, CKEditor or others. You may also want to familiarize yourself with various JavaScript design patterns, each of which provides different interfaces and degrees of coupling, which gives you many good plugin architecture choices. Understanding these options can help you better balance the needs of everyone who uses your project.
In addition to the patterns themselves, there are many good software development principles you can draw on to make such decisions. I've already mentioned a few approaches (such as the open-closed principle and loose coupling), but some other related ones include the Law of Demeter and dependency injection.
I know this sounds like a lot, but you have to do your research. There's nothing more painful than having everyone rewrite their plugin because you need to change the plugin architecture. This is a quick way to lose trust and make people lose confidence in their future contributions.
Writing a good plug-in architecture from scratch is difficult! You have to balance many considerations to build a system that meets everyone's needs. Is it simple enough? Can the function be powerful? Will it work long term?
But it is worth it, having a good plug-in system helps everyone, and developers can solve their problems freely. There are a large number of optional features from which end users can choose. You can build an ecosystem and community around your project. It's a win-win situation.
The above is the detailed content of Designing a JavaScript plug-in system is extremely important. For more information, please follow other related articles on the PHP Chinese website!