Home > front end >  How do I add a npm package to webpack.mix.js in a Laravel project?
How do I add a npm package to webpack.mix.js in a Laravel project?

Time:02-03

I'm working on a project that I'm taking over and trying to learn everything that's being used in it. I currently need to add an NPM package (slick-carousel) to the project, and I want to add it to the mix.

I installed the package by running npm install slick-carousel and can see it in my node_modules. Now I need to add them to my webpack mix, so I bundle them with everything else, but I'm not 100% on how to do it. I'm relatively new to NPM and a novice with Webpack, so this stumped me slightly.

Below is my webpack.mix file and my failed attempt.

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

 mix.js('resources/js/secret-app.js', 'public/js')
.postCss('resources/css/secret-app.css', 'public/css', [
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
]);

if (mix.inProduction()) {
    mix.version();
}

I tried adding the following:

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

 mix.js('resources/js/secret-app.js', 'public/js',
 [
     require('slick-carousel')
 ])
 .postCss('resources/css/secret-app.css', 'public/css', [
    require('postcss-import'),
    require('tailwindcss'),
    require('autoprefixer'),
    require('slick-carousel')
 ]);

 if (mix.inProduction()) {
     mix.version();
 }

Doing this and running npm run dev results in an error:

ReferenceError: window is not defined at...

I would appreciate it if someone would tell me the correct way to implement the package :)

CodePudding user response:

You would add this in your bootstrap.js file.

import slick from 'slick-carousel/slick/slick';
window.slick = slick;

Or you can use your webpack.mix.js like the following.

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

mix.js('resources/js/secret-app.js', 'public/js')
   .sass('node_modules/slick-carousel/slick/slick.scss', 'public/css')
   .js('node_modules/slick-carousel/slick/slick.js', 'public/js')
   .postCss('resources/css/secret-app.css', 'public/css', [
        require('postcss-import'),
        require('tailwindcss'),
        require('autoprefixer'),
    ]);

if (mix.inProduction()) {
    mix.version();
}
  • Related