Skip to content

CompilerPass

Mauro edited this page May 27, 2022 · 8 revisions

Compiler Pass

Sometimes, you need to do more than one thing during compilation, want to use compiler passes without an extension or you need to execute some code at another step in the compilation process. In these cases, you can create a new class with a process method

class CustomPass {
    /**
     * @param {ContainerBuilder} container
     */
    async process (container) {
       // ... do something during the compilation
    }
}

You then need to register your custom pass with the container:

import {ContainerBuilder, JsFileLoader} from 'node-dependency-injection'

let container = new ContainerBuilder()
container.addCompilerPass(new CustomPass())
await container.compile()

You must compile the container in order to use your compiler pass

Controlling the pass ordering

The optimisation passes run first and include tasks such as resolving references within the definitions. When registering compiler passes using addCompilerPass(), you can configure when your compiler pass is run. By default, they are run before the optimisation passes.

You can use the following constants to determine when your pass is executed:

  • PassConfig.TYPE_BEFORE_OPTIMIZATION
  • PassConfig.TYPE_OPTIMIZE
  • PassConfig.TYPE_BEFORE_REMOVING
  • PassConfig.TYPE_REMOVE
  • PassConfig.TYPE_AFTER_REMOVING

For example, to run your custom pass after the default removal passes have been run, use:

import {PassConfig} from 'node-dependency-injection'

container.addCompilerPass(new CustomPass(), PassConfig.TYPE_OPTIMIZE)
await container.compile()

PassConfig.TYPE_BEFORE_OPTIMIZATION is the default pass config type. PassConfig.TYPE_OPTIMIZE will override the default container optimization on compile PassConfig.TYPE_REMOVE will override the default remove container optimization on compile

You can also control the order in which compiler passes are run for each compilation phase. Use the optional third argument of addCompilerPass() to set the priority as an integer number. The default priority is 0 and the higher its value, the earlier it's executed:

// ...
// FirstPass is executed after SecondPass because its priority is lower
container.addCompilerPass(new FirstPass(), PassConfig::TYPE_AFTER_REMOVING, 10)
container.addCompilerPass(new SecondPass(), PassConfig::TYPE_AFTER_REMOVING, 30)