Laravel import custom javascript file using webpack mix

I am trying to define javascript functions in my Laravel 5.4 project (with Laravel template). I have a custom.js file with functions.

function displayDef(){
    $("#worddef").html("Yippee");
}

      

This file is included in assets via webpack.mix.js and is correctly located in frontend.js after compilation.

Problem:

function undefined: Uncaught ReferenceError: displayDef is not defined

The function is present in the compiled js file:

 /* 36 */
    /***/ (function(module, exports, __webpack_require__) {

    /* WEBPACK VAR INJECTION */(function($) {/* 
     * Local functions
     *
     */

    function displayDef() {
    ...

      

I have no idea how I can access these functions. Also if I try to put it in another file:

.js([
    'resources/assets/js/chinese.js'
], 'public/js/vendor.js')

      

I just get a second identical file.

I am very surprised that there is no answer on this topic: how to correctly define and access javascript functions in laravel 5.4 using mix?

+3


source to share


1 answer


Function

js()

c is mix

used to compile the file associated with the module.

From the Laravel site:

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

      

With this single line of code, you can now take advantage of:

  • ES2015 syntax.
  • Modules
  • Compiling .vue files.
  • Minimization for production environments.


If this function is in legacy javascript, you can use the function script

to compile it.

This option is especially useful for legacy projects where you don't need Webpack compilation for your JavaScript.

More details here: https://laravel.com/docs/5.4/mix#working-with-scripts

+1


source







All Articles