UNPKG

vue3-quickstart-cli

Version:

一个用于快速创建 Vue3 项目的脚手架工具。

41 lines (37 loc) 1.53 kB
import path from 'path'; import fs from 'fs-extra'; import chalk from 'chalk'; export default function genRouter(targetDir, pkg) { pkg.dependencies['vue-router'] = '^4.3.0'; const routerDir = path.join(targetDir, 'src/router'); fs.ensureDirSync(routerDir); // 优先生成 router/index.ts fs.writeFileSync(path.join(routerDir, 'index.ts'), `import { createRouter, createWebHistory } from 'vue-router'; import Home from '../App.vue'; const routes = [ { path: '/', name: 'Home', component: Home } ]; const router = createRouter({ history: createWebHistory(), routes }); export default router; `); // 挂载 router,自动判断 main.ts/main.js const mainTs = path.join(targetDir, 'src/main.ts'); const mainJs = path.join(targetDir, 'src/main.js'); let mainPath = fs.existsSync(mainTs) ? mainTs : mainJs; if (fs.existsSync(mainPath)) { let mainCode = fs.readFileSync(mainPath, 'utf-8'); // 如果没有引入 router,则插入 import router if (!mainCode.includes("import router from './router'")) { mainCode = mainCode.replace(/(import App from .+;\n)/, `$1import router from './router';\n`); } // 如果没有 app.use(router),则插入 if (!mainCode.includes('app.use(router)')) { mainCode = mainCode.replace(/(const app = createApp\([^)]*\);?\n)/, `$1\napp.use(router);\n`); } fs.writeFileSync(mainPath, mainCode, 'utf-8'); } console.log(chalk.green('已集成 Vue Router!')); }