# Migrating hooks to NativeScript 6.0
As you probably know, NativeScript 6.0 release will [support only bundle workflow](https://www.nativescript.org/blog/the-future-of-building-nativescript-apps) and there will be no other way to run your applications. We're dropping the legacy workflow for building the applications which is a breaking change that alters the hooks mechanism in NativeScript CLI.
But… What are NativeScript hooks?
# NativeScript hooks in short
NativeScript hooks are executable pieces of code or Node.js scripts which can be added by application or plugin developers in order 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. 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. NativeScript CLI determinates 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 `module.exports =` ... statement in the hook. For example, if the hook script is:
```typescript
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 `module.exports = statement`, it will execute the hook using Node.js [childProcess.spawn](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options) function. Using this approach you’re unable to use any of the services from NativeScript CLI.
### hookArgs
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:
```typescript=
@hook("checkForChanges")
public async checkForChanges(platformData: IPlatformData, projectData: IProjectData, prepareData: IPrepareData) { }
```
Then,`hookArgs` will have the following structure:
```json=
hookArgs: {
platformData,
projectData,
prepareData
}
```
> NOTE: `hookArgs` object is different for each hook.
# Do I need to migrate?
Let's see what you, as application developer 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 althought the entire NativeScript CLI was refactored. Here are the main changes around the 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 CLI 6.0.
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 CLI is designed to allow executing of additional actions before and after some specific parts of CLI's code is executed. In case you return concrete value or Promise, the hook is considered as before/after hook.
The hook below will be executed as a before/after hook:
```typescript
module.exports = function($logger) {
return new Promise((resolve, reject) => {
$logger.info("Executed before/after some CLI action/function.");
});
}
```
Here are all hooks supported by NativeScript CLI:
## prepare
This hook is executed exactly before/after NativeScript CLI starts the webpack compilation and the watcher for native files e.g. the actual preparation of the application.
* Using legacy workflow it is executed on initial sync of the application and on every change when NativeScript CLI is started in watch mode.
* In CLI 6.0 the hook is executed only on initial sync of the application.
## checkForChanges
The hook is executed before/after NativeScript CLI checks if there are changes in the application. NativeScript CLI keeps a 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 legacy workflow, but will be executed after it with CLI 6.0.
* Using legacy workflow this hook is executed on initial sync of the application and on every change when NativeScript CLI is started in watch mode.
* In CLI 6.0 this hook is executed on initial sync of the application. NativeScript CLI checks if there are changed native files from the last execution. Native files are all files from App_Resources and from platforms folders of the nativescript's plugins. NativeScript CLI rebuilds the application when there are changed native files.
## before-preview-sync
When preview command is executed, 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 NativeScript CLI tries to determine the glob patterns for watching the application. The purpose here is that you can modify the patterns in case you want to watch additional directories or exclude directories from watch.
## before-watch
This hook is executed exactly before NativeScript CLI starts the watch of the project directory.
## after-watch
This hook is executed when 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 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 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 NativeScript CLI had decided if it needs to prepare any part of the application. The hook is deleted as from NativeScript 6.0.
## cleanApp
This hook is executed before/after NativeScript CLI cleans the app directory in the platforms directory. It is deleted as from 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 `checkForChanges` hook in our plugin or application. Currently the structure of `hookArgs` for `checkForChanges` hook is the following:
```json=
{
checkForChangesOpts: {
platform,
projectData,
projectChangesOptions: {
nativePlatformStatus,
provision,
teamId,
bundle,
release
}
}
}
```
With the upcoming 6.0 release the above structure will be changed to the following:
```json=
{
projectData,
platformData,
prepareData
}
```
Let's see the case when the hook uses platform property from `hookArgs`:
```javascript=
module.exports = function(hookArgs) {
const platform = hookArgs.checkForChangesOpts.platform;
console.log(`The hook will be executed for ${platform} platform.`);
}
```
For the NativeScript 6.0 the above code have to be changed to:
```javascript=
module.exports = function(hookArgs) {
const platform = hookArgs.prepareData.platform;
console.log(`The hook will be executed for platform ${platform}.`);
}
```
You can easly make it backwards and forwards compatible:
```javascript=
module.exports = function(hookArgs) {
const platform = (hookArgs.checkForChangesOpts && hookArgs.checkForChangesOpts.platform) || (hookArgs.prepareData && hookArgs.prepareData.platform);
}
```
We've already migrated the following hooks and make them backward and forward compatible:
* [nativescript-vue](https://github.com/nativescript-vue/nativescript-vue/tree/master/platform/nativescript/hooks)
* [nativescript-babel](https://github.com/NativeScript/nativescript-dev-babel/blob/master/lib/after-prepare.js)
* [nativescript-unit-test-runner](https://github.com/NativeScript/nativescript-unit-test-runner/blob/master/lib/after-prepare.ts)
* [nativescript-plugin-firebase](https://github.com/EddyVerbruggen/nativescript-plugin-firebase/tree/master/src/scripts)
* [kinvey-nativescript-sdk](https://github.com/Kinvey/js-sdk/tree/master/packages/nativescript-sdk/nativescript-hook-scripts)
Here is a full mapping for all hooks that NativeScript CLI supports:
<table width="0">
<tr>
<th></th>
<th>HookArgs prior 6.0</th>
<th>HookArgs for 6.0</th>
<th>Status</th>
</tr>
<tr>
<td> prepare </td>
<td> { config } </td>
<td> { prepareData } </td>
<td> <span style="color:orange"> CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#prepare">here.</a></td>
</tr>
<tr>
<td> checkForChanges </td>
<td> { platform, projectData, projectChangesOptions } </td>
<td> { platformData, projectData, prepareData } </td>
<td> <span style="color:orange"> CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#checkForChanges">here.</a></td>
</tr>
<tr>
<td> before-preview-sync </td>
<td> { projectData, hmrData, config, externals } </td>
<td> { platform, projectDir, useHotModuleReload, env } </td>
<td> <span style="color:orange"> CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#watch">here</a></td>
</tr>
<tr>
<td> watchPatterns </td>
<td> { liveSyncData, projectData } </td>
<td> { platformData, projectData } </td>
<td> <span style="color:orange"> CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#watchPatterns">here</a></td>
</tr>
<tr>
<td> before-watch </td>
<td> { projectData, config, filesToSync, filesToRemove, hmrData } </td>
<td> { platformData, projectData, prepareData } </td>
<td> <span style="color:orange"> CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#watch">here</a></td>
</tr>
<tr>
<td> after-watch </td>
<td colspan="2"> { projectData } </td>
<td> <span style="color:green"> NOT CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#watch">here.</a></td>
</tr>
<tr>
<td> after-createProject </td>
<td colspan="2"> { projectCreationSettings } </td>
<td> <span style="color:green"> NOT CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#after-create">here.</a></td>
</tr>
<tr>
<td> beforeAndroidPlugin </td>
<td colspan="2"> { pluginBuildSettings } </td>
<td> <span style="color:green"> NOT CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#beforeAndroidPlugin">here.</a></td>
</tr>
<tr>
<td> install </td>
<td colspan="2"> { packageFilePath, appIdentifier } </td>
<td> <span style="color:green"> NOT CHANGED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#install">here.</a></td>
</tr>
<tr>
<td> shouldPrepare </td>
<td> { shouldPrepareInfo } </td>
<td> - </td>
<td> <span style="color:red"> HOOK DELETED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#shouldPrepare">here.</a></td>
</tr>
<tr>
<td> cleanApp </td>
<td> { platformInfo } </td>
<td> - </td>
<td> <span style="color:red"> HOOK DELETED </span> <br /> More info can be found <a href="https://hackmd.io/O6PlaaA3RY23B04SJm7qPA?both#cleanApp">here.</a></td>
</tr>
</table>
> NOTE: If your hook is in category <span style="color: orange"> CHANGED </span> and uses `hookArgs` you need to migrate the hook.
> NOTE: If your hook is in category <span style="color: green"> NOT CHANGED </span> you still have to check the names of injected services from within the hook.
> NOTE: If your hook is in category <span style="color: red"> DELETED </span> you can open an issue and describe what exactly is your scenario, so we can help you to find the appropriate hook for your case.
# Injected services from NativeScript CLI
NativeScript CLI provides a very powerfull `in-process` execution of hooks that allow you to use any registered services from NativeScript CLI available in injector. A full list of can be found [here](https://github.com/NativeScript/nativescript-cli/blob/master/lib/bootstrap.ts). The current resolution mechanism works based on the names, not the object types. In case the injected service is deleted or renamed from NativeScript CLI and the hook is not migrated according to that change, NativeScript CLI will not execute the hook and will show a warning.
Let's see a hook with the following injected services:
```javascript=
module.exports = function($logger, $platformsData, $projectData, hookArgs) { }
```
The above hook will not be executed with NativeScript CLI 6.0, as it will not be able to resolve `$platformsData` due to the fact that `$platformsData` is renamed to `$platformsDataService`.
> NOTE: NativeScript CLI will show the following warning: <hookName> will NOT be executed because it has invalid arguments - $platformsData.
In such a case, we need to migrate the hook:
```javascript=
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: `$logger.out` method is deleted in NativeScript 6.0 and is replaced with `$logger.info`.
# Summary
That's all 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 CLI 5.4 and 6.0 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](https://github.com/NativeScript/nativescript-cli/issues) discribing your problem and we'll assist you to find a solution!