Can System.import in webpack be configured to utilize ajax for progress events?

Recently upgraded to webpack 2, and I've successfully set it up to automatically generate chunks based on System.import calls. It's pretty cool!

However, I'm currently loading the initial chunk through an ajax call in order to monitor progress while loading. You can follow this solution here

My main query is whether there is a way to override or modify the functionality of System.import so that it utilizes an ajax request for chunk loading, allowing me to track events, rather than using a <script> tag?

Answer №1

Unfortunately, no. webpack 2 does not directly support System.import() and translates it to require.ensure() calls which utilize the <script> tag. Even the official WHATWG Loader Spec lacks an API for this functionality. An issue has been raised on this topic, which you can find here.

If you're keen on implementing your own version of require.ensure(), it is possible but requires a deeper dive into webpack's workings. Understanding how webpack handles chunk loading involves exploring its internal plugins. By studying WebpackOptionsApply, or searching for specific code snippets, you can gain insights into webpack's inner mechanisms.

Chunk loading in webpack varies based on the specified target, as different environments demand different implementations. Custom targets can be defined in webpack by passing a function instead of a string, allowing for unique plugin applications tailored to specific needs.

// webpack.config.js

const NodeSourcePlugin = require("webpack/lib/node/NodeSourcePlugin");
const FunctionModulePlugin = require("webpack/lib/FunctionModulePlugin");
const LoaderTargetPlugin = require("webpack/lib/LoaderTargetPlugin");
const JsonpChunkTemplatePlugin = require("webpack/lib/JsonpChunkTemplatePlugin");
const JsonpHotUpdateChunkTemplatePlugin = require("webpack/lib/JsonpHotUpdateChunkTemplatePlugin");

function customTarget(compiler) {
    compiler.apply(
        new JsonpTemplatePlugin(compiler.options.output),
        new FunctionModulePlugin(compiler.options.output),
        new NodeSourcePlugin(compiler.options.node),
        new LoaderTargetPlugin("web")
    );
}

module.exports = {
    entry:  require.resolve("./app/main.js"),
    output: {
        path: path.resolve(__dirname, "dist"),
        filename: "bundle.js"
    },
    target: customTarget
};

To delve deeper, the XHRTemplatePlugin can replace the existing JsonpTemplatePlugin responsible for loading chunks, in our custom implementation:

function customTarget(compiler) {
    compiler.apply(
        new XHRTemplatePlugin(compiler.options.output),
        new FunctionModulePlugin(compiler.options.output),
        new NodeSourcePlugin(compiler.options.node),
        new LoaderTargetPlugin("my-custom-target")
    );
}

The XHRTemplatePlugin dictates code provision in main and child chunks alongside hot updates:

function XHRTemplatePlugin() {}

XHRTemplatePlugin.prototype.apply = function (compiler) {
    compiler.plugin("this-compilation", function(compilation) {
        compilation.mainTemplate.apply(new XHRMainTemplatePlugin());
        compilation.chunkTemplate.apply(new XHRChunkTemplatePlugin());
        compilation.hotUpdateChunkTemplate.apply(new XHRHotUpdateChunkTemplatePlugin());
    });
};

Consider re-using the JsonpChunkTemplatePlugin and

JsonpHotUpdateChunkTemplatePlugin
based on your use-case. Your XHRMainTemplatePlugin could look like this:

function XHRMainTemplatePlugin() {}

XHRMainTemplatePlugin.prototype.apply = function (mainTemplate) {
    mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
        return this.asString([
            // Add your custom implementation here
            "fetch()"
        ]);
    });
};

This answer provides a glimpse into tweaking chunk loading within webpack. Explore real examples and webpack outputs for clarity, and don’t hesitate to draw inspiration from webpack's internal mechanisms.

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

Sending a JavaScript variable to a Ruby on Rails controller for passing it to an API for further processing

My index.html file contains a Google API map implementation. <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body { height: ...

Is there a way to extract just the JSON data from res?

While creating a search functionality to display a list of users, I encountered an error when attempting to load additional pages to show more users: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data var result = JSON.pars ...

Error detecting 403 status code during jquery AJAX request

My current code is set up to trigger an application on a different user's machine through port 9084, as I do not have access to a DEV server. The application in question is written in JAVA and I am trying to initiate it from my ASP.Net application (wh ...

Is there a solution for overflow indicators in combination with a FlexBox column layout?

To clarify this question, we do not have to provide a CSS-only solution. We are open to using JavaScript in our data-driven project. Hello! Thank you for visiting. In summary, we want to enhance Flexbox column layout by breaking the content at specific ...

The JavaScript invocation of a page method resulted in an error 500, with JSON response

I am utilizing an autocomplete control which can be found here: After making some modifications, my code looks like this: var json_options; json_options = { script:'ReportSearch.aspx/GetUserList?json=true&limit=6&', ...

The value of insertId is not being properly displayed

I am struggling to retrieve the last insert ID, as it always returns undefined Below is the API code: app.post('/post', (req, res) => { connection.query(`INSERT INTO tradeoffers (DCID, DCNAME, CATEGORY, IGN, ITEM1, Q1, ITEM2, Q2) VALUES (&q ...

What could be causing the Xpath to display instead of the actual content within the element?

Yesterday, I attempted to scrape match stats from a football game by visiting this URL: To extract the desired stats and display them, I used WebDriver to select specific data. Here's the code snippet: from selenium import webdriver from selenium.we ...

What is the best way to implement a JavaScript pattern matching for both "aaaa" and "aaa aaa"?

Can anyone help me create a pattern that can accept both strings with spaces and without spaces in the same text box? I would appreciate any guidance on how to achieve this. Thanks! ...

There seems to be an issue with the Link component from react-router-dom when used in conjunction with

I am currently utilizing react-router-dom along with Material-ui My main objective is to create a clickable row in a table that will lead to a specific path. Here is the code snippet: .map(client => ( <TableRow key={client.id} component={Link} to ...

Is it possible for Nuxtjs/apollo to make apollo wait for other requests before initiating the query?

Is there a way to have Apollo wait for the result of one request to a third party before making either of two queries? Or should I manually add the appropriate query to Apollo after receiving the results? ...

Issue with verifying file existence utilizing $.ajax()

I'm currently facing a challenge checking for the existence of a file using $.ajax(). I am cycling through a JSON file with $.each and trying to determine if a specific staff member has an image. If not, I want to default to using the no_photo.jpg ima ...

The MVC Controller received a file that is empty

Looking to submit multiple items to my MVC Controller: an image and two strings. In my View, there's a form with enctype="multipart/form-data" for automatic submission after selecting an image file. Here's the submit handler: $("#PhotoUploa ...

Open the HTML document and access the file contents

I'm having trouble reading a text file from my computer onto a website. It works fine in Internet Explorer, but won't work in Chrome. I don't have much experience with HTML, so any help would be much appreciated! <html> <body> ...

Modify data in a table using Dialog Component in Angular Material

I need to implement a Material Dialog feature that allows users to update entries in a table by clicking on the "Change Status" button. Check out this functional snippet: https://stackblitz.com/edit/angular-alu8pa I have successfully retrieved data fr ...

How can I set a value using document.getElementById(idPopUPImage).innerHTML to create a static popup in Leaflet?

I added a leaflet map to my project which you can find on Codpen In the map, I've included a button key that displays an image in a popup when clicked. However, after closing the popup and reopening it, the image doesn't show unless I click the ...

What is the best way to send JSON data to a different webpage and successfully navigate to that webpage?

Is it possible to solely utilize JavaScript (jQuery, AngularJS, or other libraries) without utilizing a form to navigate to another page while sending JSON as the POST request body? In other words, I am looking to write a piece of JavaScript code that wil ...

There was an error that occurred stating, "TypeError: Unable to access the property 'params' of undefined within the App React

Every time I log props.match.params, an error occurs: TypeError: Cannot read property 'params' of undefined at App. Interestingly, even when I log props, I see four empty arrays. Below is the relevant code snippet: Home.js import React from &quo ...

Submitting a PHP form by uploading an image with AJAX

I'm looking to submit form data to a MySQL database using AJAX. While I'm not very familiar with AJAX, I managed to write a code that successfully submits text data to the database. However, I'm facing issues with uploading and storing image ...

What could be causing my handle button to slide off the timeline towards the right?

I'm facing an issue with my volume bar component where the slider button is rendering outside of the timeline instead of on top of the progress bar. I need assistance in adjusting its position. // Here is the code for my volume bar component: import ...

Is it possible to upload the WebRTC audio blob object using the file input element like a regular file without having to download it?

Greetings and thank you for taking the time to read my inquiry. I have been utilizing WebRTC to capture audio, successfully obtaining a blob object that I can manipulate using JavaScript to link the source of an audio element and play it as though it wer ...