How to expose a js variable in global scope with laravel mix (webpack)?

I am using Laravel 5.4's mix tool to build and combine my AngularJS 1 files. Here's my webpack.mix.js for Laravel:

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

Here is the app defination:

'use strict';

var myApp = angular.module('myApp', [
    'ngRoute',
    //...
]);

and here is a directive

myApp.directive('navigation', function () {
    return {
        templateUrl: 'app/modules/layouts/nav.html',
        replace: true
    };
});

The problem is when I build the files and includes them on html I get the error

ReferenceError: myApp is not defined

from the compiled diretives.js file.

I figure out that as mix uses webpack for compiling, and webpack enclose each js file's content in a anonymous function so my myApp variable is only accessible in the compiled app.js file, not in the global scope. When I manually remove the anonymous function from compiled app.js file it works just fine.

So I was wondering if there is a way to make the myApp variable globally accessible though Laravel's mix configuration?

Answers:

Answer

Try inlining the myapp function in HTML script tags instead of putting it in a separate JavaScript file.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.