I. Project background
Different project teams use different technical frameworks (VUE or React), even if different developers in the same project team have different development habits. Eventually, the project structure will be chaotic, causing unnecessary maintenance costs for other personnel. Many companies have started to develop their own scaffolding for initializing project templates. (Many companies will put on their own private service image, here to show you put on the NPM public image, for everyone to experience convenience.)
1.1 Image Warehouse
npm (npmjs.com)
Open your browser and search ncun-cli
1.2 Scaffold source code
Nccun – CLI: Nuochun Blog Theme Development Scaffolding (gitee.com)
Nccun – CLI: Nuochun Blog Theme development Scaffolding (github.com)
1.3 Framework template source code
Ncun – CLI-vuE-Demo: NCUN Theme Template (VUE) (gitee.com)
Ncun – CLI-vuE-demo: NCUN Theme Template (vUE) (github.com)
Ncun-cli-react-demo: NCUN Theme Template (React) (gitee.com)
Ncun-cli-react-demo: Ncun Theme Template (React) (github.com)
Ncun -cli-angular-demo: Ncun Theme Template (Angular) (gitee.com)
Ncun -cli-angular-demo: Ncun Theme Template (Angular) (github.com)
Ii. Project demonstration
2.1 Global Installation
$ npm install ncun-cli -g
Copy the code
2.2 Checking installation
$ ncun
Copy the code
2.3 Viewing the Version
$ ncun -v
Copy the code
2.4 Creating a Project
$ ncun init
Copy the code
2.5 Opening the Project
2.6 Starting a Project
2.7 Access Items
Demand analysis
Since the company basically has a private GitLab, we put the template of each technical framework on the private server warehouse. When each front-end developer needs to initialize a new project, he can use the company’s scaffolding and choose his own technical framework to initialize a common template. (Here is the main demonstration how to implement a scaffold, if you have the parent company git access permission, in fact, you can directly download the template to use, generally each department and the department’s private warehouse, only for the department members to access.)
3.1 commander
Node.js command line solution for custom commands (e.g. Nccun -v)
3.2 inquirer
A user – command line interaction tool for customizing project names (e.g.? Project name:)
3.3 shelljs
Repackaging child_process to make it easier to call system commands (e.g. Git clone…)
3.4 ora
Implement the loading effect of node.js command line environment, and display various state ICONS
3.5 —
Terminal string style plugin to change the color of terminal strings (e.g. : chalk. Green (‘NCun init successfully. Now run:’))
Iv. Development and implementation
4.1 Create scaffolding warehouse
Create the ncun-CLI repository on Github and clone it locally.
$ git clone https://github.com/dianjiu/ncun-cli.git
Copy the code
4.2 Initializing the Project
This is an empty project, so let’s initialize it.
$ npm init -y
Copy the code
4.3 Modifying the Configuration
At this point, a package.json file will appear in the project, and we’ll make some simple changes here.
{
"name": "ncun-cli"."version": "21.06.09"."description": "Command line interface for Ncun"."main": "lib/ncun"."scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git"."url": "https://github.com/dianjiu/ncun-cli"
},
"homepage": "https://ncun.fun/"."keywords": [
"blog"."cms"."ncun"."cli"]."author": {
"name": "DianJiu"."email": "[email protected]"."url": "https://dianjiu.co"
},
"bin": {
"ncun": "bin/ncun"
},
"bugs": {
"url": "https://github.com/dianjiu/ncun-cli/issues"
},
"license": "MIT"."dependencies": {}}Copy the code
4.4 Adding a Dependency
Then we add the project’s base dependencies
$ npm install commander inquirer shelljs ora chalk --save
Copy the code
4.5 Optimizing directories
Create the bin,lib folders and readme. md and temp. json files in the root directory, create the ncu.js file in the bin directory, create the ncu.js and commands folders in the lib folder, and create the init.js file in the commands folder. The directory structure is as follows:
4.6 Implementing command Prompt
Use the COMMANDER plug-in to implement command prompts and basic command functions. (/bin/ ncu.js)
#! /usr/bin/env node
'use strict';
// const manager = require('.. /lib/');
// manager.versions();
// console.log(1)
const program = require("commander");
const version = require(".. /package.json").version;
program
.version(version, "-v, --version"."output the current version")
// Override the default help identifier and description
.helpOption('-h, --help'.'read more information');
program
.usage('<command>');
program
.command('init')
.description("init a ncun blog theme template ")
.alias('i')
.action(() = > {
require('.. /lib/commands/init')}); program.parse(process.argv);if(! program.args.length){ program.help() }Copy the code
4.7 Configuring a Template Repository
Configure templates repository addresses and code branches for different frameworks in templates.json.
{
"tpl": {
"vue": {
"url": "https://github.com/dianjiu/ncun-cli-vue-demo.git"."branch": "master"
},
"react": {
"url": "https://github.com/dianjiu/ncun-cli-react-demo.git"."branch": "master"
},
"angular": {
"url": "https://github.com/dianjiu/ncun-cli-angular-demo.git"."branch": "master"}}}Copy the code
4.7 Implementing the Initialization Function
/lib/commands/init.js
const { prompt } = require('inquirer');
const program = require('commander');
const shell = require('shelljs');
const ora = require('ora');
const fs = require('fs');
const config = require('.. /.. /templates.json')
const chalk = require('chalk')
const option = program.parse(process.argv).args[0];
const question = [
{
type: 'input'.name: 'template'.message: 'Template name (you can input one like react, vue, angular):'.default: typeof option === 'string' ? option : 'ncun-blog-template',
filter (val) {
return val.trim()
},
validate (val) {
// Check whether the template exists
const validate = config.tpl[val];
if(validate){
return true
}
return chalk.red('Template does not support! ');
},
transformer (val) {
returnval; }}, {type: 'input'.name: 'name'.message: 'Project name'.default: typeof option === 'string' ? option : 'ncun-blog-template',
filter (val) {
return val.trim()
},
validate (val) {
const validate = (val.trim().split("")).length === 1;
return validate || 'Project name is not allowed to have spaces ';
},
transformer (val) {
returnval; }}, {type: 'input'.name: 'description'.message: 'Project description'.default: 'Vue project',
validate () {
return true;
},
transformer(val) {
returnval; }}, {type: 'input'.name: 'author'.message: 'Author'.default: ' ',
validate () {
return true;
},
transformer(val) {
returnval; }}];module.exports = prompt(question).then(({template, name, description, author}) = > {
gitUrl = config.tpl[template].url
branch = config.tpl[template].branch
const projectName = name;
const spinner = ora('Downloading please wait... \n');
spinner.start();
// Clone the template
let cmdStr = `git clone -b ${branch} ${gitUrl} ${projectName} `
// childProcess.exec(cmdStr, function(error, stdout, stderr){
if(shell.exec(cmdStr).code ! = =0){
shell.echo('Error: Git clone failed');
shell.exit(1);
}
/ / read package. Json
fs.readFile(`. /${projectName}/package.json`.'utf8'.function (err, data) {
if(err) {
spinner.stop();
console.error(err);
return;
}
const packageJson = JSON.parse(data);
packageJson.name = name;
packageJson.description = description;
packageJson.author = author;
/ / modify package. Json
fs.writeFile(`. /${projectName}/package.json`.JSON.stringify(packageJson, null.2), 'utf8'.function (err) {
if(err) {
spinner.stop();
console.error(err);
} else {
spinner.stop();
console.log(chalk.green('NCun init successfully. Now run:'))
console.log(`
${chalk.yellow(`cd ${projectName}`)}
${chalk.yellow('npm install (or `yarn`)')}
${chalk.yellow('npm run dev (or `yarn dev`)')}
`); }}); });console.log(chalk.green(Generation '\ n) completed! '))});Copy the code
V. Project summary
At present, the project only has a simple implementation, and only supports vUE template, which will be continuously updated and optimized in the future. You can customize your own project template according to your own development habits. After downloading the scaffolding source code locally, replace the template repository address with your own and use NPM Link for local simulation debugging.