Enhance your webpack workflow with the plugin API to dynamically update asset content and regenerate hashes

For a project I'm working on, I've developed a plugin that handles the swapping of content in a specific JSON file after all modules are bundled. This is achieved through 2 steps: a loader that replaces the content with a placeholder, and the plugin that replaces the placeholder.

The loader function is as follows:

const loader = function(source) {
  this.clearDependencies();
  return JSON.stringify('REGENERATED_JSON');
};

And the plugin function looks something like this:

compilation.hooks.optimizeChunkAssets.tapAsync(PLUGIN_NAME, (chunks, callback) => {

  chunks.forEach((chunk) => {
    chunk.files.forEach((filePath) => {
      const asset = compilation.assets[filePath];
      const source = asset.source();

      replacements.forEach((id) => {
        const pattern = 'JSON.parse(""\\"REGENERATED_JSON\\""")';
        const index = source.indexOf(pattern);

        if (index < 0) return;

        const content = JSON.stringify(json_content, null, 2);
        const updatedSource = new ReplaceSource(asset);

        updatedSource.replace(index, index + pattern.length, content);
        compilation.assets[filePath] = updatedSource;
      });
    });
  });

  callback();
});

This code does have some drawbacks:

  1. It is fragile because it relies on a JSON.parse call. I couldn't find a way to make webpack treat the file as JavaScript after importing it as JSON.
  2. The content hash is not being rebuilt, nor is the file size assessment, so webpack may not accurately assess the size of the JSON content.

Is there a solution within webpack to address these issues?

Answer №1

This insightful comment provided the solution to my problem: https://github.com/webpack/webpack/issues/8830#issuecomment-580095801

To summarize:

  1. Utilize
    compilation.hooks.finishModules.tap
    to access modules after they have been parsed
  2. Add a new loader or modify module information directly within this hook
  3. Initiate a rebuild of specific modules using
    compilation.rebuildModule(module, callback)
    , consider converting to promises with promisify for handling multiple parallel rebuilds

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

The array is arranged properly, yet React is failing to render it in the correct order

Here's the code snippet I am working with: { this.state.rows.map((qc) => qc.BinsByDayByOrchardsQCs.map((qc2) => qc2.BinsByDayByOrchardsQCsDefects.map((qc3) => !defectsArray.includes(qc3.Defect) &am ...

Navigating from a view to a controller in MVC to reach a different view: a step-by-step guide

I implement the MVC model using PHP, JS, HTML, and CSS. Additionally, I utilize CodeIgniter as my framework. I am looking to understand how to redirect to another controller. While on the Home page of my project, when clicking on "details" (div = prod_det ...

javascript function How can one access the current object in a module without using the 'this' keyword?

I have observed that the reference of this inside a function, added as an event listener, points to something else. Despite reading through an informative resource and checking stackoverflow, I am still unsure how to resolve this issue (as I am relatively ...

Is it possible to validate my form using only class?

I have a group of radio buttons with the same class. These radio buttons are dynamic, which is why I am considering using the class for validation. Below is my code snippet: $('#listening_choices_wrapper').on('submit', function(e) ...

Modifying the theme of the Angular UI-Bootstrap datepicker

I am currently facing an issue with my angular datepicker, which is appearing oversized and covering almost 30% of the screen. Additionally, there are large gaps between the dates in the calendar view. After some investigation, I believe this problem may ...

Ordering items in Angular-js ng-repeat using a complex orderBy function

------- Updated query ----- I am struggling with implementing the orderBy function along with limitTo: Here is an example: orderBy id limitTo 1 'adam1@xxx' - id:10 'adam2@xxx' - id:20 'adam3@xx' - id:16 Then, I need to ...

Utilizing web components in React by solely relying on a CDN for integration

I have a client who has provided us with a vast library of UI elements that they want incorporated into our project. These elements are stored in javascript and css files on a CDN, and unfortunately I do not have access to the source code. All I have at my ...

Authenticate with Google using the Javascript API without causing a pop-up to appear

Here is the code I'm using to allow users to log in with their Google account via the Javascript API. HTML <a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a> Javascript function gPOnLoad ...

Next.js encountered a TypeError while attempting to parse the URL from a specific location when targeting the API route relatively

I'm encountering an issue with my code in the app/page (Server Component): const getUsers = async () => { const result = await fetch('/api/users', {method: 'GET'}); if (result.ok) { return result.json(); } return []; ...

How to retrieve the value of input in a Formik form when the onChange event occurs

Currently, I am working on creating a form using React JS and the Formik library. One issue I encountered was related to validation, specifically the need to replace invalid letters with an empty string. str.replace(/\D/, ''); The challenge ...

Can the coordinates in an array be constrained within a specific radius?

I am relatively new to using Google Maps and ReactJS. To plot my map, I am utilizing google-maps-react. The property I am working with is comprised of multiple polygons that collectively form the property (farm) displayed on the map. Upon clicking a spec ...

Retrieving the output of a parent computed method in VueJS, using a child component

I am facing difficulties in passing the dynamically changing value of a computed method to my child component. I am creating a button component with different save states, but the button always remains stuck on one state and does not update according to th ...

The ng2-dnd library encountered an issue: StaticInjectorError in AppModule with SortableComponent pointing to ElementRef

I have been experimenting with the ng2-dnd sortable container from ng2-dnd. Below is the HTML code for my component: <div class="row"> <div class="col-sm-3"> <div class="panel panel-success"> <div ...

JSON request returning a value that does not exist in the specified .json document

While I may be new to JSON and JavaScript, I am encountering an issue that is perplexing me. On a webpage, I have two scripts included - jQuery and "scripts2.js". In the same directory as "scripts2.js" resides a JSON file named "settings.json". Within my " ...

Retrieve information using the useEffect hook on a server-side rendered webpage

I am currently working on a project using React JS and Next JS. The page is dynamic, utilizing getStaticPaths and getStaticProps to fetch most data on the server side for rendering. However, there are certain pieces of data that require a token stored in l ...

Tips for adding multiple elements to the DOM at once

Is it possible to efficiently append elements to the DOM all at once? In the code snippet below, I am adding elements to a root element (tr_next) within a loop. $('.abc').each(function(){ //create element code here var tr_next = $("<tr> ...

Utilizing React componentDidUpdate for merging and appending data

I am working with a functional component that generates data in an object format from a state variable called scanlist: 0: brand: "AATEST" exp: "2022-08-25" gtin: "15735423000247" iname: "Arthur's Test Item" lot ...

Unable to merge geojson and json data in Leaflet map display

To send information to the map, utilize this code: function join(){ $.when( $.getJSON('bairro.json'), $.getJSON('convertJson.php') ).done(function(responseGeojson, responseData) { var data = ...

Issue: Cannot access the 'map' property of an undefined value in a React Mongo DB error

My React code was running perfectly fine until I encountered an error message in the browser console: "TypeError: Cannot read property 'map' of undefined". Let me share the snippet of my code with you. const MyComponent = () => { const [dat ...

Pass PHP date to JavaScript and increase its value

I'm looking to retrieve the server time with PHP and store it in a JavaScript variable. Once stored, I'd like it to continuously increment. Below is the code snippet: function initTime(date){ var today=new Date(date); var h=today.getHours(); v ...