megclaypool
4/15/2020 - 5:54 PM

JavaScript Error -- "Uncaught ReferenceError: Drupal is not defined"

[JavaScript Error -- "Uncaught ReferenceError: Drupal is not defined"]

What it looks like

We get multiple console warnings containing Uncaught ReferenceError: Drupal is not defined (in Safari, the error is ReferenceError: Can't find variable: Drupal)

Why this is happening

It turns out, there's a warning for every javascript file being loaded on the page which is using

jsfunction ($, Drupal) {
  ...
  Drupal.some_function...
  ...
}

How to fix it

We need to make sure that the Drupal javascript object is available on any page which is calling a javascript file which uses the Drupal object. (Duh). There's an easy mechanism for doing this: dependencies!

We load javascript files by adding them to radicati_d8.libraries.yml. We just have to make sure that any javascript file that uses the Drupal object has core/drupal listed as a dependecy.

ex:

dropdown-menu:
  version: 1.x
  js:
    patterns/_patterns/20-molecules/28-menu/menu-dropdown.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupal