Triad Triad - 3 months ago 7
Javascript Question

Drupal 8 Multiple Custom Modules Using Same External JS Lib (e.g. Angular)

I've been pulled onto a Drupal 8 project with multiple custom modules that need to use Angular.js. What is the best way to provide the Angular files to each module?

Right now, each module references the remote Angular files hosted by googleapis.com in

my-module.libraries.yml
.

my-module:
version: 1.x
js:
https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js: { type: external, minified: true }
https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-sanitize.min.js { type: external, minified: true }
js/my-module.js: {preprocess: false}
dependencies:
- core/jquery
- core/jquery.ui
- core/jquery.ui.accordion


However, I would prefer to host the Angular files locally and list them as dependencies just like jQuery.

I know I could put the Angular files in the module itself, but then each module would need its own copy.

Whatever is the proper way to do it, my goal is to host the Angular files locally and reference them from each module that depends on Angular.

Answer

The simplest way to solve this is to add a /libraries folder at the root of the Drupal project. Then create a sub-directory for each external library you are using, and reference that from your module.libraires.yml file.

For example, I created /libraries/angular/js, placed the files in there, and then referenced them by starting with a / in the code below.

my-module:
  version: 1.x
  js:
    /libraries/angular/js/angular.min.js: {}
    /libraries/angular/js/angular-sanitize.min.js: {}
    js/my-module.js: {}
  dependencies:
    - core/jquery

Now any module within the project can reference the same files.

Comments