coder222's avatar

require('jquery') in bootstrap.js doesn't work

It's a similar problem like my previous question, got this error: ReferenceError: jQuery is not defined, but can't be resolved by just using import. Similar issue here: https://github.com/laravel/framework/issues/17634, there are so many solutions there but I have tried some so far and none is working for me :D

If you know what the problem actually is, or have any reference to an article that explains this issue would be really appreciated.

0 likes
5 replies
tykus's avatar

Make sure that bootstrap.js is required by your precompiled app.js so it is included in the build; otherwise it will not be in the js/app.js build.

Wherever you want to use jQuery in your application, it must come after the js/app.js script has been included. This might mean either (i) you place the <script src="/js/app.js"> in the head, or (ii) use stacks to organise scripts, or (iii) write your jQuery logic into the compiled JS (assuming you currently have script tag(s) in various Blade templates)

coder222's avatar

@tykus Thank you very much for your reply.

Make sure that bootstrap.js is required by your precompiled app.js so it is included in the build; otherwise it will not be in the js/app.js build.

Yes, there is this code in app.js: require('./bootstrap');

(i) Ok, I have ` at the bottom. Sorry, but why should I put it on the top? It's a js file that should be loaded with the page. The error is actually coming from a Vue component that requires jQuery from an external package (I'm also not sure why jQuery isn't set as that package's dependency).

tykus's avatar

The OP did not mention you were using jQuery in Vue; hence no reference in my response.

The ProvidePlugin will automatically load the specified modules whenever they are referenced in other modules. Think of it like a global import.

coder222's avatar

@tykus Oh okay, I didn't know if it will make any difference between using it in Vue or not. So, if it's not being used in Vue, we should put <script src="/js/app.js"> on the top, otherwise, we can use ProvidePlugin, CMIIW. Thank you very much for your help.

Please or to participate in this conversation.