Dwight Watson's blog

Referencing /node_modules with Laravel Mix

This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.

Often when working on your front-end with Laravel Mix you're going to want to import or reference some third-party code you've brought in through NPM/Yarn. Whether it's JavaScript or some stylesheets, it's painful and ugly to go through the whole ../../../node_modules/foo/bar/baz.xyz routine. Luckily, there's a better way.

JavaScript

With JavaScript, Webpack will allow you to start off with the package name and then refer directly to the asset you're after. In the following example I'm pulling the collapse and dropdown modules from Bootstrap simply prefixing the string with the package name bootstrap-sass.

import "bootstrap-sass/assets/javascripts/bootstrap/collapse";
import "bootstrap-sass/assets/javascripts/bootstrap/dropdown";

Sass

With Sass it's a fairly similar process, except that you'll prefix the string with a ~. This just tells Sass you're kicking off the path from node_modules. In this example I'm pulling in Bootstrap and Font Awesome.

@import '~font-awesome/scss/font-awesome';
@import '~bootstrap-sass/assets/stylesheets/bootstrap';

A blog about Laravel & Rails by Dwight Watson;

Picture of Dwight Watson

Follow me on Twitter, or GitHub.