generate
generate copied to clipboard
Use generate as API?
So Iv'e got a generator.js file working fine locally using a global command when I'm in the same directory as the file.
However I'm wanting to also trigger it via another node script without having to call the commandline.
The docs said it can be used via both cli and api, but I see no info anywhere on how to trigger a generator.
To use a generator in an other node script, you have to import it and use it as a plugin on an instance of Generate
Hi @Truemedia, thanks for creating an issue. I can help you get everything working.
The docs said it can be used via both cli and api, but I see no info anywhere on how to trigger a generator.
Sorry about the lack of documentation, we're actively working on new docs (and were hiring a techical writer, in case you happen to know someone who might be interested).
API usage
To use the API, start by creating an instance of Generate
, then you can do anything with the instance of Generate
that you would do inside a generator.
For example, you can define tasks similar to how you would define tasks with gulp:
const Generate = require('generate');
const app = new Generate();
app.task('foo', cb => cb());
app.task('bar', cb => cb());
app.task('baz', cb => cb());
app.task('default', ['foo', 'bar', 'baz']);
// To run tasks, use the `.build()` method. The following
// will run the "default" task, which in turn will run
// the "foo", "bar" and "baz" tasks
app.build('default', err => console.log(err || 'done!'));
Generators
In case it helps, the following examples should take the mystery out of how generators work.
Generators are just functions that take an instance of Generate, so by wrapping the code from the previous example in a function, we can create a generator:
// "app" is the instance of Generate
function generator(app) {
app.task('foo', cb => cb());
app.task('bar', cb => cb());
app.task('baz', cb => cb());
app.task('default', ['foo', 'bar', 'baz']);
app.build('default', err => console.log(err || 'done!'));
}
When run by command line, Generate's CLI creates the instance of Generate for the generator by dong somethign like this:
#!/usr/bin/env node
const Generate = require('generate');
// get the path to the generator specified by the user
const generatorPath = '/path/to/generator/specified/by/user/generator.js';
const generator = require(generatorPath);
// create an instance of Generate for the generator
// (if multiple generators are chained/run consecutively,
// a separate instance of Generate is created for each generator)
const app = new Generate();
generate(app);
// next, if the user specified a task to run, the CLI
// runs that task, otherwise the CLI runs the "default" task
// on the generator. Something like this:
app.build(argv[0] || 'default', console.log(err || 'done!'));
If you're familiar with gulp, a generator.js
file is similar to a gulpfile.js
wrapped in a function, which allows Generate's CLI to create the instance.