指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

laravel11使用jquery:

1>首先 npm install jquery, 会安装最新版本v3.7
  
2>在bootstrap.js下配置jquery
import $ from 'jquery';
  
window.$ = window.jQuery = $;
  
3>在user.blade.php页面使用(这里继承自layout/app.balde.php)
@section('script')
<script>
    $(function (){
        $('.user-log').click(function (){
            console.log("11111")
        })
    })
</script>
@endsection
  
4>运行 npm run dev
  
5>访问user页面, 报:ReferenceError: $ is not defined, Jquery Import with vite
  
6> 原因分析
刚开始我还以为这是因为 引入了vue的缘故,后来我把vue相关的部分全部注释了,发现还是报这个问题
①发现使用document.addEventListener 可以解决这个问题,但是写法太丑了,这个其实是等整个页面加载完再使用 jquery
document.addEventListener('DOMContentLoaded', function() {
  $('.user-log').click(function (){
         console.log("11111")
     })
});
  
②直接通过引入 <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> , 也可以解决问题,但是这样很不友好
  
③最终发现在 script 标签里添加 type="module" 问题解决,可以正常使用 $ 了
<script type="module">
    $(function (){
        $('.user-log').click(function (){
            console.log("11111")
        })
    })
</script>
  
根本原因是:
Vite is loading scripts as modules. And module scripts are always deferred. So if your jQuery script is placed after Vite directive, jQuery code is executed first, before loading jQuery to window - this triggers $ is undefined error.
  
In best practise, you should move the jQuery code to app.js file, so it stays in it's own module. The other way to handle this is to mark your script tag as a module, then it'll follow the loading order of the document.
  
关于module scripts are always deferred: https://javascript.info/modules-intro#module-scripts-are-deferred // 以前不知道这个知识点,介绍的很详细,很有用
  
参考:https://stackoverflow.com/questions/73010251/referenceerror-is-not-defined-jquery-import-with-vite // 真的很有用的帖子
  
7>总结
laravel11使用vite编译js资源和之前的webpack还是有很大的区别的,但是使用vite更简洁,现在已经解决了使用 laravel11 + vite5 + vue3 + tailwindcss3 + jquery3 混合开发的所有问题