How to require npm packages after installing it in Laravel?
For example,I need package sweetalert2
,installing it first:
npm install --save sweetalert2
Now,do I need to require it in \resources\assets\js\bootstrap.js
file in laravel?
It's default content is like this:
window._ = require('lodash');
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
It looks like lodash
,jquery
,bootstrap
,axios
have been required into laravel,but the 4 sentences are different,they are like this:
window._ = require('lodash');
window.$ = window.jQuery = require('jquery');
require('bootstrap');
window.axios = require('axios');
Questions:
1、why do the 4 sentences have differences?
2、I want to require package sweetalert2
,how do I write it?
You should just be able to require
it in your bootstrap.js
file:
require('sweetalert2');
Then (assuming you're using scss
) in your entry .scss file:
@import "node_modules/sweetalert2/src/sweetalert2";
Also, the reason you don't have to manually attach bootstrap
to thewindow
is because it will do it automatically when it's loaded. This is because it's assumed the window
instance will always exist as it's a styling framework. One of the reason the other libraries might not do this is because they can be used in environments where window
isn't defined.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With