Vite/TypeScript项目导入JSONC文件及前后端路由共享方案咨询
解决Vue+TypeScript导入JSONC路由文件的问题及前后端路由共享最优方案
一、修复JSONC文件导入的TypeScript错误
如果坚持使用JSONC文件,需解决TypeScript识别和构建工具解析问题,步骤如下:
1. 添加JSONC类型声明
在项目src目录下创建jsonc.d.ts类型声明文件,告知TypeScript如何解析.jsonc模块:
declare module '*.jsonc' { // 定义共享路由类型 export type SharedRoute = { path: string; name: string; componentName: string; }; const routes: SharedRoute[]; export default routes; }
确保tsconfig.json的include字段包含该声明文件:
{ "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.jsonc"] }
2. 配置构建工具支持JSONC
若使用Vite,需配置Rollup插件解析带注释的JSONC:
- 安装依赖:
npm install @rollup/plugin-json --save-dev - 修改
vite.config.ts:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import json from '@rollup/plugin-json' export default defineConfig({ plugins: [ vue(), json({ allowComments: true, // 允许JSONC中的注释 namedExports: true }) ], resolve: { extensions: ['.jsonc', '.json', '.js', '.ts', '.vue'] } })
3. 正确导入JSONC文件
现在可正常导入路由文件并映射组件:
import routes from '../routes.jsonc' import { createRouter, createWebHistory } from 'vue-router' const routerRoutes = routes.map(route => ({ ...route, component: () => import(`../views/${route.componentName}.vue`) })) const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: routerRoutes })
二、前后端路由共享的最优方案:用TypeScript作为单一数据源
JSONC缺乏类型校验,维护易出错,推荐用TypeScript文件作为路由单一数据源,通过脚本生成后端所需代码:
1. 创建共享路由TS文件
在src/shared/routes.ts中定义路由结构和具体配置:
// 路由类型,前后端可复用 export type SharedRoute = { path: string; name: string; componentName: string; }; // 具体路由配置 export const sharedRoutes: SharedRoute[] = [ { path: '/', name: 'Home', componentName: 'Home' }, { path: '/dashboard', name: 'Dashboard', componentName: 'Dashboard' }, // 更多路由... ];
2. 前端Vue-Router集成
直接导入TS文件并动态映射组件:
import { createRouter, createWebHistory } from 'vue-router' import { sharedRoutes } from './shared/routes' const routerRoutes = sharedRoutes.map(route => ({ ...route, component: () => import(`../views/${route.componentName}.vue`) })) const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: routerRoutes }) export default router
3. 后端Actix-Web集成
编写Node脚本自动生成Rust路由代码:
- 安装依赖:
npm install ts-node typescript --save-dev - 创建
scripts/generate-routes.js:
const fs = require('fs'); const { sharedRoutes } = require('../src/shared/routes'); // 生成符合Rust语法的路由代码 const rustCode = ` use serde::Deserialize; #[derive(Debug, Clone, Deserialize)] pub struct SharedRoute { pub path: String, pub name: String, pub component_name: String, } pub const SHARED_ROUTES: &[SharedRoute] = &[ ${sharedRoutes.map(route => `SharedRoute { path: "${route.path}".to_string(), name: "${route.name}".to_string(), component_name: "${route.componentName}".to_string(), }`).join(',\n ')} ]; `; // 写入后端目录 fs.writeFileSync('./server/src/routes.rs', rustCode); console.log('Rust路由代码生成成功');
- 在
package.json添加脚本:
{ "scripts": { "generate-routes": "ts-node scripts/generate-routes.js" } }
- 修改路由后运行
npm run generate-routes,后端即可获取最新路由配置,无需手动维护两份文件。
三、方案优势
- TypeScript提供类型校验,避免路由配置错误
- 单一数据源,修改路由只需更新TS文件,自动同步前后端
- 支持注释、类型提示,比JSONC更易维护
内容的提问来源于stack exchange,提问作者maribox
相关产品推荐
相关产品推荐

