Gem-based Plugins and Webpack

When authoring a plugin or theme for Bridgetown, you may find yourself wanting to ensure users of your plugin are able to load in your frontend assets through Webpack (such as JavaScript, CSS, etc.) The best way to do this is to set up a package.json manifest and publish your frontend code as a package to the NPM registry.

Let’s assume you’ve been building an awesome plugin called, unsurprisingly, MyAwesomePlugin. In your my-awesome-plugin.gemspec file, all you need to do is add the yarn-add metadata matching the NPM package name and keeping the version the same as the Gem version:

  spec.metadata = { "yarn-add" => "my-awesome-plugin@#{MyAwesomePlugin::VERSION}" }

With that bit of metadata, Bridgetown will know always to look for that package in the users’ package.json file when they load Bridgetown, and it will trigger a yarn add command if the package and exact version number isn’t present.

The SamplePlugin demo repo includes a script/release command you can use to run the test suite, release a new version of the gem, and release a new version of the NPM package all in one go. (This will also be present if you set up your plugin using the bridgetown plugins new command.)

You will need to instruct your users how to add the plugin’s frontend code to their Webpack entry points. For example, they might need to update frontend/javascript/index.js with:

import MyAwesomePlugin from "my-awesome-plugin"

const awesomeness = new MyAwesomePlugin()
awesomeness.doCoolStuff()

Consider writing an automation to make this process easier for users.

Back to Plugins