search

Home  >  Q&A  >  body text

Learn how to use a CDN to serve lazy loading blocks for Vue JS

I'm developing a single page application written in Vue.js 3 and built by Vue CLI 5 (Webpack 5). The application is served by a Laravel application deployed to AWS, and the deployment tool is Laravel Vapor. The tool also uploads all static resources (including JS chunks) to AWS S3 and provides access via CloudFront.

I want all static resources used in my Vue.js application to be loaded from the CDN. The URL distributed by CloudFront is available in the ASSET_URL environment variable at build time. I've written my own asset functions in TS and SCSS that correctly resolve resource paths for both local development and production environments. Whenever I write URLs for static resources (images, fonts, etc.) in .scss or .vue files, I use these functions and everything works fine.

However, I cannot get the Vue.js application to load the JS chunks from the CDN. There is a problem with Vue Router when I modify the publicPath option in vue.config.js. If I try to directly change the output.publicPath in the Webpack configuration, the Vue CLI will throw an error saying that I can't modify it directly.

So I wrote a script that rewrites all URLs pointing to static resources in the generated index.blade.php file (similar to index. html), the initial JS chunk is now loaded from the CDN. However, all lazy loaded chunks are still loaded from the server where the Laravel application is deployed. It looks like these paths are defined in the generated app.f73fadef.js file.

So my question is, how do I load all static resources (including JS chunks) from a CDN while serving the application from a dynamic web server? Is it possible to achieve this just by changing the Vue CLI or Webpack configuration without doing any "black tricks" like modifying the generated JS files?

P粉718165540P粉718165540319 days ago429

reply all(1)I'll reply

  • P粉155710425

    P粉1557104252024-01-17 00:08:10

    I finally solved this problem. The problem is caused by the following router initialization code:

    createRouter({
      history: createWebHistory(process.env.BASE_URL),
      routes,
    });

    Once I removed the arguments to the createWebHistory function, I was able to set the publicPath option in vue.config.js for my CloudFront distribution URL , everything starts working normally. I was even able to remove my own script that was changing the URL in index.blade.php since it was no longer needed.

    reply
    0
  • Cancelreply