Search code examples
javascriptnode.jspluginsorganization

What are the best practices for writing and organizing javascript plugins?


So I have a nice chunk of code that is the same across many different javascript files, but I occasionally have to update it due to path changes or other various conditions. Now copy and pasting it all over to the new files works fine but is annoying to execute. Is there a good way to maintain one javascript file with my "plugin" code and have it be accessible by other javascript files that use the plugin?

I am looking for both a good nodejs solution, and vanilla js solution. If they could be mutually shared that'd be ideal, but not required by any means. Ideally, I'd like to host my workspace in workspace/ and have some folders, workspace/front-end-js/ and workspace/back-end-nodejs/, be able to run code off a plugin in workspace/plugins/ so that I can execute things like MyPluginVar.Foo();

I am aware of some systems, like the node's var foo = require('bar'); and the frontend browserified version, but really do not know all my options. What's the best way of writing and organizing javascript plugins?

--

Edit: I'm really trying to avoid npm, but it might be the best option.


Solution

  • You typically add your shared libraries and plugins as dependencies to your project's package.json file and install them using npm.

    CommonJS modules, which use the module.exports object and require function, are the de facto standard at the moment.

    ES2015 modules, which use the export and import statements, are an emerging formal standard, but support for them is not yet universal. They are a good option if your environment supports them.

    To load either type of module on the front end, you will need to use a bundler such as Webpack or Browserify.

    Older javascript modules typically publish to the global scope (window), and are a simple option for front end code.

    You can also support multiple module systems if you like by using a UMD (Universal Module Definition) wrapper. Here's an example from the UMD Github repo that leverages CommonJS if supported, while falling back to a browser global:

    (function (root, factory) {
        if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
            // CommonJS
            factory(exports, require('b'));
        } else {
            // Browser globals
            factory((root.commonJsStrictGlobal = {}), root.b);
        }
    }(this, function (exports, b) {
        // b represents some dependency
    
        // attach properties to the exports object to define
        // the exported module properties.
        exports.action = function () {};
    }));