Node实现自动配置路由~

517 阅读3分钟

直接上干货,因为我也是初学node,哈哈~

首先创建一个node模块create-Vue-Routers,里边创建一个bin文件夹和lib文件夹,执行npm init -y 初始化一下

再安装相关包 npm i commander download-git-repo ora handlebars figlet clear chalk open -s 介个时候node模块应该是介个亚子的

image.png 在bin文件夹下创建create.js,敲黑板划重点在create.js的开头要指定脚本解释器为node (#!/usr/bin/env node 解释器)

//create-Vue-Router/bin/create.js
#!/usr/bin/env node
const program = require('commander') //command 添加命令名称
program.version(require('../package.json')) //指定版本号,这里是指定到package.js里的版本号
program
    .command('routers')  //指定命令名称
    .description('create routers...')  //该命令的解释
    .action(require('../lib/create')) //该命令要运行的内容
program.parse(process.argv) //解析命令行参数,注意这个方法一定要放到最后调用
//process 对象是一个全局变量,它提供当前 Node.js 进程的有关信息,以及控制当前 Node.js 进程。 因为是全局变量,所以无需使用 require()。
/* process.argv 属性返回一个数组,这个数组包含了启动Node.js进程时的命令行参数,
其中:
数组的第一个元素process.argv[0]——返回启动Node.js进程的可执行文件所在的绝对路径
第二个元素process.argv[1]——为当前执行的JavaScript文件路径 */

#!/usr/bin/env node一定要写在最前面否则不管用 在package.json中添加命令“ccr”(随便起的命令名)

//create-Vue-Router/package.json
 "name": "createVueRouters",
  "version": "1.0.0",
  "main": "index.js",
  "bin": {
    "ccr": "bin/create.js"
  },

执行npm link,与本地连接,现在就可以执行ccr routers这个命令啦,接下来完善这个命令的执行内容

lib文件夹下创建create.js

//create-Vue-Router/lib/create.js
const fs = require('fs')
const handlebars = require('handlebars')  //前端模版引擎
const chalk = require('chalk')
module.exports = async () => {
    // 获取页面列表 
    // 以下路径都是相对vue项目的路径
    const list = fs.readdirSync('./src/views') //读取views文件夹下的所有文件
        .filter(v => v !== 'Home.vue')   //Home.vue是对应路由里的首页不需要被自动创建的路由也就是path:‘/’,可根据项目需要自定义排除某个文件或者某些文件
        .map(v => ({
            name: v.replace('.vue', '').toLowerCase(),  // replace将.vue的后缀替换成空,然后小写
            file: v  //文件位置
        }))
    // 生成路由定义 
    compile({ list }, './src/router/index.js', './template/router.js.hbs')
    /*** 
     * 编译模板文件 
   * @param meta 数据定义 *
   *  @param filePath 目标文件路径 *
   *  @param templatePath 模板文件路径
发布npm
*/
    function compile(meta, filePath, templatePath) {
        if (fs.existsSync(templatePath)) { //fs.existsSync(path)如果存在该路径则返回true反之false
            const content = fs.readFileSync(templatePath).toString();//获取模版里的内容
            const result = handlebars.compile(content)(meta);  //预编译一个模版并立即执行
            fs.writeFileSync(filePath, result);//fs.writeFileSync()方法用于将数据同步写入文件。如果该文件已经存在,则替换该文件。
        }
        console.log(chalk.green(`🚀${filePath} 创建成功`)) //黑板颜色改为绿色
    }
}

这里贴一个模版引擎的官网handlebarsjs.com/zh/api-refe…

//const result = handlebars.compile(content)(meta); 
 //这里写成这样比较好理解
const tamplate = handlebars.compile(content)
const result = tamplate(meta)

到这一步node模块应该长介个亚子

image.png

接下来到vue项目目录下完善一下预编译时的模版

compile({ list }, './src/router/index.js', './template/router.js.hbs')

在vue项目下创建tamplate文件夹,里边用的是代码模板渲染 hbs Mustache风格模板router.js.hbs 里边的内容就可以根据项目需要自行编辑

import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/components/Layout.vue'
Vue.use(VueRouter)

const routes = [
    {
    path: '/login', // 登录
    name: 'login',
    component: () => import('@/components/login.vue')
  },
  {
    path: '/', // tab页
    name: 'silder',
    component: () => import('@/components/silder.vue')
  },
     {{#each list}}   //模版引擎的遍历方式
      {
    path: '/{{name}}',
    name:'{{name}}',
    component: Layout,
    children: [
      {
        path: '/{{name}}',
         component: () => import('@/views/{{file}}')
      }
    ]
  },
    {{/each}}  
  ]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  if (sessionStorage.getItem('accessToken')) {
    next()
  } else {
    if (to.fullPath === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})
export default router

现在在views里疯狂创建项目需要的文件,只执行 crr routers 即可自动配置路由喽~ 里边还有很多好玩的东西我还没学会,下次再继续分享~