Sunday, 3 October 2021

Creating NX plugin for generating a single file

I would like to create my first nx plugin, which only adds a generated file to the application in the dist folder.

So this is the basicly the script as I did it before. But as nx plugins are new for me, I do not understand the difference between generator and executor (which is explained in the docs) at all.

import * as fs from 'fs'
import { promisify } from 'util'
const writeFile = promisify(fs.writeFile)

function generateContent() {
  return { foo: 'bar' }
}

async function generateFile(filePath, content) {
  try {
    await writeFile(filePath, JSON.stringify(content, null, 2) + '\r\n')
  } catch (error) {
    throw Error('Could not write file: ' + filePath)
  }
}

const run = async (): Promise<void> => {
  try {
    const content = generateContent()
    await generateFile('dist/apps/my-app/file.json', content)
  } catch (error) {
    throw Error(error)
  }
}

run()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error(err)
    process.exit(1)
  })

So if I understand it correctly, I have to put the above code in the executor - replacing the console.log line, right?

But writing the file itself has to be added to the generator, so I don't need writeFile, right?

executor.ts

import { BuildExecutorSchema } from './schema'

export default async function runExecutor(options: BuildExecutorSchema) {
  console.log('Executor ran for Build', options)
  return {
    success: true
  }
}

But I am using

run()
  .then(() => process.exit(0))
  .catch((err) => {
    console.error(err)
    process.exit(1)
  })

as a starting point in my script. How should this look like in the executor?

An example for this very basic plugin code would be very helpful for my understanding.



from Creating NX plugin for generating a single file

No comments:

Post a Comment