l_kreher's avatar

Laravel Mix: correct usage of .js(), .extract(), .babel() and .version()

I'm using Laravel (5.4) Mix to compile the JavaScript assets for my project, with a single assets file that uses require() to load all modules.

So to start off, I want to use mix.js('resources/assets/js/app.js', 'public/js') to compile everything into a main file.

Problem 1: This works for npm run dev, but not for npm run production, where I get the error:

Unexpected character '`' [./~/foundation-sites/js/foundation.util.core.js:24,0][/js/vendor.js:10294,124]

But since I'm not modifying the libraries all that often, I use mix.extract(['lodash', 'modernizr', 'jquery', 'select2', 'jquery-ui', 'jquery-ui/ui/widgets/datepicker', 'foundation-sites']).

Problem 2: The created vendor.js file is not in ES5, but I don't expect I can just do mix.babel('public/js/vendor.js', 'public/js/vendor.js'), at least I can't get it to work at all. How do I apply babel to a generated .js file?

When I get all of these issues fixed, can I simply run mix.version() to have Mix do the cache-busting for me?

app.js:

require('./bootstrap');

bootstrap.js:

window._ = require('lodash');

try {
    window.modernizr = require("modernizr");
    window.$ = window.jQuery = require('jquery');
    require('select2');
    require('jquery-ui');
    require('jquery-ui/ui/widgets/datepicker');

    require('foundation-sites');
} catch (e) {
}
0 likes
1 reply
l_kreher's avatar
l_kreher
OP
Best Answer
Level 1

It turned out both problems were actually the same thing. Problem 1 was caused by the files not being in ES5, so I added

mix.webpackConfig({
    module: {
        rules: [
        {
            test: /\.jsx?$/,
            exclude: /node_modules(?!\/foundation-sites)|bower_components/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: ['env']
                }
            }
        }
        ]
    }
});

Now I don't need mix.babel() anymore, and I can just run .version() on the generated files. Sometimes writing down what the exact problem is helps a lot solving it all by yourself. I'll leave this up here in case someone else runs into the same problem.

Please or to participate in this conversation.