JavaScript

Writing JS

The JS for your project is compiled from the files you put in the JS section of your project.

Importing

The entry file is app.js. You can put all your custom JS in that file, or create other files and include them. Let's say you create a file foo/bar.js, then you can include it in app.js as follows:

import 'foo/bar'

Or you can export and import specific variables:

// In foo/bar.js
export function doSomething() {
  ...
}

// In app.js
import { doSomething } from 'foo/bar'

doSomething()

Binding To The window Scope

Be aware that the compiled JS will be included in the page as a module, like this:

<script src="..." type="module"></script>

This means that variables and functions you declare on the global scope in your JS files, are not automatically available on the pages (the window scope). To make something in a JS file available on the pages, you have to explicitly bind it to the window. To illustrate, this is a simple example to make things clear:

<script type="module">
    function foo() {
        alert('foo')
    }

    window.bar = function () {
        alert('bar')
    }
</script>

{{-- ❌ Won't work --}}
<button onclick="foo()">Click Me</button>

{{-- ✅ Will work --}}
<button onclick="bar()">Click Me</button>

External Dependencies

When you want to use external libraries like sliders, Fancybox and so on, you'll have to include external JS. There are 2 options to do this.

CDN

The simplest way is to include JS from a CDN. You can put the tags in your master template, or add them to the scripts stack. If you do this in a file or component you include multiple times, this is the best way to do this:

@once
    @push('scripts')
        <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
    @endpush
@endonce

Skypack (or similar)

Skypack is a fairly new tool that allows you to include optimized npm packages in your JS with no build tools. For example, you can put something like this in a JS file:

import confetti from 'https://cdn.skypack.dev/canvas-confetti'
confetti()

Take a look at the Skypack website for more information.

Compilation

If you change a JS file, the first time you refresh some page of the website, we recompile the JS with Rollup. A little delay can occur during compilation.

In staging environments, no minification will happen. However, when you publish your site to production, all JS is bundled and minified so your production JS is as small as possible.

Including In Your Views

Use the built-in @scripts directive in your master template before your closing </body> tag. It will include the compiled JS for your project automatically:

<html>
    ...
    <body>
        ...
        @scripts
    </body>
</html>
Previous topic
← CSS
Next topic
Helpers →