简体   繁体   中英

Adding NPM javascript library to Laravel 8

I'm using the mobiscroll javascript component library with a new Laravel 8 app I'm building. I've used the trial scripts by simply copying the minified css / js to the public/css and public/js directories of my laravel app, and then pushing the script / css files into the layout's stack .

I'd like to be able to require these more "natively" by installing the module via npm and referencing the module. In a react app I'd have no problem with this-- but how is it done in laravel?

I've tried adding window.mobiscroll = require('@mobiscroll/javascript'); to the bootstrap.js file, since that seems to be how the axios and _ libraries are being made available, but I still am getting Uncaught ReferenceError: mobiscroll is not defined errors when I try to initialize a component.

I also tried adding it to the app.js file like this:

require('alpinejs');
require('@mobiscroll/javascript');

with the same error as before. I am running npm run watch so the mix process is happening and succeeding with each attempt, so I don't think it's simply a problem with caching or compilation.

I didn't see anything that seemed to address this on SO or the laravel docs.

EDIT: having the same issue with dayjs , added via npm i dayjs , added to bootstrap.js using window.dayjs = require('dayjs'); , compiled via mix, cleared all caches, and still getting error dayjs is not defined .

First, install Mobiscroll in your root Laravel folder.

npm install @mobiscroll/javascript-lite --save-dev

Then you want to reference the JS and CSS in the appropriate spots.

In resources/js/bootstrap.js.

try {
    window.mobiscroll = require('@mobiscroll/javascript-lite');

    require('bootstrap');
} catch (e) {
}

In resources/css/app.css.

@import '~@mobiscroll/javascript-lite/dist/css/mobiscroll.css';

If your webpack.mix.js is something like this...

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);

Do an npm run prod .

Make sure you reference your generated CSS file in your Blade template/layout.

<link type="text/css" rel="stylesheet" href="{{ mix('css/app.css') }}">

Also, for JS.

<script src="{{ mix('js/app.js') }}" defer></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM