Progressive Decoupling 2: A How To Guide
Not really. It turns out that it is enough to place the package.json file from core/ two levels up in the directory tree (in case of a composer project) and adjust paths to scripts to enjoy modern JS in contrib and custom code. With this file in the repository root we can run
to install dependencies, and we’re good to go with ES6.
will start the watcher, which monitors all .es6.js files and transpiles them to their .js counterparts whenever a change is detected.
The scripts can be invoked in one of 4 ways
To commit or not to commit?
Is it fine to commit the output (.js) files? That depends on the nature of the code. If it’s a contrib module / theme it’s best to do so. Target users shouldn’t be forced to transpile themselves and the build process of Drupal modules is not adjustable at the time off writing this post.
Contrib modules would most likely provide just the optimized code (without source maps). The committed source .es6.js files can be used to overwrite the output files with dev features enabled for individual environments if needed.
The choice here depends on the hosting platform. If it supports adjusting the build process based on the environment, then the .js files don’t have to be committed at all. The source files are enough and the compilation can be done before each deployment. Source maps can be used for dev and prod should get the optimized build. This is how it looks like in an .amazee.io.yml file for instance:
As with every artifact, ruling out the compiled versions of js files from the repository makes the development process smoother, mainly by reducing conflicts. On the other hand, it doesn’t have to be a big problem if the team is small enough.
Here’s a recipe for adding an example ES6 library to a theme.
- Add this package.json file the root of your project
- Install dependencies
- Start the file watcher
- Add a library definition to package_name.libraries.yml in your module or theme.
- Create the index file (js/mylib/index.es6.js)
- Save the file and check the terminal window with the file watcher, js/mylib/index.es6.js should be mentioned there and the compiled version - index.js - should be created next to the source file. The library is now ready to be used in a module or theme.
That’s it for setting up ES6 in a project. In the next post we’ll take a look at polyfills, talk about the fetch API and a see how to use async functions - the undeniable game changer from ES8.
If you want to learn more about Drupal libraries check these out