Guide to Implementing Code Splitting in Webpack 4 for a Library that Exports Separate Modules in a Similar Manner to Lodash or Office Fabric UI

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.

Answer №1

Were you able to achieve your goal in the scenario mentioned above? I have encountered a similar issue while working on the same use case. Upon investigation, I discovered that when a library is defined in webpack, it is added to the this object as

window.myWebpackJsonpMyPrivateLibrary
in the minified main chunk, which remains undefined. Removing the library and libraryTarget from webpack can resolve this issue.

In my situation, I also faced an issue where required chunks were not loading when this module was used as an installed dependency in another project.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What methods are available for parsing JSON data into an array using JavaScript?

I possess an item. [Object { id=8, question="وصلت المنافذ الجمركية في...طنة حتّى عام 1970م إلى ", choice1="20 منفذًا", more...}, Object { id=22, question="تأسست مطبعة مزون التي تع... الأ ...

What is the best way to add custom text to the URL input field of the CKEditor image/link dialog?

Hey everyone, I've been working with CKEditor 4 on my project and I'm facing a challenge. I need to insert a string into the URL textfield in the image or link dialog window using JavaScript/jQuery. Here's where I'm stuck: https://i.ss ...

AngularJS array value with HTML tags is not displaying properly upon invocation

In Angular, I have an array that has the following structure: $scope.posts = [ { "ID" : id(), "Title" : "A", "Company" : "Company A", "Location" : "San Francisco, CA", "Date" : "2016-06-20", "Description ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

What is the process for retrieving a documentDB document using Azure functions?

After setting up an Azure function and a DocumentDB database with a users collection, I find myself at a roadblock trying to establish the connection between the two. My intention is to input a username and have the function automatically retrieve the corr ...

Tips on removing v-bind directives from HTML code in VueJS

So, I've been working with Vue code and HTML recently. Take a look at this example: Vue.component('area-selectors-box', { template: ` <div class="area-selectors-box"> <area-selector v-for="(select, index) in selects" : ...

React Router: Navigating to a Route Becomes Problematic with useNavigate Hook

I am currently developing a React application that utilizes React Router for navigation purposes. One specific component named ShowNotes is causing some issues with the implementation of a "Delete" button, which is intended to redirect to the "/DeleteNotes ...

The functionality of item.classList.toggle() in HTML+CSS+JS fails to execute

I have been working on a program that aims to flip a card when it is clicked. The JavaScript code I have written for this functionality is as follows: /* Card flipping onclick */ import "./Stylesheets/FlipCardStyle.css" var cards = document.quer ...

How to efficiently load SharePoint profile images in an asynchronous manner

Currently, I am working within a SharePoint farm that has User Profiles enabled. Within this environment, we are developing a community feature that includes a profile wall showcasing all members of the community. My task involves retrieving and displaying ...

Guide to successfully setting up a Json server and ReactJS to run simultaneously on the same port

Currently, I am facing an issue while attempting to run my React application with a JSON server as the backend API. The problem arises when trying to run them on different ports due to a CORS error. I am currently seeking advice and looking for a solutio ...

tag directive not functioning properly

I have encountered an issue while trying to create a simple custom directive. When I specify the directive as <div my-info></div> in my HTML file, it works fine. However, when I specify it as <my-info></my-info>, it does not work. ...

Angularjs allows you to repeat a specific number of elements based on a given number

I am working with an object that is connected to the $scope in my Angularjs application {name: 'Vampire Cafe', rating: 4, review: "Food was good, cafe was a bit dark..."} I want to display the value of the rating by showing a certain number of ...

What sets apart 'hasClass' from 'is'? Additionally, is there a substitute to retrieve a Jquery element instead?

Similar Question: jQuery .hasClass() vs .is() Sample HTML code: <div class="results"> <div class="table"> <form class="tr" action="#" method="post"> <div class="td"> <input class="dat ...

Powershell error occurs when custom arguments are used with NPM

I'm attempting to run an npm script with a personalized argument: "publish-local": "ng build $PROJECT && cd dist/$PROJECT && npm publish --registry=http://my.local.npm.registry" Here is how I am trying to execute it from the command prompt: PROJECT ...

Adding styling to my project using @material-ui v5 has resulted in a CSS rule being injected, although I did not define it myself

I'm in the process of incorporating a simple menu component into my project, and I followed the instructions provided in the documentation. When viewing it in a CodeSandbox, everything appears as expected. However, within my actual project, the menu ...

Using the Node.js mongodb-native library to insert multiple strings as separate documents

node: 8.9.4 mongo: 3.6.3 mongodb-native: 2.2.33 Query: How can I seamlessly insert an array of simple strings as new documents with just one call? I prefer not to pre-process the array before insertion. I'm in search of a magical mongo solution h ...

Angular backslash is encoded

Experiencing the same issue as this individual: angularjs-slash-after-hashbang-gets-encoded The URL is getting encoded and not routing correctly, causing it to fall to the otherwise in my route config. I have not been able to identify the root cause yet, ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

SignalR 2.2 application encountering communication issues with client message reception

I am facing an issue in my application where clients are not receiving messages from the Hub when a user signs in. Here is my Hub class: public class GameHub : Hub { public async Task UserLoggedIn(string userName) { aw ...

Guide on sending two dynamically generated select box values through ajax in order to retrieve values for a third select box

I am currently working on a task where I need to populate the 3rd select box based on the selections made in the first two select boxes, which have dynamic values. Below is the jQuery ajax code snippet that I have written (Please note that this code curre ...