最近做项目遇到一个问题,很多页面,项目初始化的时候,总是把旧项目copy一个过来,然后删除里面不需要的东西,再加新项目要用的东西。做多之后感觉很繁琐。于是想到,有没有办法一键初始化项目呢。于是调研到了发布npm包。
1.注册npm
npm网站地址:https://www.npmjs.com/
npm网站注册地址:https://www.npmjs.com/signup
注册之后,输入命令
npm adduser
npm login
然后根据提示输入用户名,密码,邮箱登录完成
2.创建一个文件夹,以下是一个实例
我创建的是 plus-init-template
进入文件夹 plus-init-template,执行
npm init
一直回车,生成package.json
在根目录下新建index.js文件,内容如下
//创建一个index.js文件,文件内的代码如下
console.log(222);
控制台输入显示:
表明成功,可以保存发布
npm publish
如果出现
表示发布失败,因为有人已经使用了该名字,那么去package.json文件,修改name的值,然后重新执行npm publish
发布成功之后,去npm官方网站,查询自己的包名字,可以查看发布结果。
发布成功之后,验证下载。
npm install 包名字
注意:如果发布之后,修改文件再次发布,需要更换版本号
现在,生成npm包已经可以了,接下来,就定制属于自己的npm包。
需求:我们要做的是自定义一个npm包,该包可以自动初始化模板代码。(可以把公用代码放进去,初始化的时候就有一个初始化项目文件)
npm包地址:https://github.com/aleilei123/plus-init-template.git
项目初始化模板:https://github.com/aleilei123/init-tmp.git
先来看看例子:以下例子加了注释在里面,可自行研究
package.json配置如下
{
"name": "plus-init-template",
"version": "1.0.3",
"description": "一键生成模版",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/aleilei123/init-tmp.git"
},
"keywords": [
"template",
"typescript",
"create template",
"commander",
"download-git-repo"
],
"bin": {
"plus": "index.js"
},
"author": "zhaileilei",
"license": "ISC",
"homepage": "https://blog.csdn.net/zhaileilei1/article/details/93895994",
"dependencies": {
"chalk": "^2.4.1",
"commander": "^2.17.0",
"download-git-repo": "^1.0.2",
"handlebars": "^4.0.11",
"inquirer": "^6.0.0",
"log-symbols": "^2.2.0",
"ora": "^3.0.0",
"request": "^2.88.0",
"silly-datetime": "^0.1.2"
}
}
index.js写入:
#!/usr/bin/env node
// 以上这行代码必须加,加上才可以使用 bin 下面的自定义命令
const fs = require('fs');
let path = require('path');
const program = require('commander');
const download = require('download-git-repo'); //下载模版文件
const chalk = require('chalk'); //美化终端
const symbols = require('log-symbols'); //美化终端
const handlebars = require('handlebars'); //修改模版文件内容
const ora = require('ora'); //提示下载
var inquirer = require('inquirer'); //提示文本
const package = require('./package.json'); //获取版本信息
const re = new RegExp("^[A-Za-z0-9-]+$"); //检查文件名,字母数字中划线
var myDate = new Date();
function appendZero(obj) {
if (obj < 10) return "0" + "" + obj;
else return obj;
}
var versionDate = (`${myDate.getFullYear()}${appendZero(myDate.getMonth()+1)}${appendZero(myDate.getDate())}`);
program
.version(package.version, '-v,--version')
.command('init <name>') //规定的输入方式 ,需要 init **
.action(name => {
if (!re.test(name)) {
console.log(symbols.error, chalk.red('错误!请输入dd'));
return
}
if (!fs.existsSync(name)) {
inquirer
.prompt([])
.then(answers => {
console.log(symbols.success, chalk.green('开始创建..........,请稍候'));
const spinner = ora('正在下载模板...');
spinner.start();
download(`direct:https://github.com/aleilei123/init-tmp.git`, name,{ clone: true }, err => {
if (err) {
spinner.fail();
} else {
spinner.succeed();
var root_path = process.argv[2];
var MyUrl = `${root_path}/${name}`;
function myReadfile(MyUrl) {
fs.readdir(MyUrl, (err, files) => {
if (err) throw err
files.forEach(file => {
//拼接获取绝对路径,fs.stat(绝对路径,回调函数)
let fPath = path.join(MyUrl, file);
fs.stat(fPath, (err, stat) => {
//stat 状态中有两个函数一个是stat中有isFile ,isisDirectory等函数进行判断是文件还是文件夹
if (stat.isFile()) {
if (fPath == `${name}/src/index.html` || fPath == `${name}/webpack-user-config.js`) {
const content = fs.readFileSync(fPath).toString();
const result = handlebars.compile(content)({ projectName: name,versionDate: versionDate });
fs.writeFileSync(fPath, result);
}
}
else {
myReadfile(fPath)
}
})
})
})
}
myReadfile(name);
console.log(symbols.success, chalk.green('下载完成'));
}
});
});
} else {
console.log(symbols.error, chalk.red('有相同名称模版'));
}
});
program.parse(process.argv);
配置好后执行:
npm i -g
只有执行这个命名了,配置的bin下面的命令才可以使用。这样,其他文件需要此npm的时候,执行
npm install 包名
plus init **
‘plus’是bin下的文件,init是index.js规定的输入方式。然后就可以下载对应的模板到文件夹。
删除npm包
npm --force unpublish 包名