Skip to content

Custom generators

Ensure you have likec4 in your dependencies:

npm i likec4

The likec4 gen command generates files from your model.
You can add your own generators to it.
Generators are functions, so define them in a TypeScript or JavaScript project config:

likec4.config.ts
import { defineConfig } from 'likec4/config'
export default defineConfig({
name: 'my-project',
title: 'My Project',
generators: {
'hello': async ({ likec4model, ctx }) => {
await ctx.write({
path: 'hello.txt', // relative to the project folder
content: `Project: ${likec4model.project.id}`,
})
},
},
})

Now you can run your generator with CLI:

Terminal window
likec4 gen hello

In multi-project workspace use:

Terminal window
likec4 gen hello --project my-project
# Other options
likec4 gen hello --project my-project --use-dot

A generator receives an object with two fields:

  • likec4model: the LikeC4 model of the project, with layouted views.
  • ctx: the context of the generator:
    • ctx.write({ path, content }) writes a file. path is absolute or relative to the project folder; missing folders are created.
    • ctx.locate(target) returns the source location of an element, relationship, view or deployment element.
    • ctx.project has the id, title and folder of the project; ctx.workspace is the workspace folder.
    • ctx.abort(reason) stops the generator.

There is also helper function defineGenerators to define reusable generators:

shared_generators.ts
import { defineGenerators } from 'likec4/config'
export default defineGenerators({
'hello': async ({ likec4model, ctx }) => {
await ctx.write({
path: 'hello.txt', // relative to the project folder
content: `Project: ${likec4model.project.id}`,
})
},
})

Now you can use it in your configs:

likec4.config.ts
import { defineConfig } from 'likec4/config'
import generators from './shared_generators'
export default defineConfig({
name: 'my-project',
title: 'My Project',
generators,
})