« Back

Adding Flexibility to Your Themes Through Gulp Hooks

Technical Blogs May 14, 2018 By Alexander Valencia Staff

I recently took an online course to learn more about TypeScript, a superset of JavaScript that provides optional static typing, classes, interfaces, and much more. Whenever I'm in the process of  learning a new language/framework/etc. I find it helpful to experiment in a setting I'm already familiar with, where I can  add that new thing a little at a time. Since I work with Liferay themes on a daily basis, I thought it would be a fun experiment to use TypeScript for a theme's main.js file.

At first, I had to compile my TypeScript then move the compiled js file over to the src/js folder in my theme. After doing this a few times I found myself wondering, "there's got to be an automated way to do this." And, there is! Using the example of our liferay-theme-es2015-hook I was able to create a hook that would add TypeScript compilation to the build process; you can see the finished hook here. I'll be using my TypeScript hook as an example of how you could further add custom flexibility to your theme building process.

To create the hook, the first thing to do is initialize a new npm project using npm init to generate and add the necessary fields to the package.json. Next, add the depdencies we'll need  for developing our hook, gulp and liferay-theme-tasks:

npm install --save-dev gulp liferay-theme-tasks

Next create an index.js where the custom gulp tasks will reside.

Depending on what extra processes you would like to add to your theme build, the following steps would be slightly different; adjust for your own project as needed.

Here's the index.js file of the liferay-theme-typescript-hook; let's break down what's happening here.

We've added a few more depenedencies to our hook, gulp-typescript, run-sequence, and typescript. Add the dependencies you need using require statements then export the function for use by the liferay-theme-tasks hook using the standard module.exports.

Next, we'll create the gulp.task we'll want to be picked up and ran in our gulp build/deploy process. In the example, I've created a task called 'typescript:compile' that will be called by the hook.

Finally we tell the hook where to insert the task in the process, since this has to do with my main.js/ts in my src folder I've pointed to 'after:build:src' for further examples you can see the gulp.hook() sequences in the es2015 hook.

And that's it! Now, to make this available for either personal or public use we need to do one of the following: for personal use, from the hook's root folder call npm link to make the npm package available on your system. For public usage simply use npm publish to add your package to the npm public registry.

If you'd like to try the TypeScript hook locally, I've put clear instructions with examples on the repository.

Have fun expanding your theme building workflow!

No comments yet. Be the first.