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)
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.ymlfile, like this: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.ymlto define my custom libraries in this way:You can also use your custom library as a dependency:
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