Skip to content

Latest commit

 

History

History
174 lines (128 loc) · 4.26 KB

README-zh_CN.md

File metadata and controls

174 lines (128 loc) · 4.26 KB

generate-history-method-webpack-plugin

一个根据约定式路由,自动生成路由方法的Webpack插件

NPM version NPM downloads

Test

中文 | 英文

📦 安装

pnpm add generate-history-method-webpack-plugin -D
# or
yarn add generate-history-method-webpack-plugin -D
# or
npm i generate-history-method-webpack-plugin -D

确保你的依赖有qs,否则请安装

pnpm add qs -D
# or
yarn add qs -D
# or
npm i qs -D

确保在你项目 src 下面export default对应的history:

比如你使用的是browser模式,可以参考react-router-6/src/browser_history.ts,那么导出该history

import type { BrowserHistory } from 'history'
import { createBrowserHistory } from 'history'

export type { BrowserHistory }
export default createBrowserHistory()

比如你使用的是hash模式,可以参考react-router-6/src/hash_history.ts,那么导出该history

import type { HashHistory } from 'history'
import { createHashHistory } from 'history'

export type { HashHistory }
export default createHashHistory()

⚙️ 参数

interface GenerateHistoryMethodWebpackPluginOptions {
  /**
   * @description 用来定义路由参数类型的文件名
   * @default index.params
   *  */
  paramsName?: string
  /**
   * @description 用来识别是路由页面的文件名
   * @default index.page
   */
  pageName?: string
  /**
   * 生成的history从哪个模块导入
   * @default ~history
   * @example
   * import history from '~history'
   */
  historyModuleName?: string
  /**
   * 你原先的history模块名
   * @default 'history'
   */
  originHistoryModuleName?: string
  /**
   * 哪个根目录下是存放页面的
   * @example
   * path.resolve(cwdPath, 'src/pages') */
  pagesRootPath: string
  /**
   * 路由模式,hash or brower
   * @default 'browser'
   */
  mode?: HistoryMode
  /** 
   *  react-router 版本, 目前支持 v5 和 v6 */
  reactRouterVersion: 5 | 6
}

🔨 使用

// webpack.config.js
const GenerateHistoryMethodWebpackPlugin = require('generate-history-method-webpack-plugin')
const path = require('path')

module.exports = {
  ...,
  plugins: [
    new GenerateHistoryMethodWebpackPlugin()
  ],
}

// 根目录新建 .generate-history-method.config.js
const path = require('path')
module.exports = {
  pagesRootPath: path.resolve(__dirname, 'src/pages'),
  originHistoryModuleName: '@/browser_history',
  reactRouterVersion: 6,
}

👇 例子

  • 如果你页面在目录 src/pages/system/setting/purchase_setting, 那么会自动提示对应的路由方法

  • 如果你在页面同目录下添加了如 index.params.ts 作为页面的参数类型, 那么当天调用方法并传参时,会有对应的类型提示
// order_detail/index.params.ts
export default interface Params {
  /** 这是订单id */
  id: string
}

更多的使用方法可以参考playgrounds下面的 src/app:

以及webpack.config.js:

📄 协议

generate-history-method-webpack-plugin 遵循 MIT 协议.