Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

common-boilerplate

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

common-boilerplate

base class for boilerplate

  • 0.4.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1
Maintainers
1
Weekly downloads
 
Created
Source

common-boilerplate

base class for boilerplate

NPM version build status Test coverage David deps Known Vulnerabilities NPM download

Usage

$ npm i common-boilerplate --save

Write your boilerplate

use boilerplate-boilerplate for quick start.

$ npm i boilerplate-boilerplate
$ node ./node_modules/boilerplate-boilerplate/bin/cli.js

Lifecycle

- ask question
- list all file from boilerplate paths
- render files to target dir
- npm install
- unit test

Directory

├── boilerplate
│   ├── lib
│   ├── test
│   ├── README.md
│   ├── _.eslintrc
│   ├── _.gitignore
│   ├── _package.json
│   └── index.js
├── test
│   └── index.test.js
├── index.js
├── README.md
└── package.json
  • index.js is your Boilerplate Logic, the main entry.
  • boilerplate/** is your template dir, will be copy to dest.

Boilerplate Entry

// index.js
const Boilerplate = require('common-boilerplate');

class MainBoilerplate extends Boilerplate {
  // must provide your directory
  get [Symbol.for('boilerplate#root')]() {
    return __dirname;
  }
};

module.exports = MainBoilerplate;
module.exports.testUtils = Boilerplate.testUtils;

Ask questions

Inquirer is built-in to provide prompt helper.

Add your questions:

class MainBoilerplate extends Boilerplate {
  initQuestions() {
    const questions = [
      // remain super questions
      ...super.initQuestions(),

      // add new questions
      {
        name: 'name',
        type: 'input',
        message: 'Project Name: ',
        default: () => this.locals.name, // set default from locals
      },
      {
        type: 'list',
        name: 'type',
        message: 'choose your type:',
        choices: [ 'simple', 'plugin', 'framework' ],
      }
    ];
    return questions;
  }
  // ...
};

Locals

this.locals is used to fill the teamplte, it's merge from built-int -> argv -> user's prompt answer;

Built-in:

  • name - project name, by default to git repository name
  • user - user info
    • name - git config user.name
    • email - read from git user email
    • author - ${user} <${email}>
  • git - git url info
    • extract from git config remote.origin.url
    • see git-url-parse for more details.
  • npm - npm global cli name, will guest by order: tnpm -> cnpm -> npm
  • registry - npm registry url, not set by default

Template Render

Built-in render is very simple:

  • {{ test }} will replace
  • \{{ test }} will skip
  • support nested value such as {{ obj.test }}
  • unknown variable will render as empty string

Custom your render logic:

// recommended to use https://github.com/mozilla/nunjucks
const nunjucks = require('nunjucks');

// perfer to disable auto escape
nunjucks.configure({ autoescape: false });

class MainBoilerplate extends Boilerplate {
  async renderTemplate(tpl, locals) {
    return nunjucks.renderString(tpl, locals);
  }

  // custom your locals
  async initLocals() {
    const locals = await super.initLocals();
    locals.foo = 'bar';
    return locals;
  }
};

File Name Convert

  • also use template render, so {{name}}.test.js is supported.
  • some file is special, so you can't use it's origin name
    • such as boilerplate/package.json, npm will read files and ignore your files.
    • use _ as prefix, such as _package.json / _.gitignore / _.eslintrc
    • add your mapping by this.fileMapping

Default mappings:

this.fileMapping = {
  gitignore: '.gitignore',
  _gitignore: '.gitignore',
  '_.gitignore': '.gitignore',
  '_package.json': 'package.json',
  '_.eslintrc': '.eslintrc',
  '_.eslintignore': '.eslintignore',
  '_.npmignore': '.npmignore',
};

Logger

Provide powerful cli logger for developer, see signale for more details.

debug is disabled by default, use --verbose to print all logs.

this.logger.info('this is a log');

this.logger.disable([ 'info', 'debug' ]);

this.logger.enable('debug');

CommandLine argv

Also support custom argv:

  • if pass the same name with question, then skip asking user and write it to locals
  • argv will convert to camelCase, such as --page-size=1 -> pageSize
  • dot prop will convert to nested object, such as --page.size=1 -> { page: { size: '1' } }
  • see yargs#optionskey for more details
class MainBoilerplate extends Boilerplate {
  // use as `--test=123 --str=456`
  initOptions() {
    const options = super.initOptions();

    options.test = {
      type: 'string',
      description: 'just a test',
    };

    options.str = {
      type: 'string',
      description: 'just a str',
    };

    return options;
  }
};

Built-in:

  • --baseDir= - directory of application, default to process.cwd()
  • --npm= - npm cli, tnpm/cnpm/npm, will auto guess
  • --registry= - npm registry url, also support alias -r=china

Boilerplate Chain

Support mutli-level boilerplate, so you can share logic between boilerplates.

class ShareBoilerplate extends Boilerplate {
  // must provide your directory
  get [Symbol.for('boilerplate#root')]() {
    return __dirname;
  }
};
module.exports = ShareBoilerplate;
// don't forgot to exports `testUtils`
module.exports.testUtils = Boilerplate.testUtils;
// child
class MainBoilerplate extends ShareBoilerplate {
  // must provide your directory
  get [Symbol.for('boilerplate#root')]() {
    return __dirname;
  }

  // example for ignore some files from parent
  async listFiles(...args) {
    const files = await super.listFiles(...args);
    files['github.png'] = undefined;
    return files;
  }
};
module.exports = MainBoilerplate;
module.exports.testUtils = ShareBoilerplate.testUtils;
  • must provide getter Symbol.for('boilerplate#root') to announce your root, and boilerplate directory is required to exists at your root directory.
  • will auto load all files from boilerplate, same key will be override.
  • you could custom by async listFiles(), such as ignore some files from parent.

Unit Testing

Extends Coffee to provide testUtils for cli.

const testUtils = require('common-boilerplate').testUtils;

describe('test/index.test.js', () => {
  it('should work', () => {
    return testUtils.run()
      // .debug()
      .waitForPrompt()
      // answer to the questions
      .write('example\n')
      // emit `DOWN` key to select the second choise
      .choose(2)

      // expect README.md to be exists
      .expectFile('README.md')

      // check with `includes`
      .expectFile('README.md', 'this is a desc')

      // check with regex
      .expectFile('README.md', /desc/)

      // check whether contains
      .expectFile('package.json', { name: 'example' })

      // opposite assertion
      .notExpectFile('not-exist')
      .notExpectFile('README.md', 'sth')

      // see others at `coffee` docs
      .expect('stdout', /some console message/)
      .expect('stderr', /some error message/)
      .expect('code', 0)

      // don't forgot to call `end()`
      .end();
  });
});

FAQs

Package last updated on 02 Oct 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc