I have a project where I have some API handled by a couple of node servers and a React client application that allows interaction with them.
I also have some code that executes some functionalities that are common for all the 3 components (client-side code), while others are only common between the 2 server components (server-side code).
The common library uses CommonJs
module import, all my code is inside the src
folder except for some tests.
Using this setup I can import the library in my server components without any problem. However, If I try to use it on my React application I get many errors due to imports that are not working properly because trying to use server-side functionalities like fs
and many others.
I have tried to use Webpack
with Universal Module Definition (UMD) in order to have a library that can work with both browser and server, here my config:
const path = require("path");
module.exports = {
entry: path.resolve(__dirname, "src/index.js"),
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
globalObject: "this",
library: {
name: "common-libs",
type: "umd",
},
},
mode: process.env.NODE_ENV,
};
However, when I run webpack
script I get errors about my dependencies that are not resolved.
My overall goal is to publish this library as an npm package and import it on all my projects in order to have those common functionalities in one place.
Do you have any suggestions?