laravel - How to serve lazy-loaded Vue JS chunks from CDN
问题描述
I work on a single-page application written in Vue.js 3 and built by Vue CLI 5 (Webpack 5). The app is being served from a Laravel app which is deployed to AWS by Laravel Vapor. This tool also uploads all static assets (including JS chunks) to AWS S3 and make them available via CloudFront.
I want to load all static assets used in the Vue.js app from this CDN. The URL of the CloudFront distribution is available at build time in ASSET_URL
environment variable. I have written my own asset
functions in both TS and SCSS which are able to resolve asset paths properly for both local development and production environment. I use these functions whenever I write a URL of a static asset (image, font, etc.) in either .scss
or .vue
file and everything works fine.
But I am not able to make Vue.js app load JS chunks from CDN. When I modify publicPath option in vue.config.js
, Vue Router gets broken. If I try to change output.publicPath directly in Webpack config, I get an error from Vue CLI saying that I cannot modify it directly.
So I have written a script that rewrites all URLs pointing to static assets in the generated index.blade.php
file (similar to index.html
in a typical Vue.js project) and initial JS chunks are loaded from CDN now. However, all lazy-loaded chunks are still being loaded from the server where Laravel app is deployed. It looks like these paths are somehow defined the generated app.f73fadef.js
file.
So my question is, how can I load all static assets (including JS chunks) from CDN while serving an app from a dynamic web server? Is it even possible to do this just by changing Vue CLI or Webpack config and without any dirty "hacks" (like modifying generated JS files)?
解决方案
我终于能够解决这个问题。该问题是由以下路由器初始化代码引起的:
createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
一旦我删除了createWebHistory
函数参数,我就可以在我的 CloudFront 分配 URL 中设置publicPath选项,vue.config.js
并且一切都开始正常工作。我什至可以删除我自己的更改 URL 的脚本,index.blade.php
因为它不再需要。
推荐阅读
- ios - 如何在合适的视图中快速将日期格式从 1999-05-18 转换为 18 月
- android - 在哪里可以找到有关替代 API 的 android 官方新闻?
- angular - 如何在构建期间对构建组件启用所需的属性检查?
- android - 无法在 x86_64 上运行 .apk
- angular - Angular 6 7 8 - 拖放 + 虚拟滚动 + Observable
- excel - 如何将弹出窗口中的 ID 与 Excel 中的 VBA 对齐?
- python - python如何在调用流取消()后处理grpc流
- sql - 将几个查询“SELECT INTO..”合并为一个
- linux - 脚本应输出此文本“this is text”;“Nano”;”超过 10 个字符
- java - 如何在Android中使用后台服务覆盖两次甚至3次单击电源按钮甚至音量上/下键?