So far in this book, we've only talked about topics that can be considered to relate to backend development. This means heavy PHP working with the APIs and the database, and so on. This is because this book is oriented toward module developers rather than "themers". Also, the author of this book is admittedly not a JavaScript, or any kind of frontend, developer.
Nevertheless, in this chapter we'll switch gears and talk a bit about frontend development, namely, how to work with JavaScript in a Drupal 8 application. This is because there are many things developers can and should be doing in their modules that require frontend technologies. There are a few approaches and techniques specific to Drupal when it comes to adding and using JavaScript files and we will talk about those here. Moreover, we will also prove how powerful Drupal 8 is in allowing us to do quite a bit of JavaScript work without actually writing a single line of JavaScript code.
So, there are a few things we will cover in this chapter.
First, we will talk about the approach of writing JavaScript in Drupal. You already learned in Chapter 4, Theming, how you can create libraries and attach them to render arrays, elements, or pages. Basically, using libraries, we can get our JavaScript files loaded when we need. I recommend you check out the Assets and libraries section from Chapter 4, Theming, if you don't remember exactly how libraries work. Because in this chapter, we will continue from there and talk a bit about what actually goes inside those JavaScript files.
We won't actually write a lot of JavaScript code in the first part—just enough to get you started though. In the second part, we will not write any at all. Instead, we will talk about the robust Ajax API that comes with Drupal and that allows us to build some very dynamic functionalities that rely on JavaScript. To demonstrate how things work, we will revisit our importer functionality that we started in Chapter 7, Your Own Custom Entity and Plugin Types, and improve it using Ajax.
Finally, we will also talk about the States system of the Form API, which allows us to make our form elements dynamic and dependent on others in a declarative way. Again, we won't even have to know any JavaScript to do what is actually quite complex client-side behavior.