Back to Blog Home
← all posts

Migrating CLI Hooks to NativeScript 6.0

July 9, 2019 — by Fatme Zeyneva

As you might know, the upcoming NativeScript 6.0 release only supports bundled builds, and you will no longer be able to run your apps without using webpack. These workflow changes also affect the hooks mechanism in the NativeScript CLI.

In this article we’ll look at what NativeScript hooks are, and how you can migrate your hooks to work the NativeScript 6.0 CLI.

NativeScript hooks in short

NativeScript hooks are executable pieces of code or Node.js scripts, which can be added by app or plugin developers to customize the execution of particular NativeScript commands. They give you the power to perform special activities by plugging in different parts of the build process of the application. The NativeScript CLI supports two different ways of executing hooks:

  • In-process execution
  • Spawned execution via Node.js spawn function

In-process execution of hooks

In-process execution is available only for JavaScript hooks. The NativeScript CLI determines if the hook should be executed in-process based on the module.exports statement. So in order to enable in-process execution all you need to have is a  module.exports = ... statement in the hook. For example, if the hook script is:

module.exports = function($logger) { }

Then, the hook script will be require'd by the CLI, and the exported function will be called through the injector. The in-process execution gives you the flexibility to use any available service from NativeScript CLI.

spawned execution of hooks

If NativeScript CLI cannot find a module.exports = statement, it will execute the hook using a Node.js childProcess.spawn function. When using this approach you’re unable to use any of the services from the NativeScript CLI.

hookArgs

The NativeScript CLI supports a special argument named hookArgs. The hookArgs is an object containing all the arguments passed to the hooked method. For example, let's say NativeScript CLI has a method checkForChanges with the following definition:

@hook("checkForChanges")
public async checkForChanges(platformData: IPlatformData, 
projectData: IProjectData, prepareData: IPrepareData) { }

Then,hookArgs will have the following structure:

hookArgs: {
    platformData,
    projectData,
    prepareData
}

NOTE: The hookArgs object is different for each hook.

Do I need to migrate?

With this background in mind, let's look at what you, the app or plugin developer, need to do to migrate your hooks to NativeScript 6.0.

If your application or plugin doesn't use hooks, there is no need to migrate and no additional actions are required. You can stop reading now.

If your application or plugin has hooks, you need to check if your hooks are affected from the changes for NativeScript 6.0.

What are exactly the changes in NativeScript hooks?

NativeScript CLI 6.0 will NOT change the way the hooks are loaded, processed and executed, however, the entire NativeScript CLI was refactored, and this refactoring might affect your hooks. Here are the main changes related to hooks:

  • The hooks workflow
  • The structure of hookArgs
  • The names of injected services from NativeScript CLI

NOTE: The changes about the structure of hookArgs and the names of injected services affects only in-process hooks.

You can safely skip the next two sections in the following cases:

  1. You're an application developer and all your hooks are from plugins. In this case you should update to the latest version of the plugins and log an issue in plugin's repo if there is a plugin that is still not compatible with the 6.0 CLI.
  2. You're an application developer and all your custom hooks are missing the module.exports = statement, e.g. the hooks will NOT be executed in-process.
  3. You're a plugin developer and all your hooks are marked with { inject: false } inside package.json of the plugin, e.g. the hooks will NOT be executed in-process.

The hooks workflow

The hooks mechanism in the NativeScript CLI is designed to allow executing additional actions before and after some specific parts of CLI's code is executed. In case you return concrete value or a Promise, the hook is considered as a before/after hook.

The hook below will be executed as a before/after hook:

module.exports = function($logger) {
    return new Promise((resolve, reject) => {
        $logger.info("Executed before/after some CLI action/function.");
    });
}

Here are all hooks supported by the NativeScript CLI:

prepare

This hook is executed exactly before/after the NativeScript CLI starts the webpack compilation and the watcher for native files, e.g. the actual preparation of the application.

  • When using the legacy workflow it is executed on the initial sync of the application, and on every change when the NativeScript CLI runs in watch mode.
  • In the 6.0 CLI the hook is executed only on the initial sync of the application.

checkForChanges

The hook is executed before/after the NativeScript CLI checks if there are changes in the application. The NativeScript CLI keeps the state of application and, based on this state, decides if the application should be rebuilt, reinstalled or restarted on device. The hook is executed before prepare hooks using the legacy workflow, but will be executed after it with 6.0 CLI.

  • Using the legacy workflow this hook is executed on the initial sync of the application and on every change when NativeScript CLI runs in watch mode.
  • In the 6.0 CLI this hook is executed on the initial sync of the application. The NativeScript CLI checks if there are changed native files from the last execution. Native files are all files from the App_Resources and platforms folders. The NativeScript CLI rebuilds the application when there are changed native files.

before-preview-sync

When the preview command is executed the NativeScript CLI shows a QR code. This hook is executed when the QR code is scanned with device and the device is reported to the CLI.

watchPatterns

This hook is executed exactly before the NativeScript CLI tries to determine the glob patterns for watching the application. The purpose here is that this allows you to alter the patterns in case you want to watch additional directories or exclude directories from watch.

before-watch

This hook is executed exactly before the NativeScript CLI starts the watch of the project directory.

after-watch

This hook is executed when the NativeScript CLI stops watching the project directory. This can happen in the following cases:

  • When you press Ctrl+C in the terminal where NativeScipt CLI is running
  • When all devices for the LiveSync process are disconnected
  • When there is a problem with the LiveSync process and the NativeScript CLI is unable to livesync the changes.

after-createProject

This hook is executed after creating the project from template.

buildAndroidPlugin

This hook is executed before/after building the .aar of the Android plugin.

install

This hook is executed before/after the application is installed on connected device or emulator/simulator.

shouldPrepare

This hook is executed before/after the NativeScript CLI decides if it needs to prepare any part of the application. The hook was deleted in NativeScript 6.0.

cleanApp

This hook is executed before/after the NativeScript CLI cleans the app directory in the platforms directory. This hook was deleted in NativeScript 6.0.

The structure of hookArgs

The hookArgs is an object containing all the arguments of the hooked method. More info can be found here.

NOTE: hookArgs object is different for each hook.

For example, let's say we have a checkForChanges hook in our plugin or application. Currently the structure of hookArgs for checkForChanges hook is the following:

{
    checkForChangesOpts: {
        platform,
        projectData,
        projectChangesOptions: {
            nativePlatformStatus,
            provision,
            teamId,
            bundle,
            release
        }
    }
}

With the upcoming 6.0 release, the above structure will be changed to the following:

{
    projectData,
    platformData,
    prepareData
}

Let's see the case when the hook uses platform property from hookArgs:

module.exports = function(hookArgs) {
    const platform = hookArgs.checkForChangesOpts.platform;
    console.log(`The hook will be executed for ${platform} platform.`);
}

In NativeScript 6.0, the above code needs to change to:

module.exports = function(hookArgs) {
    const platform = hookArgs.prepareData.platform;
    console.log(`The hook will be executed for platform ${platform}.`);
}

You can easily make the code backwards and forwards compatible as follows:

module.exports = function(hookArgs) {
    const platform = (hookArgs.checkForChangesOpts && hookArgs.checkForChangesOpts.platform) || (hookArgs.prepareData && hookArgs.prepareData.platform);
}

We've already migrated the following hooks to make them backward and forward compatible:

Here is a full mapping for all hooks that the NativeScript CLI supports:

HookArgs prior 6.0 HookArgs for 6.0 Status
prepare { config } { prepareData } CHANGED
More info can be found here.
checkForChanges { platform, projectData, projectChangesOptions } { platformData, projectData, prepareData } CHANGED
More info can be found here.
before-preview-sync { projectData, hmrData, config, externals } { platform, projectDir, projectData, useHotModuleReload, env } CHANGED
More info can be found here.
watchPatterns { liveSyncData, projectData } { platformData, projectData } CHANGED
More info can be found here.
before-watch { projectData, config, filesToSync, filesToRemove, hmrData } { platformData, projectData, prepareData } CHANGED
More info can be found here.
after-watch { projectData } NOT CHANGED
More info can be found here.
after-createProject { projectCreationSettings } NOT CHANGED
More info can be found here.
beforeAndroidPlugin { pluginBuildSettings } NOT CHANGED
More info can be found here.
install { packageFilePath, appIdentifier } NOT CHANGED
More info can be found here.
shouldPrepare { shouldPrepareInfo } - HOOK DELETED
More info can be found here.
cleanApp { platformInfo } - HOOK DELETED
More info can be found here.

NOTE: If your hook is in category CHANGED and uses hookArgs, you need to migrate the hook.

NOTE: If your hook is in category NOT CHANGED, you still have to check the names of injected services from within the hook.

NOTE: If your hook is in category DELETED, you can open an issue and describe your scenario so we can help you to find the appropriate hook for your case.

Injected services from NativeScript CLI

The NativeScript CLI provides a very powerfull in-process execution of hooks that allows you to use any registered services from NativeScript CLI available in the injector. A full list of can be found here. The current resolution mechanism works based on names, and not object types. In case the injected service is deleted or renamed from NativeScript CLI, and the hook is not migrated according to that change, the NativeScript CLI will not execute the hook and will show a warning.

Let's see a hook with the following injected services:

module.exports = function($logger, $platformsData, $projectData, hookArgs) { }

The above hook will not be executed with NativeScript 6.0 CLI, as it will not be able to resolve $platformsData due to the fact that $platformsData is renamed to $platformsDataService.

NOTE: The NativeScript CLI will warn you that hooks will NOT be executed because it has invalid arguments - $platformsData.

In such a case, we need to migrate the hook:

module.exports = function($logger, $projectData, $injector, hookArgs) {
    const platformsData = getPlatformsData($injector);
}

function getPlatformsData($injector) {
    try {
        return $injector.resolve("platformsData");
    } catch (err) {
        return $injector.resolve("platformsDataService");
    }
}

Here is a mapping with the most frequently injected services from NativeScript CLI:

Service name prior 6.0 Replacement in 6.0
$platformsData $platformsDataService
$liveSyncService $runController
$platformService $runController
$projectData $projectData
$logger $logger

NOTE: The $logger.out method is deleted in NativeScript 6.0 and is replaced with $logger.info.

Summary

That's all the changes around hooks for NativeScript 6.0 release. We encourage you to migrate your hooks and make them backwards compatible. This way, in case you are a plugin author, other developers will be able to use your plugins with both 5.4 and 6.0 CLIs, and you'll not force them to upgrade their existing applications. Handling breaking changes can be annoying, but we are here and will help you to make the transition smoother. Just create a new issue describing your problem and we'll assist you to find a solution!