简体   繁体   中英

Laravel import javascript custom file with webpack mix

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

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

This file is included in the assets via webpack.mix.js and is properly found in the frontend.js after compilation.

Problem:

the function is 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've no idea how I'm supposed to 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'm quite surprised there is no topic answered about that: how to properly define and access javascript functions in laravel 5.4 with mix?

js() function in mix is used to compile the module bundled file.

From Laravel site :

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

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

  • ES2015 syntax.
  • Modules
  • Compilation of .vue files.
  • Minification for production environments.

If this function is in legacy javascript, you can use script function to compile it.

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

For more check here : https://laravel.com/docs/5.4/mix#working-with-scripts

In your project root directory, run the update

npm update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM