Search code examples
laravelwebpackassetsnpm-installlaravel-mix

laravel mix compile assets from a package in node_modules?


I started using laravel-mix on my new Laravel 5.7 project to compile all the js/css into one file, which will appear in my public js/css directory (one for each page) like this:

mix.js('resources/js/app.js', 'public/js')
   .sass('resources/sass/app.scss', 'public/css')
   .js('resources/js/create.member.js', 'public/js/backend/members')
   .sass('resources/sass/create.member.scss', 'public/css/backend/members')
   .sourceMaps();

Like this I want to keep the views tidy and reduce the number of assets that have to be loaded.

Everything fine so far and I understand how to work with laravel-mix. Now I installed some packages, specifically cropperjs and summernote, via npm, to my node_modules directory.

It fails when I import/require their scss/js to the scripts which are going to be compiled and placed in public by laravel-mix because it seems that these scripts (cropper.js, summernote.scss, etc...) are referencing to other assets across their origin package directory within the node_modules directory (fonts, images, etc...)

For JS I do:

require('../../node_modules/cropperjs/dist/cropper.js');
require('../../node_modules/summernote/dist/summernote.js');

Fors SCSS I do:

@import '~cropperjs/src/css/cropper';
@import '~summernote/src/less/summernote-bs4';

My question is: What is good practice when using packages, installed with npm?

Do I have to put the whole package directory to my public directory? Do I link to the assets in the package directory which is located in the node_modules directory? Or is their any chance left to compile them together with my other assets via laravel-mix/webpack, maybe a flag I'm missing or so? Do I have to use any additional software like bower to make things happen?


Solution

  • For js I just use

    import 'vue'
    import 'cropperjs'
    

    Usually the package documentation will tell you how to import it.