Skip to main content
Logo
Overview

UI5 Custom Task Creation and Usage

May 16, 2021
2 min read

Originally published on SAP Community in May 2021.

In UI5 Tooling, a custom task adds extra operations to the build. This demo removes i18n texts that are not used in the project, which saves time when project files are combined from different workspaces and many i18n texts become redundant.

Task configuration

In ui5.yaml, the custom task is registered together with the standard task it runs relative to. Here it runs before replaceCopyright:

builder:
customTasks:
- name: cleanUnusedi18nKeys
beforeTask: replaceCopyright
---
# Task extension as part of your project
specVersion: "2.1"
kind: extension
type: task
metadata:
name: cleanUnusedi18nKeys
task:
path: tasks/cleanUnusedi18nKeys.js

Task file

The task file exports an async function. The workspace object gives access to the project files:

module.exports = async function ({ workspace, dependencies, taskUtil, options }) {
// ...
};

Logic

Each i18n key is searched for in the project files (controllers, fragments, views and the manifest). Keys that are not found are left out of the new i18n file. Every async call is awaited so the steps run in order.

const textResources = await workspace.byGlob("**/*{view.xml,fragment.xml,controller.js,manifest.json}");
const i18nFiles = await workspace.byGlob("**/*.properties");
// ...
await Promise.all(i18nFiles.map(async (i18nFile) => {
// ...
lines = lines.filter((l) => l.found === true);
for (let i = 0; i < lines.length; i++) {
line = lines[i];
i18nString += line.key + " = " + line.value + "\n";
}
i18nString.substring(0, i18nString.length - 2);
await i18nFile.setString(i18nString);
await workspace.write(i18nFile).then(() => console.log('DONE'));
// ...
}));

Result

After ui5 build, the i18n keys that are not used anywhere in the workspace are gone from the build output.

Final words

The full code is on GitHub as a reference for building a custom task, and the API reference covers further requirements. Libraries like Babel or Grunt.js can also be used inside a task.

Custom tasks can format, transpile or lint files before or during the build. Thanks to contributors in the UI5 Ecosystem, many ready-made tasks already cover common needs.