Retrieving sections from dynamic imports via a CDN link just like any other resources

I currently have a CDN set up to point to my base domain with a 1:1 mapping. I am in the process of building my bundle on the server and I want to load it using the CDN URL. After running npm run build, I am aiming for the following structure:

public/
  css/
    app.css
  js/
    index.js
    1.js.gz
    1.js
    2.js.gz
    2.js

My goal is to have these resources loaded like this on my CDN:

https://mycdn.com/public/js/index.js
https://mycdn.com/public/css/app.css

This is my current configuration in webpack.mix.js:

mix
  .sass('resources/sass/app.css', 'public/css')
  .js('resources/js/index.js', 'public/js')

The files are generated in the correct location and then included in my index.blade.php:

<script src="{{ elixirCDN('/js/index.js') }}"></script>

I have a custom function called elixirCDN to prepend the filename with the CDN URL.

function elixirCDN($file)
{
    $cdn = '';

    if(config('system.cdn_url'))
    {
        $cdn = config('system.cdn_url');
    }

    return $cdn . elixir($file);
}

Everything works fine until I try using dynamic imports like this:

const Home = () => import("./Home")

In an ideal situation, I want these dynamic imports to also load from the CDN:

https://mycdn.com/public/js/1.js

However, they currently load with a relative path using my base domain:

https://mybasedomain.com/public/js/1.js

I have tried setting publicPath to my CDN URL and using setPublicPath(), but it hasn't had any effect. How can I ensure my chunks are also loaded from the CDN?

Answer №1

Hey there! While this may not be the absolute solution, it's definitely a step in the right direction. I encountered this issue when my conditional import stopped working after updating all the webpack and babel packages.

Prior to the dynamic import, you'll need to establish a temporary public path for webpack to point to the specific chunk that needs to be imported dynamically.

__webpack_public_path__ = 'https://cdn.dev.acsi.eu/eurocampings/assets/dev/dist/';

Once this is set, the import should function properly.

import(/* webpackChunkName: "state" */ './modules/BookingState/State')
        .then(({createState}) => {
            createState();
            this.renderEurocampingsWebsite(window);
        });

The dynamic import works for me now, although it appears that the conditional import used to work without asynchronous behavior before all the package updates...

I recently discovered that webpack supports additional 'magical' comments, which can alter the code behavior to be more procedural. However, it may result in both modules being imported for the conditional import. Here's an example:

import(
            /* webpackChunkName: "state" */
            /* webpackMode: "eager" */
            /* webpackPreload: true */
            './modules/BookingState/State'
        )
        .then...

Answer №2

I encountered a similar issue where my primary script was being loaded into a different page, resulting in the chunks attempting to load from the root URL instead of the CDN.

After exploring the solution provided above, I implemented the following approach:

Within the root imported file:

export function configureWebpackToLoadChunksFromScriptUrl() {
  const scriptPath: string = (document.currentScript as any || {}).src;
  const loadPath = scriptPath ? scriptPath.substring(0, scriptPath.lastIndexOf('/')) : '';
  if (loadPath) {
    __webpack_public_path__ = loadPath;
  }
}
configureWebpackToLoadChunksFromScriptUrl();

export async function initializeApplication(elementId: string) {
  const { loadApplicationOnHtmlElement } = (await import('./loaded-app'));
  loadApplicationOnHtmlElement(elementId);
}

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

Beginner coding exercises to master JavaScript

With a proficiency in CSS, HTML, and some knowledge of Jquery and PHP, I aspire to become a Front End Web Developer. However, my lack of understanding in Javascript is holding me back. I acquired my current skillset by rapidly learning over 9 months while ...

What is the method for incorporating a variable in MapReduce?

I have the following MapReduce script that I'm working with: splitAndGroupServices = function(groupMembers) { var mapFunction = function() { for(var idx in this.services) { var service = this.services[idx]; if(service.mem ...

What is the best way to implement form fields that have varying validation patterns based on different conditions?

Currently, my focus is on developing a form that prompts the user to choose between "USA" or "International" via radio buttons. The input field for telephone numbers should then adapt its requirements based on the selected country - either a 10-digit US nu ...

A guide on deploying Laravel and PostgreSQL with Docker containers

Need assistance with creating dockerfile and docker-compose files for setting up Laravel with Postgres. Below is my docker file: FROM php:7.4 RUN apt-get update && apt-get install -y \ libfreetype6-dev \ libjpeg62-turbo- ...

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...

Consider modeling as a variable

I came across a situation where I need to execute different code based on the model type. However, I find myself repeating similar code blocks multiple times. Is there a way to efficiently substitute the model into the code without duplicating the same l ...

The continuous looping issue is being triggered when implementing a like button using firestore along with useEffect and UseState

I have developed a component to be loaded into various cards for displaying data. This particular component retrieves and stores data from the card (sale_id) onto the database. import { LikeButtonStyle } from './LikeButton.styled'; import { Image ...

The upload functionality in Codeigniter seems to be malfunctioning

I am currently developing a content management system using Codeigniter. I am facing an issue with uploading files from the system. Although I am able to receive the file, the do_upload method seems to be not functioning correctly. I have looked for soluti ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

Unable to assign the value of a Ruby variable to a JavaScript variable

I have a Ruby variable that contains latitude and longitude coordinates: @json = [{"lat":37.8690058,"lng":-122.2555342},{"lat":37.8739362,"lng":-122.2653001},{"lat":37.8701101,"lng":-122.2578559}] When I attempt to use this variable in a JavaScript scrip ...

Switching the markLine in vega lite to a markBar causes it to lose its sorting arrangement

I have created the following data visualization: data = [{"student_name": "student 0", "e": "100.15", "d": "127.81"}, {"student_name": "student 1", "e": "100.30", "d": "189.94"}, {"student_name": "student 2", "e": "100.15", "d": "105.33"}, {"student_nam ...

Registering a change event for a table's value

I am a beginner in Angular and struggling with writing an event that can successfully pass the changed value from a table cell to my component. Below is the HTML code for the table cell, where the user should be able to change the value and have it passed ...

What is the best way to integrate asynchronous computed observable with several concurrent $.ajax requests?

I'm currently working on implementing an asynchronous computed observable following the guide provided here. While I have successfully achieved this for a single ajax call, I am facing a challenge in figuring out how to perform multiple ajax calls in ...

Issue with JQuery UI Tabs not displaying additional HTML pages in JavaScript

One issue I'm facing is that I added Tabs from JQuery UI on my website. The tab containing paragraphs loads fine, but the tabs linked to other HTML pages (which don't have tabs) won't load. Here is my .js file code and .html code: $(funct ...

Does the Apps Script parser JSON.parse() incorrectly remove leading zeros from string object keys?

I am facing an issue with my Apps Script Web App where JSON data is being manipulated when I try to parse it. Specifically, keys with leading zeros are being altered (e.g "0123" becomes "123") during the JSON.parse() function call. It seems like the functi ...

Error message: "Unable to access 'title' property of an undefined value" for an item with a length of 1

Despite the fact that the collection is not undefined and the `title` attribute is also not undefined, for some reason I am unable to read the `title` attribute from the `received` variable. The error indicates that it is undefined. var received = document ...

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

Can Selenium WebDriver be utilized to automate tasks in desktop applications?

In the midst of preparing to create automated tests for a Web/Desktop application that is still in its early stages of development, I am intrigued by the integration of Laravel, VueJS, and the Electron Framework. Electron, known for facilitating the creati ...

jQuery AJAX chained together using promises

In my current project, I am facing an issue where I have 4 get requests being fired simultaneously. Due to using fade effects and the asynchronous nature of these requests, there are times when empty data is received intermittently. To address this issue, ...

Modify the NAME attribute when clicked using Jquery

I am attempting to modify the NAME attribute of a DIV with the text from a textbox using jQuery. Take a look at my code snippet: http://jsfiddle.net/e6kCH/ Can anyone help me troubleshoot this issue? ...