Laravel+Vite环境下JS模块导入导出404错误求助
Laravel中JS模块导入404问题解决
问题详情
我在Laravel 9项目中尝试实现JavaScript代码的导出与导入,但始终失败,具体场景如下:
自定义函数文件(horizontalScrollFunction.js)
export function double(n) { return n * 5; }
Blade模板中的导入代码(home_page.blade.php)
<script type="module"> import { double } from "./public/assets/customFunctions/horizontalScrollFunction.js" console.log(double(5)); </script>
出现的404错误
GET http://mylink/public/assets/customFunctions/horizontalScrollFunction.js net::ERR_ABORTED 404 (Not Found)
Vite配置文件
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; export default defineConfig({ plugins: [ laravel([ 'resources/js/appErp.js', ]), ], });
运行环境
- Windows 10系统
- Chrome 103.0.5060.134浏览器
- Laravel 9.19版本
解决办法
1. 修正路径错误
浏览器加载模块时,./public/ 是错误的路径——Laravel的public目录是Web根目录,所以路径需直接从根目录开始:
<script type="module"> import { double } from "/assets/customFunctions/horizontalScrollFunction.js" console.log(double(5)); </script>
2. 遵循Vite项目规范(推荐)
Laravel配合Vite时,建议将自定义JS文件放在resources/js目录下,通过Vite打包处理:
- 将
horizontalScrollFunction.js移动到resources/js/customFunctions/目录 - 在
resources/js/appErp.js中导入并导出函数:export { double } from './customFunctions/horizontalScrollFunction.js'; - 在Blade模板中通过Vite使用:
@vite(['resources/js/appErp.js']) <script type="module"> import { double } from '@/appErp.js'; console.log(double(5)); </script> - 或者直接通过Vite的asset辅助函数引用:
<script type="module"> import { double } from '{{ Vite::asset('resources/js/customFunctions/horizontalScrollFunction.js') }}'; console.log(double(5)); </script>
3. 确保资源编译到位
如果使用Vite打包,需运行npm run dev(开发环境)或npm run build(生产环境),将资源编译到public/build目录,此时导入路径需对应/build/assets/...格式。
内容的提问来源于stack exchange,提问作者user9172014
相关产品推荐
相关产品推荐

