## Vue根据自定义模板生成项目[vue-cli/preset]
- 前端开发形成自己的一套代码了之后,每次新建项目按照自己习惯的模版创建
- 需要准备内容包含三个件
- generator/index.js
- preset.json
- template 自己封装的一套代码
- 如图:
- [](https://static.adong.wiki/static/images/md/2021110101.png)
- 模版中增加了常用的函数,日常积累,和一些基础封装 axios,store的常用处理
generator/index.js 文件内容
``` javascript
const fs = require('fs');
const tool = (api) => {
return {
deleteFile(path) {
const file = api.resolve(path);
if (fs.existsSync(file)) {
fs.unlinkSync(file);
}
},
deleteDir(path) {
const dir = api.resolve(path);
if (fs.existsSync(dir)) {
fs.readdirSync(dir).forEach((o) => {
const file = dir + '\\' + o;
if (fs.statSync(file).isDirectory()) {
fs.readdirSync(dir).forEach((p) => {
fs.unlinkSync(dir + '\\' + o + '\\' + p);
});
} else {
fs.unlinkSync(file);
}
});
fs.rmdirSync(dir);
}
}
};
};
module.exports = (api, options, rootOptions) => {
const utils = tool(api);
// 命令
api.extendPackage({
scripts: {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
});
// 安装一些基础公共库
api.extendPackage({
dependencies: {
"core-js": "^3.6.4",
"vue": "^2.6.11",
"vue-router": "^3.1.5",
"vuex": "^3.1.2",
"element-ui": "^2.15.6",
"vant": "^2.12.31",
"axios": "^0.24.0",
},
devDependencies: {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"less": "^3.0.4",
"less-loader": "^5.0.0",
"vue-template-compiler": "^2.6.11"
}
});
api.render('../template');
api.onCreateComplete(() => {
process.env.VUE_CLI_SKIP_WRITE = true;
});
};
```
preset.json 文件内容
``` javascript
{
"useConfigFiles": true,
"plugins": {
"@vue/cli-plugin-babel": {},
"@vue/cli-plugin-router": {
"historyMode": true
},
"@vue/cli-plugin-vuex": {}
},
"cssPreprocessor": "less"
}
```
#### 将模版上传 github
- [https://github.com/adongge/vue-base-template](https://github.com/adongge/vue-base-template)
#### 安装vue3 cli
``` Bash
npm install -g @vue/cli
```
#### 创建项目
``` Bash
vue create --preset adongge/vue-base-template demo
```
#### 运行后,浏览器查看效果,对应的依赖都已完成安装,直接开始实际开发,可以封装自己常用的功能模块快速新建直接运行
- [](https://static.adong.wiki/static/images/md/2021110102.png)
#### 待续...