search
HomeWeb Front-endJS TutorialDesigning a JavaScript plug-in system is extremely important

Designing a JavaScript plug-in system is extremely important

[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 build a plugin system

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.

The smallest plugin system in the world

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:

  1. Code to be executed
  2. Metadata (e.g. name, description, version number, dependencies, etc.)

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.

Better plug-in architecture

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:

  • It simplifies the API.
  • It makes testing easier (for BetaCalc and the plugin itself).
  • It reduces the dependencies of our system and makes it more loosely coupled together.

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.

What else can we do?

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?

Your plug-in system

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.

Summary

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!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool