0

I'm having some trouble using custom JavaScript function within Laravel 5.6 and can't figure out what I'm doing wrong.

I have a custom file created in /assets/js/ labeled helpers.js with the following function:

export const isBetween = function(n, a, b) {
    return (n - a) * (n - b) <= 0
};

Then, in app.js I imported the file:

import { isBetween } from './helpers.js';

If I do console.log(isBetween(20, 1, 40) inside app.js, it works properly. However, I can't execute inside my blade template; the console log says it's not defined. E.g.:

<script type="text/javascript">
    jQuery(document).ready(function($) {
        console.log(isBetween(20, 1, 40));
    });
</script>

2 Answers 2

3

We use import in ES6/ES5 to import specific modules. But if you want to use it outside of your app.js, then you must make it a global variable like so:

window.isBetween = isBetween; // add this in helpers.js

Sign up to request clarification or add additional context in comments.

2 Comments

Great, that solved my problem so I'll accept it as the answer, but I'm curious if this is the best practice for a Laravel application?
Well, it's perfectly fine to have global variables if you have 2 separate scripts (app.js and say another) that are interdependent. All you have to make sure is that they don't conflict with other JS scripts or libraries. Typically, well written libraries encapsulate most variables, so I dont think you will have to worry about this. But if you want to be really cautious you can namespace it like so: window.myAppName = {}; window.myAppName.isBetween = isBetween and in your JQuery use myAppName.isBetween(....). That way all your global functions can share your app namespace
0

If you're running mix in a terminal with npm run watch and you're still experiencing this issue then double check to make sure you're including the mix'd assets on your blade template:

<script src="{{ mix('js/app.js') }}"></script>

Also, make sure that this <script> tag is above any of your other JS scripts.

1 Comment

Thanks for the comment, but yes, I am running npm run watch and app.js is above my other scripts. I am using <script type="text/javascript" src="{{ asset('js/app.js') }}"></script> instead of mix(), but I tried that as well and didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.