I’m quite happy with how VS studio compiles code and always use build server to build packages, so this blog does not have actual reason behind, except question from d365fo.tools team. Guys are doing a great job and if you have not used their tools yet, give them a spin!

Code below find all referenced modules and compile them before compiling selected module, however, usually you reference standard modules that do not need to be built, so exclude everything that is not required.

using Microsoft.Dynamics.AX.Framework.Xlnt.ILGenerator;
using Microsoft.Dynamics.AX.Framework.Xlnt.XppParser.Pass2;
using System;

class CompilerSample
{
    private const string PackagesLocalDirectory = @"k:\AosService\PackagesLocalDirectory";
    static void Main(string[] args)
    {
        string moduleToCompile = "Retail";
        ServiceMetadataProvider provider = new ServiceMetadataProvider(PackagesLocalDirectory, true, true, true, moduleToCompile);
        var modules  = provider.GetReferencedModules();

        //generally we don't need to build standard modules, here is just an example
        foreach (var module in modules )
        {
            CompileModule(module);
        }

        CompileModule(moduleToCompile);

        Console.ReadLine();
    }

    private static void CompileModule(string module)
    {
        Parameters parameters = new Parameters();
        parameters.XppMetadataPath = PackagesLocalDirectory;
        parameters.ModelModuleName = module;
        parameters.ReferencedAssembliesFolder = PackagesLocalDirectory;
        parameters.AssemblyOutputPath = System.IO.Path.Combine(PackagesLocalDirectory, module, "bin");
        ILGeneratorMain.Compile(parameters);
    }
}