Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require npm packages after installing it in Laravel?

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?

like image 283
zwl1619 Avatar asked Mar 09 '23 02:03

zwl1619


1 Answers

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!

like image 181
Rwd Avatar answered Mar 11 '23 15:03

Rwd