May 25, 2021 Grunt
6. Specify the default selection for the inquiry
7. Define an initialization mold
grunt-init
a tool for automatically creating project scaffolding. I
t builds a complete directory structure based on the current working environment and some of the configuration options you give.
As for the specific files and content it generates, it depends on the template you choose and the configuration options you give for the specific information during the build process.
Note: This stand-alone program used to exist as Grunt's built-in "init" task. You can see more about its evolution in the Upgrade from 0.3 to 0.4 guide.
In order to use grunt-init, you need to install it in a global environment.
npm install -g grunt-init
This installs
grunt-init
command into your system path, allowing you to run it in any directory.
Note: You may need to use sudo permissions or run shell commands as a super administrator to do this.
grunt-init --help
help and a list of available templates
grunt-init TEMPLATE
and based on available templates
grunt-init /path/to/TEMPLATE
based on templates available in any other directory
Note that most templates should generate their files in the current directory (the directory that executes the command) (automatically generated project-related files), so if you don't want to overwrite existing files, be careful to switch to a new directory to ensure that the files are generated to another directory.
Once the templates are installed in your
~/.grunt-init/
(the Windows platform
%USERPROFILE%\.grunt-init\
you can
grunt-init
command. W
e recommend that you use git to clone the template into the project directory.
For example,
the grunt-init-jquery template
can be installed like this:
git clone https://github.com/gruntjs/grunt-init-jquery.git ~/.grunt-init/jquery
Note: If you want to use a template locally like "foobarbaz", you should specify
~/.grunt-init/foobarbaz
clone it.
grunt-init
the actual directory name that is actually in
~/.grunt-init/
Here are some grunt-init templates that are officially maintained by Grunt:
You can create and use custom templates. However, your template must follow the same file structure as the one above.
Here's an
my-template
that must follow the following general file structure:
my-template/template.js
- main template file.
my-template/rename.json
- Template-specific rename rules that are processed as templates.
my-template/root/
files to be copied to the destination.
Assuming that these
/path/to/my-template
directory, the command
grunt-init /path/to/my-template
processes these templates.
There may be more than one named unique template (multiple templates that are not renamed) in this directory.
In addition, if you put this custom template in your
~/.grunt-init/
%USERPROFILE%\.grunt-init\
on Windows), you only need to use
grunt-init my-template
command to use this template.
When the initialization template is executed, any files in the root/subdirect directory are copied to the current
root/
init.filesToCopy
and
init.copyAndProcess
methods.
Note that all copied files are processed
{% %}
as
props
and all templates are replaced based on the data in the props data object collection, unless
noProcess
Take a look
at the case in jquery template.
rename.json
used to
sourcepath
renamed mapping relationship from sourcepath to
destpath
sourcepath
be a file path to be copied relative to the
root/
but
destpath
value can contain a template of
{% %}
If
destpath
specified as
false
the file will not be copied.
In addition,
srcpath
supports wildcard matching patterns.
Each initialization prompt has a hard-coded default value or it attempts to determine the default value based on the current environment.
If you want to override the default value for a particular prompt, you can do so selectively in OS X or Linux's
~/.grunt-init/defaults.json
%USERPROFILE%\.grunt-init\defaults.json
file.
For example, since I want to replace the default name with a different name, and I want to exclude my email address, and I want to automatically specify
defaults.json
might look like this.
{
"author_name": "\"Cowboy\" Ben Alman",
"author_email": "none",
"author_url": "http://benalman.com/"
}
Note: Even if all built-in prompts are documented, you can still find their names and defaults in the source code.
This short template description also appears with the template name when the user runs
grunt init
or
grunt-init
to display all available initialization templates.
exports.description = descriptionString;
If this option is specified, this optional extension description will be displayed before any prompt information is displayed. T his is a great place to give users some information about help with namespaces. These tips may be required or optional, and so on.
exports.notes = notesString;
Grunt terminates and generates a warning message that the user can use --force to override this default behavior if a match
--force
or if a match pattern array appears.
This is useful in situations when the initialization template might overwrite an existing file.
exports.warnOn = wildcardPattern;
However, the most
'*'
which matches any file or directory. U
se
minimatch wildcard
mode for great flexibility.
For example:
exports.warnOn = 'Gruntfile.js'; // Warn on a Gruntfile.js file.
exports.warnOn = '*.js'; // Warn on any .js file.
exports.warnOn = '*'; // Warn on any non-dotfile or non-dotdir.
exports.warnOn = '.*'; // Warn on any dotfile or dotdir.
exports.warnOn = '{.*,*}'; // Warn on any file or dir (dot or non-dot).
exports.warnOn = '!*/**'; // Warn on any file (ignoring dirs).
exports.warnOn = '*.{png,gif,jpg}'; // Warn on any image file.
// This is another way of writing the last example.
exports.warnOn = ['*.png', '*.gif', '*.jpg'];
Although
exports
property is defined outside the function, all actual initialization code is specified inside it. T
his function accepts three arguments,
grunt
parameter is a reference to a grunt that contains all
the grunt methods and libraries.
init
parameter is an object that contains methods and properties that exist specific to this initialization template.
done
parameter is a function that must be called when the initialization template execution is complete.
exports.template = function(grunt, init, done) {
// See the "Inside an init template" section.
};
You can add a properly named license agreement certificate file to a file object.
var files = {};
var licenses = ['MIT'];
init.addLicenseFiles(files, licenses);
// files === {'LICENSE-MIT': 'licenses/LICENSE-MIT'}
Return an array of available license agreement certificates:
var licenses = init.availableLicenses();
// licenses === [ 'Apache-2.0', 'GPL-2.0', 'MIT', 'MPL-2.0' ]
It provides an absolute or relative source file path, as well as an optional relative relative target file path, which can be selectively processed by passing callback functions when copying a file.
init.copy(srcpath[, destpath], options)
Traverse all the files in the passed object, copy the source files to the destination path, and work with the content.
init.copyAndProcess(files, props[, options])
The default initial value specified by the user in
defaults.json
init.defaults
The absolute path to the target file.
init.destpath()
Returns a unique array of all files or directory paths that match a given wildcard pattern. T
his method receives wildcard mode parameters in the form of a comma split or array. I
f the path matches the pattern
!
A
t the beginning, the results matched to the pattern are excluded from the returned array.
Patterns are processed sequentially, so it is important to include and exclude the order in which they appear in the array.
init.expand([options, ] patterns)
Returns an object that contains the files to be copied, each containing the absolute path of the source file and the relative path of the target file, and renames (or ignores) the rules in
rename.json
if present.
var files = init.filesToCopy(props);
/* files === { '.gitignore': 'template/root/.gitignore',
'.jshintrc': 'template/root/.jshintrc',
'Gruntfile.js': 'template/root/Gruntfile.js',
'README.md': 'template/root/README.md',
'test/test_test.js': 'template/root/test/name_test.js' } */
Gets a single task file path.
init.getFile(filepath[, ...])
Returns an object that contains all available templates.
init.getTemplates()
Search the initialization template in the initialization directory.
template
to the location of the template.
It
~/.grunt-init
./.grunt-init and grunt-init.
init.initSearchDirs([filename])
Start the program and prompt to start typing.
init.process(options, prompts, done)
init.process({}, [
// Prompt for these values
init.prompt('name'),
init.prompt('description'),
init.prompt('version')
], function(err, props) {
// All finished, do something with the properties
});
Give the user a hint and let the user enter the value of their choice.
init.prompt(name[, default])
This object contains all the prompt information.
var prompts = init.prompts;
Read the default values of the JSON format in the task file, if one exists, and merge them into a data object.
init.readDefaults(filepath[, ...])
The rename rule for the template.
var renames = init.renames;
// renames === { 'test/name_test.js': 'test/{%= name %}_test.js' }
Search for an array of directories for templates.
var dirs = init.searchDirs;
/* dirs === [ '/Users/shama/.grunt-init',
'/usr/local/lib/node_modules/grunt-init/templates' ] */
Search for the initialized template path based on the file name and return an absolute path.
init.srcpath(filepath[, ...])
Returns the absolute path to the user template directory.
var dir = init.userDir();
// dir === '/Users/shama/.grunt-init'
Save a
package.json
Callback functions can be used for post-processing properties to add/remove/other operations.
init.writePackageJSON(filename, props[, callback])
Used for author email addresses in
package.json
By default, an attempt is made to find a default value from the user's git configuration.
For author full name and copyright information in
package.json
You will also try to find a default value from the user's git configuration.
package.json
to expose the author's personal website.
The relative path of the cli script in the root of the project.
A public URL for project problem tracking. If the project has a Github repository, it will automatically point to the project Github's problem tracking module (issue).
The description of the project.
Usually
package.json
or README file.
A valid Grunt version scope definition required for the project.
A public URL that points to the first page of the project. If this item is using a github repository, then the default is the url of the Github repository.
In the case of a jQuery project, it represents the version of jQuery required for the project. Must be a valid version range definition.
Project license agreement certificate. M
ultiple license agreement certificates are split using spaces, with built-in license
MIT
MPL-2.0
GPL-2.0
Apache-2.0
T
he default is
MIT
protocol.
You
can use the init.addLicenseFiles
method to add custom license agreement certificates.
The main entrance to the project.
The default is
lib
after the project name in the lib directory.
The name of the project. It will be heavily used in the project template, pointing by default to the current working directory.
The version of Node .js project. Must be a valid version range definition.
The command to run the test in the project,
grunt
The git repository for the project. The default is a guessed github url.
The name of the project that is suitable for everyone to identify. The default is the original project name, and it is filtered to be recognized.
The version number of the project.
The default is the first valid semantic version number:
0.1.0