Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🏭 Core generator for ngX-Rocket add-ons

License

NotificationsYou must be signed in to change notification settings

ngx-rocket/core

Repository files navigation

NPM versionBuild StatusNode versionXO code styleLicense

Core generator for creating ngX-Rocket add-ons

Table of Contents

Usage

This package extendsYeoman base generator with all the boilerplate needed to createngX-Rocket add-ons, and even more.

First install the dependency:

npm install --save @ngx-rocket/core

Then create a new add-on generator like this:

'use strict';constGenerator=require('@ngx-rocket/core');module.exports=Generator.make({baseDir:__dirname});

Add some template files in atemplates/ folder and you're done.

Congratulations on making your first Yeoman generator! 🎉

Concepts

This package allows you to create advancedYeoman generators that can be used asngX-Rocket add-ons or standalone generators.

See thisexample addon, you can use it as a base for your own add-ons.

First it may be helping to be familiar withYeoman generators, since they have tofollow specific naming and structure rules.

Prompts and properties

You may want to ask the user some question about what he wants to generate, to do so you have to provide a list ofprompts like this:

module.exports=Generator.make({baseDir:__dirname,// Your generator prompts// See https://github.com/sboudrias/Inquirer.js#objects for detailsprompts:[{type:'confirm',name:'sayHello',message:'Shall we say hello?',default:true},{type:'input',name:'helloName',message:'To whom shall we say hello?',default:'world',// Only ask this one when "yes" is replied to the sayHello promptwhen:props=>props.sayHello}]});

You can see in this example that prompts can even be shown conditionally using the propertywhen.

After the user has answered your prompts, the results will be exposed as properties of theprops object.Theprops object can then be used directly in yourtemplates.

To avoid repeating the same questions between core and add-ons generators, theseprops can be shared and retrievedusingGenerator.shareProps andGenerator.sharedProps.Note that in that goal, prompts name matching already defined properties with be automatically skipped once defined.

Templates

Your generator templates should go under thegenerators/app/templates/ folder.

With its most basic usage, any file put in this folder will be copied as-is in the generated project folder.But you may often have to customize the file depending of the userprompts.

To do so, just prepend an underscore (_) to the file name and it will become anEJS template, willfull access to theprops object:

// generators/app/templates/_hello.md#<%=props.appName// From shared properties %><%if (props.sayHello) {-%>Hello<%=props.helloName%>!<% }else {-%>...was notin the mood to say hello:-(<% }-%>

You can then inject strings from the prompts or apply conditions for example.

See theEJS documentation for the complete syntax options.

File prefix rules

To avoid using complex hardcoded logic in generator, prefix-based file naming rules are used.

Conditional prefix

There is two ways to conditionally include a file depending of user choices:

  • Using aconditional folder at root level, with the syntax__<prefix>/:all files under this folder will be copied if the prefix condition is matched.

    Example:__authentication/my-service.ts will be copied to<project-dir>/my-service.ts only if the user hasenabled authentication during prompts.

  • Using aconditional prefix on a specific file, with the syntax__<prefix>.<filename>:this file will be copied if the prefix condition is matched.

    You can even complete this by adding_ before the<filename> part to also make it an EJS template, ie__<prefix>._<filename>.

    Example:__authentication.myservice.ts will be copied to<project-dir>/my-service.ts only if the user hasenabled authentication during prompts.

Multiple conditions are also supported using the+ character:__<prefix1>+<prefix2>+<prefixN>.<filename>.

You can use thedefault prefix rules and extend them if needed.These rules match the questions asked by the main generator(generator-ngx-rocket):

  • web: the user has chosen to make aweb app as one of its targets
  • cordova: the user has chosen to make amobile app as one of its targets
  • electron: the user has chosen to make adesktop app as one of its targets
  • pwa: the user has chosen to add progressive web app support
  • bootstrap: the user has chosenBootstrap for its UI
  • ionic: the user has chosenIonic for its UI
  • material: the user has chosenAngular Material for its UI
  • raw: the user has chosen to not use any UI library
  • universal: the user has chosen to useAngular Universal (Server-Side Rendering)
  • auth: the user has enabled authentication
  • ios: the user has chosen to support iOS for its mobile app
  • android: the user has chosen to support Android for its mobile app
  • windows: the user has chosen to support Windows (Universal) for its mobile app

Action prefix

In addition to conditional prefix, you can specifyhow the file should be copied to the destination folder.

By default files are copied entirely, overwriting previous version if needed (if multiple add-ons are trying to writethe same file, the one finally written will be from the last processed add-on).

To use actions you have to use this syntax(<action>).<filename>. This syntax can also be combined with theconditional/template prefixes like this:__<conditional-prefix>(<action>)._<filename>

Example:(merge).package.json will merge the content with<project-dir>/package.json.

This is the list of currently implemented file actions:

  • merge (only for JSON files): performs a deep merge of the JSON properties, concatenating arrays with unique values.
  • raw: disable template processing even if filename starts with an underscore (_).

Advanced customization

If your generator needs to perform additional specific actions, you can add code for custom tasks to be executed aspart of the composition lifecycle.

For this you simply create a new class to extend the baseGenerator:

// generators/app/templates/index.jsconstGenerator=require('@ngx-rocket/core');constpkg=require('../../package.json');classExampleGeneratorextendsGenerator{// DO NOT add a constructor, it won't be called.// Use initializing() method instead.initializing(){// Setting version allows Yeoman to automatically notify the user of updatesthis.version=pkg.version;this.log(`Example generator is running version${this.version}`);}end(){this.log(`This was nice, see ya!`);}}module.exports=Generator.make({baseDir:__dirname,// Your custom generatorgenerator:ExampleGenerator});

A complete working example is available here:addon-example

There is a set of specific task names for each part of the project generation lifecycle, for example theinitializingtask of all generators will be executed before moving on to the next one.

To learn more about Yeoman's run loop and see the list of specific task with their priorities, see therunning context documentation. The composability docs also haveexample execution sequence to understand how generators workwith each other.

See also the full YeomanBase generator documentation for the list ofavailable properties and methods you can use in your generator.

Note: be careful when overriding one of the methods already defined in@ngx-rocket/core base Generator (promptingorwriting)! To maintain the base behavior along with your additions, you have to manually call the original methodusingsuper.<method>() in your overridden method, like this:

classExampleGeneratorextendsGenerator{writing(){// Do your stuff hereconsole.log('Hey there!');// Make sure you call the base method to maintain proper behavior!returnsuper.writing();}}

Generating only tools

As part of the update process or if your users are only interested with generating only the toolchain, you can definefilters to exclude template files that are not part of the toolchain.

All generators automatically support the--tools option that enable the filters.

To define these filters you have 2 possibilities:

  • Create a.toolsignore in your generatorbaseDir root to exclude files that are not part of the toolchain.It uses the same syntax as a.gitignore file.

  • Specify atoolsFilter option whencreating your generator instance. Note thatsetting this option will remplace any rules that may be defined in a.toolsignore file.This option takes either a string or an array of strings, using the same syntax as a.gitignore file.

Standalone note

If you want your generator to work as a standalone and not only as an ngX-Rocket add-on, you must define theappNamepropery, either using an argument option:

classMyStandaloneGeneratorextendsGenerator{initializing(){this.argument('appName',{desc:'Name of the app to generate',type:String,required:true});}}

or a prompt:

module.exports=Generator.make({baseDir:__dirname,prompts:[{type:'input',name:'appName',message:'What\'s the name of your app?'}]});

or both :)

Fullstack mode

By default, an add-on is configured to generateclient templates, but by setting thetypeoption you can generateserver templates orboth client andserver templates.

When any add-on generator is either configured asserver orfullstack, the whole project generation switches tofullstack mode, meaning that the generated output will contain both client and server code.

At any time after the initialization of your generator you can check if fullstack mode is enabled by using theisFullstack() instance method.

The client and server output folders can be modified by the user or forced by your generator through the environmentvariablesNGX_CLIENT_PATH andNGX_SERVER_PATH. If not modified,client andserver will be used as defaultoutput folders.

API

Static methods/properties

Generator.make(options)

Creates a new Yeoman generator extending the core ngx-rocket generator.

{object}options Configures your generator instance:
  • baseDir: base directory for your generator templates
  • generator: your generator base class (optional)
  • options: generator options, see related section athttp://yeoman.io/authoring/user-interactions.html (optional).
  • prompts: generator prompts, usingInquirer.js format (optional).
  • templatesDir: generator templates directory (optional, default:'templates')
  • prefixRules: generator template prefix rules (optional, default:Generator.defaultPrefixRules())
  • toolsFilter: file filter patterns to use when toolchain only option is enabled. If not provided, the generatorwill try to load the.toolsignore file insidebaseDir.
  • type: generator type, can beclient,server orfullstack (optional, default: 'client'). Infullstackmode, client and server templates must be separated intoclient,server androot subfolders.

Generator.defaultPrefixRules

Gets the default prefix rules.

The default rules are these:

{web:props=>props.target.includes('web'),cordova:props=>props.target.includes('cordova'),electron:props=>props.target.includes('electron'),pwa:props=>Boolean(props.pwa),bootstrap:props=>props.ui==='bootstrap',ionic:props=>props.ui==='ionic',raw:props=>props.ui==='raw',universal:props=>Boolean(props.universal),auth:props=>Boolean(props.auth),ios:props=>props.mobile.includes('ios'),android:props=>props.mobile.includes('android'),windows:props=>props.mobile.includes('windows')};

You can use this method to extend the default rules with your own, like this:

constextentedRules=Object.assign(Generator.defaultPrefixRules,{hello:props=>Boolean(props.hello)});

Generator.sharedProps

Gets a copy of properties shared between generators.To share additional properties, useGenerator.shareProps.

Also available on the generator instance.

Generator.shareProps(props)

Sets additional properties shared between generators.To avoid collisions issues, only properties that are currently undefined will be added.

Also available on the generator instance.

Instance properties

sharedProps (read-only)

SeeGenerator.sharedProps.

shareProps(props)

SeeGenerator.shareProps.

isStandalone (read-only)

Returnstrue if the generator is running standalone orfalse if it is running as an add-on.

isFullstack (read-only)

true if this or a composed generator has declared to be inserver orfullstack mode orfalse if it is runningin client only mode.

packageManager (read-only)

Returns the package manager to use (eithernpm oryarn).The default value isnpm, and can be changed either by the--packageManager option or the environment variableNGX_PACKAGE_MANAGER.


[8]ページ先頭

©2009-2025 Movatter.jp