Laravel Compiling Assets


Laravel Compiling Assets – The Laravel Compiling Assets provides a fluent API for defining webpack make steps for your application using several CSS and javaScript pre-processor.


Laravel Compiling Assets.

Let us understand how to use laravel Compiling Assets.

Function:-

There are following functions available in laravel Compiling Assets.

  • 1. Introduction.
  • 2. Installation & Setup.
  • 3. Running Mix.
  • 4. Working With Stylesheets.
  • 5. Working With JavaScript.
  • 6. Copying Files & Directories.
  • 7. Versioning / Cache Busting.
  • 8. Browsersync Reloading.
  • 9. Environment Variables.
  • 10. Notifications.

1. Introduction.

It provides a fluent API for defining webpack make steps for your laravel application using several CSS and javaScript pre-processor. By using simple method chaining, You can define your assets with pipeline like this:-

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

2. Installation & Setup.

Installing Node

Before triggering Mix, you have to ensure that Node.js and NPM are installed on your machine.

node -v
npm -v

If you are not using vagrant, then you can easily install the latest version of node and NPM.

Laravel Mix

The only remaining step is to install laravel mix. Within a fresh installation of laravel, you will find a package.json file in the root of your directory structure. You can istall the dependencies it references by running this code.

npm install

If you are running your VM on a window host system. You have to run the npm install command with the –no-bin-links switch enabled.

npm install --no-bin-links

3. Running Mix.

Mix is a configuration layer on top of Webpack, so to run your Mix tasks you only need to execute one of the NPM scripts that is included with the laravel package.json file.

npm run dev
npm run production

Watching Assets For Changes

To watching all relevent file for changes, we use npm run watch command will continue running in your terminal.

npm run watch

You can find that in environment Webpacks is not updating when your file changes.

npm run watch-poll

4. Working With Stylesheets.

The webpack.mix.js file is your entry point for all asset compilation. Think of it as a light configuration wrapper around Webpack. Mix tasks can be chained together to define exactly how your assets should be compiled.

Less

We use less method to compile LESS into CSS.

mix.less('resources/assets/less/app.less', 'public/css');

Multiple calls to the less method can be used to compile multiple files.

mix.less('resources/assets/less/app.less', 'public/css')
   .less('resources/assets/less/admin.less', 'public/css');

You want to customize the file name of CSS, You may pass the full path as a second argument.

mix.less('resources/assets/less/app.less', 'public/stylesheets/styles.css');

Sass

The Sass method allows you to compile Sass into Css.

mix.sass('resources/assets/sass/app.scss', 'public/css');

You can also compile multiple sass file like less method.

mix.sass('resources/assets/sass/app.sass', 'public/css')
   .sass('resources/assets/sass/admin.sass', 'public/css/admin');

Additional Node-sass plug-in option may be provided as the third argument.

mix.sass('resources/assets/sass/app.sass', 'public/css', {
    precision: 5
});

Stylus

It is also similar to less and sass. It allows to compile stylus into css.

mix.stylus('resources/assets/stylus/app.styl', 'public/css');

You can also install additional stylus plug-in, such as Rupture

mix.stylus('resources/assets/stylus/app.styl', 'public/css', {
    use: [
        require('rupture')()
    ]
});

PostCSS

It is a powerful tool for transforming your Css, is included with laravel Mix out of box. Install the desired plug-in through NPM and then reference it in your webpack.mix.js
file.

mix.sass('resources/assets/sass/app.scss', 'public/css')
   .options({
        postCss: [
            require('postcss-css-variables')()
        ]
   });

Plain CSS

You want to concatenate some plain CSS stylesheets into a single file, you can use the style method.

mix.styles([
    'public/css/vendor/normalize.css',
    'public/css/vendor/videojs.css'
], 'public/css/all.css');

URL Processing

You may use URL processing for CSS compilation, Webpack will rewrite and optimize any url() call within your stylesheets.

.example {
    background: url('../images/example.png');
}

Source Maps

Source map can be activated by calling the mix.sourceMaps() method in your webpack.mix.js file.

mix.js('resources/assets/js/app.js', 'public/js')
   .sourceMaps();

5. Working With JavaScript.

Mix provides several features to help you work with your JavaScript files, such as compiling ECMAScript 2015, module bundling, minification, and simply concatenating plain JavaScript files. Even better, this all works seamlessly, without requiring an ounce of custom configuration

mix.js('resources/assets/js/app.js', 'public/js');

Using single line of code you can take advantage of:-

ES2015 syntax.
Modules
Compilation of .Vue files.
Minification for production environments.

Vendor Extraction

The vendor library is that it take long term chaining. Like a single update to your application code will force the browser to re-download all your vendor library.

mix.js('resources/assets/js/app.js', 'public/js')
   .extract(['vue'])

The extract methods accept array of all library or modules that you want to extract into a vendor.js

public/js/manifest.js: The webpack manifest runtime
public/js/vendor.js: Your vendor libraries.
public/js/app.js: Your application code.

To avoid javascript code, to load these file in proper way.

<script src="/js/manifest.js"></script>
<script src="/js/vendor.js"></script>
<script src="/js/app.js"></script>

React

Mix can automatically install the Babel plug-ins for React support. It replace your mix.js() call with mix.react().

mix.react('resources/assets/js/app.jsx', 'public/js');

Vanilla JS

It is similar to combining stylesheets with mix.style(), you can also combine and minify any number of javascript files with script() methods.

mix.scripts([
    'public/js/admin.js',
    'public/js/dashboard.js'
], 'public/js/all.js');

Custom Webpack Configuration

The webpack.config.js method is use to get file to you up and running as quickly as possible. You may need to manually modify this file.

Merging Custom Configuration

Mix provide a useful webpackconfig method which allows you to merge any short webpack configuration override. The webpackconfig method accepts an object.

mix.webpackConfig({
    resolve: {
        modules: [
            path.resolve(__dirname, 'vendor/laravel/spark/resources/assets/js')
        ]
    }
});

Custom Configuration Files

If you want completely customize your webpack configuration, copy the node_modules/laravel-mix/setupwebpack.config.js file to your project directory. Then point all of the –config references in your package.json file to the newly copied configuration file.

6. Copying Files & Directories.

The copy method can be used to copy files and directories to new locations. This is useful when a particular asset within your node_modules directory need to be relocated to your public folder.

mix.copy('node_modules/foo/bar.css', 'public/css/bar.css');

When copying a directory, the copy method will flatten the directory structure.

mix.copyDirectory('assets/img', 'public/img');

7. Versioning / Cache Busting.

Many developer suffix their compiled assets with a timestamp or unique token to force browser to load the fresh assets instead of serving stale copies of the code. Mix can handle this to using version method.

This method is automatically append a unique hash to the file name of all compile file.

mix.js('resources/assets/js/app.js', 'public/js')
   .version();

After generating the version file, you want know the exact file name. Then you should use Laravel’s global mix function.

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

Because versonied file are usually unnecessary in development, you may like to instruct the versioning process to only run during npm run production.

Let’s look at a simple example.

mix.js('resources/assets/js/app.js', 'public/js');

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

8. Browsersync Reloading.

BrowserSync can automatically monitor your file for changes and inject your changes in browser without need a manuall refresh. You can enable support by calling the mix.browserSync() method.

Let’s look at a simple example.

mix.browserSync('my-domain.dev');

mix.browserSync({
    proxy: 'my-domain.dev'
});

9. Environment Variables.

You may inject enviromental variable in Mix by prefixing a key in you .env file with MIX_.

MIX_SENTRY_DSN_PUBLIC=http://example.com

After the variable has been defined in your .env file, you can access via the process.env object.

process.env.MIX_SENTRY_DSN_PUBLIC

10. Notifications.

When available, Mix will automatically display OS notifications for each bundle. This will give you instant feedback, as to whether the compilation was successful or not. However, there may be instances when you’d prefer to disable these notifications

mix.disableNotifications();

Advertisements

Add Comment

đź“– Read More