如何在Laravel的Vite环境中从JS文件导入Node模块?
在Laravel + Vite中从public目录的JS文件导入node_modules模块
问题关键点
你现在的配置有两个关键问题:
- 没必要把
node_modules里的模块直接加到Vite的input入口里,Vite本身就能自动解析node_modules里的模块,手动加反而容易导致重复打包或者解析出错。 public目录在Vite里默认是静态资源目录,不是源码目录,直接在里面的JS文件用模块导入需要额外配置支持。
解决步骤
1. 调整vite.config.js配置
先删掉input里的node_modules路径,把public/js/my-file.js加入入口,还可以按需加别名简化导入:
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import path from 'path'; export default defineConfig({ plugins: [ laravel({ input: [ 'resources/css/app.css', 'resources/js/app.js', 'public/js/my-file.js' // 把你的JS文件加入Vite处理入口 ], refresh: true, }), ], resolve: { alias: { // 可选:配个别名,以后导入更短 'fathom-client': path.resolve(__dirname, 'node_modules/fathom-client/dist/fathom-client.esm.js') } } });
2. 正确在my-file.js里写导入语句
不用写复杂路径,直接用包名导入就行,Vite会自动去node_modules找:
// 推荐写法:直接用包名导入 import { load as faLoad, trackPageview as faPageView, } from "fathom-client"; // 要是配了别名,也可以这么写 // import { load as faLoad, trackPageview as faPageView } from "fathom-client";
3. 修改Blade视图的加载代码
不用单独加载node_modules里的文件了,直接加载Vite处理后的my-file.js就行,模块会自动被打包进去:
@vite(['public/js/my-file.js']) // 要是你的app.js里已经引入了my-file.js,只加载app.js也可以 // @vite('resources/js/app.js')
额外提醒
- 别直接写
node_modules里的文件路径,Vite的模块解析会自动处理依赖,手动写路径以后包更新了容易出问题。 - 把
public里的JS加入Vite的input后,Vite就会把它当成源码处理,支持模块导入了。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

