A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.md 17KB

3 kuukautta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. title: Designing a JavaScript Plugin System
  2. url: https://css-tricks.com/designing-a-javascript-plugin-system/
  3. hash_url: d9c30865dde8c88394ba054836a18ae3
  4. archive_date: 2024-02-27
  5. og_image: https://css-tricks.com/wp-json/social-image-generator/v1/image/318994
  6. description: WordPress has plugins. jQuery has plugins. Gatsby, Eleventy, and Vue do, too.
  7. favicon: https://css-tricks.com/favicon.svg
  8. language: en_US
  9. <p>WordPress has <a href="https://wordpress.org/plugins/" rel="noopener">plugins</a>. jQuery has <a href="https://plugins.jquery.com" rel="noopener">plugins</a>. <a href="https://www.gatsbyjs.org/docs/plugins/" rel="noopener">Gatsby</a>, <a href="https://www.11ty.dev/docs/plugins/" rel="noopener">Eleventy</a>, and <a href="https://css-tricks.com/getting-started-with-vue-plugins/">Vue </a>do, too.</p>
  10. <p>Plugins are a common feature of libraries and frameworks, and for a good reason: they allow developers to add functionality, in a safe, scalable way. This makes the core project more valuable, and it builds a community — all without creating an additional maintenance burden. What a great deal!</p>
  11. <p>So how do you go about building a plugin system? Let’s answer that question by building one of our own, in JavaScript.</p>
  12. <span id="more-318994"></span>
  13. <p class="explanation">I’m using the word “plugin” but these things are sometimes called other names, like “extensions,” “add-ons,” or “modules.” Whatever you call them, the concept (and benefit) is the same.</p>
  14. <h3 class="wp-block-heading" id="lets-build-a-plugin-system"><a href="#aa-lets-build-a-plugin-system" aria-hidden="true" class="aal_anchor" id="aa-lets-build-a-plugin-system"><svg aria-hidden="true" class="aal_svg" version="1.1" viewbox="0 0 16 16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>Let’s build a plugin system</h3>
  15. <p>Let’s start with an example project called BetaCalc. The goal for BetaCalc is to be a minimalist JavaScript calculator that other developers can add “buttons” to. Here’s some basic code to get us started:</p>
  16. <pre rel="JavaScript" class="wp-block-csstricks-code-block language-javascript" data-line=""><code markup="tt">// The Calculator
  17. const betaCalc = {
  18.   currentValue: 0,
  19.   
  20.   setValue(newValue) {
  21.     this.currentValue = newValue;
  22.     console.log(this.currentValue);
  23.   },
  24.   
  25.   plus(addend) {
  26.     this.setValue(this.currentValue + addend);
  27.   },
  28.   
  29.   minus(subtrahend) {
  30.     this.setValue(this.currentValue - subtrahend);
  31.   }
  32. };
  33. // Using the calculator
  34. betaCalc.setValue(3); // =&gt; 3
  35. betaCalc.plus(3);     // =&gt; 6
  36. betaCalc.minus(2);    // =&gt; 4</code></pre>
  37. <p>We’re defining our calculator as an object-literal to keep things simple. The calculator works by printing its result via <code>console.log</code>.</p>
  38. <p>Functionality is really limited right now. We have a <code>setValue</code> method, which takes a number and displays it on the “screen.” We also have <code>plus</code> and <code>minus</code> methods, which will perform an operation on the currently displayed value.</p>
  39. <p>It’s time to add more functionality. Let’s start by creating a plugin system.</p>
  40. <h3 class="wp-block-heading" id="the-worlds-smallest-plugin-system"><a href="#aa-the-worlds-smallest-plugin-system" aria-hidden="true" class="aal_anchor" id="aa-the-worlds-smallest-plugin-system"><svg aria-hidden="true" class="aal_svg" version="1.1" viewbox="0 0 16 16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>The world’s smallest plugin system</h3>
  41. <p>We’ll start by creating a <code>register</code> method that other developers can use to register a plugin with BetaCalc. The job of this method is simple: take the external plugin, grab its <code>exec</code> function, and attach it to our calculator as a new method:</p>
  42. <pre rel="JavaScript" class="wp-block-csstricks-code-block language-javascript" data-line=""><code markup="tt">// The Calculator
  43. const betaCalc = {
  44.   // ...other calculator code up here
  45.   register(plugin) {
  46.     const { name, exec } = plugin;
  47.     this[name] = exec;
  48.   }
  49. };</code></pre>
  50. <p>And here’s an example plugin, which gives our calculator a “squared” button:</p>
  51. <pre rel="JavaScript" class="wp-block-csstricks-code-block language-javascript" data-line=""><code markup="tt">// Define the plugin
  52. const squaredPlugin = {
  53.   name: 'squared',
  54.   exec: function() {
  55.     this.setValue(this.currentValue * this.currentValue)
  56.   }
  57. };
  58. // Register the plugin
  59. betaCalc.register(squaredPlugin);</code></pre>
  60. <p>In many plugin systems, it’s common for plugins to have two parts:</p>
  61. <ol><li>Code to be executed</li><li>Metadata (like a name, description, version number, dependencies, etc.)</li></ol>
  62. <p>In our plugin, the <code>exec</code> function contains our code, and the <code>name</code> is our metadata. When the plugin is registered, the exec function is attached directly to our <code>betaCalc</code> object as a method, giving it access to BetaCalc’s <code>this</code>.</p>
  63. <p>So now, BetaCalc has a new “squared” button, which can be called directly:</p>
  64. <pre rel="JavaScript" class="wp-block-csstricks-code-block language-javascript" data-line=""><code markup="tt">betaCalc.setValue(3); // =&gt; 3
  65. betaCalc.plus(2);     // =&gt; 5
  66. betaCalc.squared();   // =&gt; 25
  67. betaCalc.squared();   // =&gt; 625</code></pre>
  68. <p>There’s a lot to like about this system. The plugin is a simple object-literal that can be passed into our function. This means that plugins can be downloaded via npm and imported as ES6 modules. Easy distribution is super important!</p>
  69. <p>But our system has a few flaws.</p>
  70. <p>By giving plugins access to BetaCalc’s <code>this</code>, they get read/write access to all of BetaCalc’s code. While this is useful for getting and setting the <code>currentValue</code>, it’s also dangerous. If a plugin was to redefine an internal function (like <code>setValue</code>), it could produce unexpected results for BetaCalc and other plugins. This violates <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle" rel="noopener">the open-closed principle</a>, which states that a software entity should be open for extension but closed for modification.</p>
  71. <p>Also, the “squared” function works by producing <a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)" rel="nofollow noopener">side effects</a>. That’s not uncommon in JavaScript, but it doesn’t feel great — especially when other plugins could be in there messing with the same internal state. A more <a href="https://en.wikipedia.org/wiki/Functional_programming" rel="nofollow noopener">functional</a> approach would go a long way toward making our system safer and more predictable.</p>
  72. <h3 class="wp-block-heading" id="a-better-plugin-architecture"><a href="#aa-a-better-plugin-architecture" aria-hidden="true" class="aal_anchor" id="aa-a-better-plugin-architecture"><svg aria-hidden="true" class="aal_svg" version="1.1" viewbox="0 0 16 16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>A better plugin architecture</h3>
  73. <p>Let’s take another pass at a better plugin architecture. This next example changes both the calculator and its plugin API:</p>
  74. <pre rel="JavaScript" class="wp-block-csstricks-code-block language-javascript" data-line=""><code markup="tt">// The Calculator
  75. const betaCalc = {
  76.   currentValue: 0,
  77.   
  78.   setValue(value) {
  79.     this.currentValue = value;
  80.     console.log(this.currentValue);
  81.   },
  82.  
  83.   core: {
  84.     'plus': (currentVal, addend) =&gt; currentVal + addend,
  85.     'minus': (currentVal, subtrahend) =&gt; currentVal - subtrahend
  86.   },
  87.   plugins: {},    
  88.   press(buttonName, newVal) {
  89.     const func = this.core[buttonName] || this.plugins[buttonName];
  90.     this.setValue(func(this.currentValue, newVal));
  91.   },
  92.   register(plugin) {
  93.     const { name, exec } = plugin;
  94.     this.plugins[name] = exec;
  95.   }
  96. };
  97.   
  98. // Our Plugin
  99. const squaredPlugin = { 
  100.   name: 'squared',
  101.   exec: function(currentValue) {
  102.     return currentValue * currentValue;
  103.   }
  104. };
  105. betaCalc.register(squaredPlugin);
  106. // Using the calculator
  107. betaCalc.setValue(3);      // =&gt; 3
  108. betaCalc.press('plus', 2); // =&gt; 5
  109. betaCalc.press('squared'); // =&gt; 25
  110. betaCalc.press('squared'); // =&gt; 625</code></pre>
  111. <p>We’ve got a few notable changes here.</p>
  112. <p>First, we’ve separated the plugins from “core” calculator methods (like <code>plus</code> and <code>minus</code>), by putting them in their own plugins object. Storing our plugins in a <code>plugin</code> object makes our system safer. Now plugins accessing this can’t see the BetaCalc properties — they can only see properties of <code>betaCalc.plugins</code>.</p>
  113. <p>Second, we’ve implemented a <code>press</code> method, which looks up the button’s function by name and then calls it. Now when we call a plugin’s <code>exec</code> function, we pass it the current calculator value (<code>currentValue</code>), and we expect it to return the new calculator value.</p>
  114. <p>Essentially, this new <code>press</code> method converts all of our calculator buttons into <a href="https://en.wikipedia.org/wiki/Pure_function" rel="nofollow noopener">pure functions</a>. They take a value, perform an operation, and return the result. This has a lot of benefits:</p>
  115. <ul><li>It simplifies the API.</li><li>It makes testing easier (for both BetaCalc and the plugins themselves).</li><li>It reduces the dependencies of our system, making it more <a href="https://en.wikipedia.org/wiki/Loose_coupling" rel="noopener">loosely coupled</a>.</li></ul>
  116. <p>This new architecture is more limited than the first example, but in a good way. We’ve essentially put up guardrails for plugin authors, restricting them to <a href="https://www.bryanbraun.com/2015/02/16/on-designing-great-systems/" rel="noopener">only the kind of changes that we want them to make</a>.</p>
  117. <p>In fact, it might be too restrictive! Now our calculator plugins can only do operations on the <code>currentValue</code>. If a plugin author wanted to add advanced functionality like a “memory” button or a way to track history, they wouldn’t be able to.</p>
  118. <p>Maybe that’s ok. The amount of power you give plugin authors is a delicate balance. Giving them too much power could impact the stability of your project. But giving them too little power makes it hard for them to solve their problems — in that case you might as well not have plugins.</p>
  119. <h3 class="wp-block-heading" id="what-more-could-we-do"><a href="#aa-what-more-could-we-do" aria-hidden="true" class="aal_anchor" id="aa-what-more-could-we-do"><svg aria-hidden="true" class="aal_svg" version="1.1" viewbox="0 0 16 16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>What more could we do?</h3>
  120. <p>There’s a lot more we could do to improve our system.</p>
  121. <p>We could add error handling to notify plugin authors if they forget to define a name or return a value. It’s good to think like a QA dev and imagine how our system could break so we can proactively handle those cases.</p>
  122. <p>We could expand the scope of what a plugin can do. Currently, a BetaCalc plugin can add a button. But what if it could also register callbacks for certain lifecycle events — like when the calculator is about to display a value? Or what if there was a dedicated place for it to store a piece of state across multiple interactions? Would that open up some new use cases?</p>
  123. <p>We could also expand plugin registration. What if a plugin could be registered with some initial settings? Could that make the plugins more flexible? What if a plugin author wanted to register a whole suite of buttons instead of a single one — like a “BetaCalc Statistics Pack”? What changes would be needed to support that?</p>
  124. <h3 class="wp-block-heading" id="your-plugin-system"><a href="#aa-your-plugin-system" aria-hidden="true" class="aal_anchor" id="aa-your-plugin-system"><svg aria-hidden="true" class="aal_svg" version="1.1" viewbox="0 0 16 16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>Your plugin system</h3>
  125. <p>Both BetaCalc and its plugin system are deliberately simple. If your project is larger, then you’ll want to explore some other plugin architectures.</p>
  126. <p>One good place to start is to look at existing projects for examples of successful plugin systems. For JavaScript, that could mean <a href="https://learn.jquery.com/plugins/basic-plugin-creation/" rel="nofollow noopener">jQuery</a>, <a href="https://www.gatsbyjs.org/docs/creating-plugins/" rel="nofollow noopener">Gatsby</a>, <a href="https://github.com/d3/d3/wiki/Plugins" rel="nofollow noopener">D3</a>, <a href="https://ckeditor.com/docs/ckeditor4/latest/guide/plugin_sdk_intro.html" rel="nofollow noopener">CKEditor</a>, or others.</p>
  127. <p>You may also want to be familiar with various <a href="https://seesparkbox.com/foundry/javascript_design_patterns" rel="noopener">JavaScript design patterns</a>. (Addy Osmani <a href="https://addyosmani.com/resources/essentialjsdesignpatterns/book/" rel="noopener">has a book</a> on the subject.)  Each pattern provides a different interface and degree of coupling, which gives you a lot of good plugin architecture options to choose from. Being aware of these options helps you better balance the needs of everyone who uses your project.</p>
  128. <p>Besides the patterns themselves, there’s a lot of good software development principles you can draw on to make these kinds of decisions. I’ve mentioned a few along the way (like the open-closed principle and loose coupling), but some other relevant ones include the <a href="http://wiki.c2.com/?LawOfDemeter" rel="nofollow noopener">Law of Demeter</a> and <a href="https://www.martinfowler.com/articles/injection.html" rel="noopener">dependency injection</a>.</p>
  129. <p>I know it sounds like a lot, but you’ve gotta do your research. Nothing is more painful than making everyone rewrite their plugins because you needed to change the plugin architecture. It’s a quick way to lose trust and discourage people from contributing in the future.</p>
  130. <h3 class="wp-block-heading" id="conclusion"><a href="#aa-conclusion" aria-hidden="true" class="aal_anchor" id="aa-conclusion"><svg aria-hidden="true" class="aal_svg" version="1.1" viewbox="0 0 16 16"><path fill-rule="evenodd" d="M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z"></path></svg></a>Conclusion</h3>
  131. <p>Writing a good plugin architecture from scratch is difficult! You have to balance a lot of considerations to build a system that meets everyone’s needs. Is it simple enough? Powerful enough? Will it work long term?</p>
  132. <p>It’s worth the effort though. Having a good plugin system helps everyone. Developers get the freedom to solve their problems. End users get a large number of opt-in features to choose from. And you get to grow an ecosystem and community around your project. It’s a win-win-win situation.</p>