You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 10与Vite下动态ES模块导入的问题及解决方法

Laravel 10 升级后 Vite 适配动态按需加载 JS 文件的解决方案

背景

现有一套特殊业务逻辑的实现方案,在Webpack Mix环境下可正常运行,但升级至Laravel 10并切换为Vite构建工具后,动态按需加载JS文件的逻辑无法适配。

原有可正常运行的模块导入逻辑

工具函数模块导入

app.js通过ES模块导入工具函数文件,并存储函数引用,这部分在Vite下可正常工作,Vite会通过rollupOptions自动替换打包后的文件路径:

const helperLookup = {
    "dateFormat": {},
    "validateFile": {},
};
    
// Import general helper file
import('../js/components/general-module.js')
.then(module => {
    // Create a "helperLookup" link to each function
    helperLookup["dateFormat"] = module.dateFormat;
    helperLookup["validateFile"] = module.validateFile;
});

固定路径的页面JS导入

导入指定页面JS文件并传递工具函数,这部分也能正常打包运行:

import('../js/first-page.js')
.then(module => {    
    module.shareGlobalFunctions(helperLookup["dateFormat"]);
    module.default();
})

遇到的动态加载问题

存在多个需根据HTML/Blade页面按需加载的JS文件,通过页面内联脚本指定文件名:

<script>
    document.js_arr = [
        {
            "file": "example-module.js",
        }
    ];
</script>

app.js读取该数组后尝试动态导入对应文件,但由于导入路径为动态变量,Vite在构建时无法识别具体文件名,无法完成打包及路径替换。

尝试直接使用打包后的路径并在vite.config.js中配置文件后,虽能加载文件,但调用module.default()时出现错误:

TypeError: t.default is not a function

原因是该文件被单独打包,app.js无法识别其模块转换后的引用关系。

最终解决方案:使用import.meta.glob

通过import.meta.glob方法预匹配目标目录下的所有JS模块,Vite会自动关联原文件与打包后的文件,同时支持样式文件的自动处理:

1. 预定义模块匹配

const modules = import.meta.glob('../js/components/*.js')

2. 动态调用模块

遍历页面指定的文件列表,通过预定义的模块映射加载并执行:

// 假设js_object是document.js_arr中的单个元素
modules[js_object["file"]]()
.then(module => {
    module.default();    
});

内容的提问来源于stack exchange,提问作者Delmontee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:06:02