I currently have a large custom NPM library that is utilized by multiple teams within the organization. The library is currently published as one extensive single file, similar to the main lodash file. However, this approach results in bloated application bundle sizes since some of the applications do not require all the contents of the library.
Currently, the apps are importing the library like this:
import { SomeReactComponent, someHelperFunction } from 'my-private-library';
My goal is to publish the library with individual modules, similar to Lodash. The imports would then look like this:
import SomeReactComponent from 'my-private-library/lib/SomeReactComponent';
import someHelperFunction from 'my-private-library/lib/someHelperFunction';
I have managed to configure Webpack to output the library in this format using multiple entry points. However, I am facing challenges in getting Webpack to separate shared dependencies among those modules. For instance:
src/SomeReactComponent.jsx
import React from 'react'
import SOME_CONST_STRING from '../constants';
const SomeReactComponent = () => {
return (
<div>You are using {SOME_CONST_STRING}</div>
);
}
export default SomeReactComponent;
src/someHelperFunction.js
import SOME_CONST_STRING from '../constants';
export default function someHelperFunction() {
return `This is just an example of ${SOME_CONST_STRING}`;
}
While my Webpack setup outputs individual files, it fails to effectively split out common code for consumption by applications. For instance, the SOME_CONST_STRING
dependency is duplicated in both exported files.
My current Webpack configuration looks something like this (trimmed for brevity):
module.exports = {
entry: {
SomeReactComponent: './src/SomeReactComponent',
someHelperFunction: './src/someHelperFunction',
},
output: {
path: './lib',
library: 'MyPrivateLibrary',
libraryTarget: 'umd',
filename: '[name].js'
}
// other settings removed for brevity
}
I have attempted to utilize the splitChunks
optimization setting as follows:
module.exports = {
entry: {
SomeReactComponent: './src/SomeReactComponent',
someHelperFunction: './src/someHelperFunction',
},
output: {
path: './lib',
library: 'MyPrivateLibrary',
libraryTarget: 'umd',
filename: '[name].js'
},
optimization: {
splitChunks: {
chunks: 'all',
},
},
// other settings removed for brevity
}
Although this splits the code, attempting to use the library in an app after applying this change results in errors such as (
ERROR in TypeError: __webpack_require__(...) is not a function
). Can anyone point out where I might be going wrong? Is my desired outcome achievable with Webpack? Are there any documented examples available on how to achieve this?
I apologize for the example code provided; due to the private nature of my library, real-code illustrations are not feasible.