Drupal 8: where to include common scripts

872 Views Asked by At

I am looking at adding a new javascript library to drupal 8. I want the ability to call this library from other modules / libraries.

The way WordPress does this is by the use of wp_enqueue_scripts. Using a common library would make sure that my library is loading just once.

An existing implementation of this in drupal is the way you can add dependencies into your the yml files

js:
 dependencies:
  - core/jquery

Is there a way I can add my own javascript library as the dependency that can be used throughout my drupal instance (all modules and themes should be able to use this as a dependency)

1

There are 1 best solutions below

3
tompagabor On BEST ANSWER

If you want to add any custom code, you need to create and enable your custom module or theme, where you can define your custom javascript file in the my_module.libraries.yml file, like this:

my_library:
  js:
    dist/js/my_stuff.js: {}
  dependencies:
    - core/jquery

In this case, your custom code is placed in de dist/js folder. Then you should add your library to Drupal. I usually use the my_module.info.yml to define my custom libraries in this way:

libraries:
  - my_module/my_library

You can also use your custom library as a dependency:

my_other_library:
  js:
    dist/js/my_other_stuff.js: {}
  dependencies:
    - core/jquery
    - my_module/my_library

More info about attaching libraries: https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module

More info about *.info.yml file: https://www.drupal.org/docs/8/theming-drupal-8/defining-a-theme-with-an-infoyml-file