How can an external JS library be integrated into Drupal for use within a custom Ckeditor4 plugin?
My custom plugin needs to set a javascript cookie each time I click on the plugin icon and unset when I close the plugin dialog.
I attempted to use JQuery which didn't work and when I googled the issue, I found a post saying the jquery-cookie is being replaced with js-cookie.
I attempted to install js-cookie and tried the following example:
(function ($, Drupal, drupalSettings, CKEDITOR, Cookies) {
Cookies.set('foo', 'bar')
})(jQuery, Drupal, drupalSettings, CKEDITOR, window.Cookies);
but got the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'set')
I'm not sure if it's becuase of the way I attached the JS-Cookie library.
The following are the steps I took to attach the library.
I used a composer plugin to require js-cookie into my custom module. My composer.json is as follows:
{
"name": "my/module",
"description": "Custom module ckeditor4 plugin",
"authors": [
{
"name": "my-name",
"email": "[email protected]"
}
],
"repositories": [
{
"type": "composer",
"url": "https://asset-packagist.org"
}
],
"extra": {
"installer-types": [
"npm-asset",
"bower-asset"
],
"installer-paths": {
"libraries/asset-packagist/{$name}": [
"type:npm-asset",
"type:bower-asset"
]
}
},
"require": {
"oomphinc/composer-installers-extender": "^2.0",
"npm-asset/js-cookie": "^3.0",
"npm-asset/cookie": "^0.5.0"
}
}
Which downloads the required library into the following directory structure from the root of the module code base:
libraries
├── asset-packagist
│ ├── cookie
│ └── js-cookie
At this point I am able to create an entry in my_module.libraries.yml using the following:
js-cookie:
js:
libraries/asset-packagist/js-cookie/dist/js.cookie.min.mjs: {}
dependencies:
- core/jquery
- core/drupalSettings
. . . and attach the library to a form using the following hook_form_alter implementation:
function my_module_form_alter(&$form, &$form_state, $form_id) {
$form['#attached']['library'][] = 'my_module/js-cookie';
}
And I confirmed the js-cookie library is sucessfully loaded in the HTML: