abc
abc

Reputation: 2437

Yeoman pass prompt answers to subgenerator

I have a yeoman generator with some subgenerators.

I know I can pass options from the parent- to the subgenerators when calling composeWith(...).

But how can I pass the answers I get from prompting? The are not available at the point when composeWith is called.

For example I prompt in the generator for an app name and want to provide this to all the subgenerators as options?

Upvotes: 1

Views: 375

Answers (2)

BjornO
BjornO

Reputation: 911

One way to do this is using the built-in config.

In the "parent" generator:

configuring(){
    this.log('Saving configuration in .yo-rc.json')
    const answers = this.answers.answers()
    for(const key in answers){
        this.config.set(key, answers[key])
    }
    this.config.save()
}

In the "child" generator, to populate templates:

    const templateData = {
        ...this.config.getAll(),
        ...
    }
    this.fs.copyTpl(
        this.templatePath(),
        this.destinationPath(),
        templateData
    )

This should be simple enough to change for your use case, eg perhaps you'd want this.config.get(something) in the child generator.

Just note this won't work across different generators; only between a generator and its own sub-generators:

The .yo-rc.json file is a JSON file where configuration objects from multiple generators are stored. Each generator configuration is namespaced to ensure no naming conflicts occur between generators.

This also means each generator configuration is sandboxed and can only be shared between sub-generators. You cannot share configurations between different generators using the storage API. Use options and arguments during invocation to share data between different generators.

Upvotes: 1

abc
abc

Reputation: 2437

Oh, found in the related questions that I could call the subgenerator after prompting, instead of the initialize-method (as in the quite outdated tutorial)

Upvotes: 0

Related Questions