Home:ALL Converter>Drupal 8 - I cannot call a function in another JavaScript file

Drupal 8 - I cannot call a function in another JavaScript file

Ask Time:2021-09-22T05:37:31         Author:Charly

Json Formatter

I have two JavaScript files on my custom theme. One file has functions that need to be used on the other file. What I have below doesn't work. This is the error I get.

Uncaught ReferenceError: test is not defined.

jQuery will be used on both files.

file1.js

/**
 * @file
 * UI behaviors
 */

(function ($, Drupal) {

 'use strict';

  $(document).ready(function () {
    function test(){
     console.log('hello'):
    }
  });

})(jQuery, Drupal);

file2.js

/**
 * @file
 * UI behaviors
 */

(function ($, Drupal) {

  'use strict';

  $(document).ready(function () {
     test();
  });

})(jQuery, Drupal);

customtheme.libraries.yml

scripts:
  js:
    js/file1.js: {}
    js/file2.js: {}

customtheme.info.yml

libraries:
 - 'customtheme/scripts'

Author:Charly,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275825/drupal-8-i-cannot-call-a-function-in-another-javascript-file
yy