Understanding Laravel Mix
Laravel comes equipped with tools for front-end asset management. Interestingly, though Laravel applications are written in PHP, NodeJS manages assets such as Cascaded Style Sheets (CSS) and JavaScript (Js). In addition, NodeJs Comes with Node Package Manager (NPM) - which is synonymous with Composer in PHP. NPM manages and version-controls all the front-end libraries.
Laravel also come equipped with WebPack - a JavaScript module bundler. Webpack is a highly effective module bundler that prepares JavaScript and assets for the browser. WebPack makes it easy to use JavaScript modules, libraries, bundles and minified JS. Also, WebPack helps in using CSS preprocessors like less, sass, stylus or PostCSS. Webpack allows the developer to use the most recent versions of JavaScript and compiles the code to work on older browsers. However, the downside to Webpack is the steep learning curve.
A thin layer exists on top of the WebPack called the Laravel mix to simplify the management of front-end assets. Laravel Mix exposes fluent API for dynamically constructing Webpack configuration. Laravel Mix makes it a breeze to compile and minify an application's CSS and JavaScript files.
This blog has been written with the help of Laravel experts at Obii Kriationz Web LLP - one of the best Web Development Company in Bangalore Let us dive deeper into the concept of Asset from the Laravel perspective:
Asset Compilation:
Assets are client-side elements required to render the application in its intended form on a browser. Assets include CSS, JS, Images or any other element found inside the 'public' directory of a Laravel application.
These elements might depend on modules, libraries, bundles or others. Since the assortment of tech stacks is abundant, it is tough for a developer to keep track of the versions and compatibility to use and render.
WebPack bundles all the dependent modules and libraries required by the application to render. Laravel Mix provides a fluent API for defining Webpack build steps for a Laravel application using several standard CSS and JavaScript preprocessors.
To talk in layman's terms: Laravel allows asset compilation through Laravel Mix and WebPack to render application front-end with the possibility of using modern JavaScript without worrying about the browser support, extracting any vendor or third-party libraries, thereby improving the site's caching abilities.
How to Install Laravel Mix:
Step 1: Before you try to install Laravel Mix on your environment, makes sure NodeJs and NPM are installed. You can do so by running node -v command on your shell
Step 2: On the shell, run composer create-project laravel/laravel mix --prefer-dist
Step3: Once the package is installed, run npm install
Step 4: To run the Mix
npm run dev --For running all Mix tasks
npm run prd -- For running all Mix tasks and Minify the output.