「这是我参与11月更文挑战的第23天,活动详情查看:2021最后一次更文挑战」
前言
本章要进入之前的设想,进入vue的脚手架搭建啦!
需求整理
- 我们需要一定的项目结构
- 将重复的代码内容存放在其中
开始实践
磨刀不误砍柴工,首先创建项目的一小步就是我们先创建一个文件夹用来存放我们的文件啦!(屁话)
初始化
我们先运行以下代码,初始化我们的package.json:
npm init or yarn init
安装依赖
然后我们需要安装yeoman的依赖
npm add yeoman-generator
安装完毕之后,我们进入项目中
创建主目录
我们在项目中创建generators/app/index.js、generators/template结构如图(内容地址之后会在文章底部放出来的)
创建好之后,我们需要对index.js进行一些编写了
const Generator = require('yeoman-generator')
module.exports = class extends Generator {
prompting() {
return this.prompt([
type: 'input',
name: 'name',
message: '你的项目名',
default: this.appname
]).then(answers => {
this.answers = answers
})
}
writing() {
}
}
这里 writing 我们就不能像之前那样就做一些简单的操作了,我们就需要对我们需要进行挖坑的模板进行内容填充,提供EJS的方法:(EJS官网)[ejs.bootcss.com/]
上面我们写入了两个方法,一个prompting方法,一个writing方法,实际上,写在这里的方法有一定的优先级顺序,在官网找到了相应的顺序,官网内容如下:
- initializing - Your initialization methods (checking current project state, getting configs, etc)
- prompting - Where you prompt users for options (where you’d call this.prompt())
- configuring - Saving configurations and configure the project (creating .editorconfig files and other metadata files)
- default - If the method name doesn’t match a priority, it will be pushed to this group.
- writing - Where you write the generator specific files (routes, controllers, etc)
- conflicts - Where conflicts are handled (used internally)
- install - Where installations are run (npm, bower)
- end - Called last, cleanup, say good bye, etc
按官网的顺序,写入的方法名字和上面的名字相同时,按上面的名字优先级顺序处理,如果与上面名字不同,则按default的优先级处理
部分代码
const Generator = require('yeoman-generator')
module.exports = class extends Generator {
prompting() {
return this.prompt([
type: 'input',
name: 'name',
message: '你的项目名',
default: this.appname
]).then(answers => {
this.answers = answers
})
}
writing() {
// 把每一个文件都通过模板转换到目标路径
// 通过数组循环的方式 去对应生成文件
const templates = [
'.editorconfig',
...
// 通用样式
'src/index.css',
// vue 入口页面
'src/main.ts',
]
templates.forEach(item => {
this.fs.copyTpl(
this.templatePath(item),
this.destinationPath(item),
this.answers
)
})
}
}
然后我们运行
npm link or yarn link
然后通过yeoman去运行我们的脚手架
yo zce vue // 我的文件名
这样一个简单的脚手架就完毕了,当然之后我们还可以加入更多的配置进行使用 地址:gitee.com/liuyinghao1…
发布
npm publish or yarn publish
输入完毕之后,会出现一个报错,原因是我们使用了淘宝镜像
解决方法
npm config set registry=http://registry.npmjs.org
or
yarn config set registry=http://registry.yarnpkg.org