EggJS

项目初始化

npm init egg -type=ts
// 后续选择 ts 版本

[egg-init] use registry: <https://registry.npmjs.org>
[egg-init] target dir is /Users/yangliang/Desktop/project/github/learning-js/Vue3/实战/news-pro-vue3/api
[egg-init] fetching npm info of egg-init-config
? Please select a boilerplate type ts - Simple egg && typescript app boilerplate
[egg-init] use boilerplate: ts(egg-boilerplate-ts)
[egg-init] fetching npm info of egg-boilerplate-ts
[egg-init] downloading <https://registry.npmjs.org/egg-boilerplate-ts/-/egg-boilerplate-ts-1.7.0.tgz>
[egg-init] extract to /var/folders/z7/vzm1yfhj4f13pkkw4rprbhww0000gn/T/egg-init-boilerplate
[egg-init] collecting boilerplate config...
? project name api
? project description Data API for news-vue3
? project author Lance
? cookie security keys 1647505056274_5269

// 最后
npm install

egg-cors 解决跨域问题

npm i egg-cors -S
import { EggPlugin } from 'egg';

const plugin: EggPlugin = {
  cors: {
    enable: true,
    package: 'egg-cors'
  }
};

export default plugin;
export default (appInfo: EggAppInfo) => {
  ...
  // cors 跨域配置
  config.cors = {
    origin: () => '*', // 保证所有域名访问都能过来
    allowMethods: 'GET,PUT,POST,DELETE,HEAD,PATCH',
    credentials: true
  }
  // csrf安全关闭
  config.security = {
    csrf: {
      enable: false
    }
  }
  // 聚合配置
  config.userConfig = {
    APP_KEY: 'your api key',
    API: {
      GET_NEWS_LIST: '<http://v.juhe.cn/toutiao/index>'
    }
  }

  // the return config will combines to EggAppConfig
  return {
    ...config,
    ...bizConfig,
  };
};

Vue3

路由

动态路由起别名

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/detail/:uniquekey/:from',
    name: 'Detail',
    component: () => import(/* webpackChunkName: "detail" */'../views/Detail.vue')
  },
  {
    path: '/mynews',
    name: 'MyNews',
    component: () => import(/* webpackChunkName: "mynews" */'../views/MyNews.vue')
  }
]

动态 header 配置

export const headerInfos: Array<IHeaderInfo> = [
  {
    // 路由名称
    name: 'Home',
    // header标题
    title: '新闻头条',
    // 左图标是否显示
    left: false,
    // 右图标是否显示
    right: true,
    // 左边显示的图标名称 // 'iconfont icon-' + ...path
    leftIcon: '',
    // 右边显示的图标名称
    rightIcon: 'mine',
    // 左边图标的路由
    leftPath: '',
    rightPath: '/mynews'
  },
  {
    // 路由名称
    name: 'Detail',
    // header标题
    title: '新闻详情',
    // 左图标是否显示
    left: true,
    // 右图标是否显示
    right: true,
    // 左边显示的图标名称 // 'iconfont icon-' + ...path
    leftIcon: 'arrow-right',
    // 右边显示的图标名称
    rightIcon: 'star-o',
    // 左边图标的路由
    leftPath: '',
    rightPath: ''
  },
  {
    // 路由名称
    name: 'MyNews',
    // header标题
    title: '收藏列表',
    // 左图标是否显示
    left: true,
    // 右图标是否显示
    right: false,
    // 左边显示的图标名称 // 'iconfont icon-' + ...path
    leftIcon: 'arrow-right',
    // 右边显示的图标名称
    rightIcon: '',
    // 左边图标的路由
    leftPath: '',
    rightPath: ''
  }
]

const routes: Array<RouteRecordRaw> = [...]