Writing npm packages for server and client with webpack
Supposed we wanted to have consistent response messages based on specific actions across projects, it becomes quite obvious that we have a common package containing all these messages (One code to rule them all).
In this example, we are going to build this package. The package should useable by backenders (Server Side) as well as the frontenders(Client Side)
We will be building a package that returns a message for a specific action.
Follow this awesome tutorial to get started on how to build a package.
Let’s get started by looking at our directory structure.
installing the required dependencies
npm i webpack
Next in our index.js file
The important take away is the if block. In the browser, we attach the
customMessages object to the window object whiles exporting it on the server.
The important take away is the
target:'web' config key. this tells webpack to optimize our final bundled code to be used in the browser more on webpack targets here.
We bundle our code by running
webpack . our final project structure should look something like this.
we can then use our package in like so.
Hope this helps. Happy Coding 😙.
Find the code sample on this repo: