Juarrow
Juarrow

Reputation: 2384

Add custom build/prepare step to project

I have an ionic app targeting Android and iOS.

What i want to achieve, but i'm unsure about how to do, is being able to specify a command line flag when building/preparing the code for both platforms. My first goal would be to replace a resource with another one - in this case an image - used only for test versions (Like replacing the release icon with the beta icon).

How to do this? And is it even possible using ionic build/prepare?

Upvotes: 1

Views: 134

Answers (1)

Juarrow
Juarrow

Reputation: 2384

Using Ionic Hooks (kudos @sebaferreras) i managed to get it working as follows:

  1. Add the hooks to ionic.config.json:

    "hooks": { "build:before": "./scripts/build-before.js", "serve:before": "./scripts/serve-before.js" }

  2. Create the hook scripts & resources to use. (E.g. a simple hook script for ionic build - without checks, for simplicity:

module.exports = function(ctx)
{
  // Use console.log(ctx); to print the context to the console when running 'ionic build/serve'

  const projectDir = ctx.project.dir;

  if(isDevBuild(ctx))
  {
    useDevelopmentImage(projectDir);
    console.log('Using development logo.');
  }
  else
  {
    useProductionImage(projectDir);
    console.log('Using production logo.');
  }
};

function isDevBuild(context)
{
  if(context.build.prod)
    return false;

  return true;
}

function useDevelopmentImage(projectDir)
{
  const devLogoPath = projectDir + '/images/dev_logo.png';
  // Could also use context.project.src instead of projectDir + '/src...'
  const targetPath  = projectDir + '/src/assets/imgs/logo.png';

  let fs = require('fs');
  fs.copyFileSync(devLogoPath, targetPath); 
}

function useProductionImage(projectDir)
{
  const prodLogoPath = projectDir + '/images/prod_logo.png';
  const targetPath   = projectDir + '/src/assets/imgs/logo.png';

  let fs = require('fs');
  fs.copyFileSync(prodLogoPath, targetPath);
}

Upvotes: 1

Related Questions