Publishing a Widget as an NPM Package

Have you created a Scrivito widget you would like to share with other developers for adding it to their Scrivito-based app? Or maybe you’ve written a cool integration with a third-party service, and want to spare others the effort.

In this guide we are going to explain to you the basic procedure for creating an npm package from a Scrivito widget. We’ll use a slightly simplified version of our FaqWidget here.

Develop your widget

Some guides on publishing React components

The first thing you’ll need is, of course, the widget you want to share. So, develop your widget as part of your app, which might or might not be based on the Scrivito Example App.

Initialize your package project

If you want to share the code of your future package on a repository hosting platform such as GitHub or BitBucket, create a repository and clone it to your local machine. The resulting directory would be your project directory for the package. Otherwise, create the project directory manually, named like your package.

Make sure you have npm on your machine, then change to your project directory and run npm init. You will be asked to enter the package name, the URL of your remote repository (e.g. on GitHub), and a couple of things more.

Since the widget requires the host app to have React and Scrivito installed, we’ve added them as peer dependencies to this configuration. We’ve also changed the entry point (main) to “build/index.js”, and added the start and build script names.

If your widget depends on other modules, don’t forget to install them (and add them to the dependencies) as needed.

In case you need to upgrade babel, there’s a tool for this that makes things a lot easier, babel-upgrade.

Configure webpack

For having webpack build your package and transpile your React code to JavaScript, two files are required in the project directory, “webpack.config.js” and “.babelrc”:

Add your widget

In your project directory, create a folder named “src”. In this folder, create a file named “index.js”. This file is the entry point, meaning that Webpack will execute the code in the process of installing your package.

You can place all the code your widget is comprised of in this “index.js” file, or import parts from separate files. In the case of an ordinary widget, you’d copy-paste the contents of the “…Class.js”, “…EditingConfig.js”, and “…Component.js” files like we did below for our FaqWidget:

When adding a widget to a page, the “FaqWidget” should now be among the widgets offered!

Publish your package

If everything works as it should and your readme file is complete, sign up for an npm account, if you don’t have one already, and make sure that your package name is unique. Then npm publish. If you want to test-publish the package locally, there’s an npm sibling for this, Verdaccio.