自定义项目模版开发
mkdir imooc-cli-dev-template-custom-vue2
cd imooc-cli-dev-template-custom-vue2
npm init -y
touch index.js
# 修改 package.json 中的 "main": "index.js"
npm publish
自定义模版安装逻辑开发
// 部分代码
async installCustomTemplate() {
// 查询自定义模板的入口文件
if (await this.templateNpm.exists()) {
const rootFile = this.templateNpm.getRootFilePath();
if (fs.existsSync(rootFile)) {
log.notice('开始执行自定义模板');
const templatePath = path.resolve(this.templateNpm.cacheFilePath, 'template');
const options = {
templateInfo: this.templateInfo,
projectInfo: this.projectInfo,
sourcePath: templatePath,
targetPath: process.cwd(),
};
const code = `require('${rootFile}')(${JSON.stringify(options)})`;
log.verbose('code', code);
await execAsync('node', ['-e', code], { stdio: 'inherit', cwd: process.cwd() });
log.success('自定义模板安装成功');
} else {
throw new Error('自定义模板入口文件不存在!');
}
}
}
自定义项目 index.js 中代码,大体移植了 ejsRender函数、installNormalTemplate函数。大概是:脚手架框架提供“加载执行自定义项目 index.js” 的功能,用户自己在 index.js 中写“拷贝缓存模版代码”、“ejs渲染输入模版信息”等功能代码。这样用户自由度更高,好多东西可以按照自己的格式来。
自定义模版上线
......