Triad Triad - 1 year ago 34
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 in


version: 1.x
js: { type: external, minified: true } { type: external, minified: true }
js/my-module.js: {preprocess: false}
- 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 Source

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.

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

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