Declaring global helper functions and understand the namespace when using laravel-mix / webpack

I am totally new to webpack (i previously built my apps by including tons of css / js files by "hand") and am now trying to understand how namespaces work when working with the named tools.

i have an app.js

require('./bootstrap');

require('./helperFunctions');

/* ... more, unrelated stuff */

webpack.mix.js is untouched from the original file delivered with the laravel 5.5 sample project

let mix = require('laravel-mix');

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

my helperFunctions.js is a simple js file with some helpful functions i want to use throughout my project:

function foo_bar(A, B) {
    return A - B;
}

/* more functions, following the same structure... */

but everytime i try to use one of the functions defined in the helperFunctions file i find that they are "undefined", even in the app.js file directly after the 'require' happens.

after inspecting the generated app.js file i found that my functions are encapsulated in an anonymous function function(module, exports) { /* my File contents go here */ }, resulting in them being unavailable to the rest of the scripts.

while i understand that this is propably there to reduce polluting the global namespace, i dont understand how i am supposed to define global objects (such as data Storage objects for vue) or functions such as helper functions.

can anybody explain how this is supposed to work, or link me to a ressource explaining this for someone who never worked with an asset compiler (if this is even the right terminus).

cheers

// Edit: i think i found a solution, after stumbling over this: https://nodejs.org/api/modules.html#modules_modules

I editted the helper functions file to something like this:

module.exports = {
    foo_bar(A, B) {
        return (A - B);
    },

    /* ... more functions ... */
}

And imported it wherever i need it like this:

import HelperFunctions from './helperFunctions'

var result = HelperFunctions.foo_bar(5, 8);

However, this only works in files which are pre packed using webpack. is registering the component under window.HelperFunctions the only way to make them available in dynamically generated <script></script> tags throughout the website?

Answers:

Answer

Registering your helper methods on the window object, as you kind of suggested, is a simple and easy to understand approach, so that's what I would choose to do if I wanted these methods to be available globally.

window.myHelperMethod = function () { console.log('ayo, this works!') }

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.