Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考

vite-plugin-pages


File system based routing for Vue 3 / React / Solid applications using Vite


Getting Started


Vue


Install:

  1. ``` shell
  2. npm install -D vite-plugin-pages
  3. npm install vue-router
  4. ```

React


since v0.19.0 we only support react-router v6, if you are using react-router v5 use v0.18.2.


Install:

  1. ``` shell
  2. npm install -D vite-plugin-pages
  3. npm install react-router react-router-dom
  4. ```

Solid


Install:

  1. ``` shell
  2. npm install -D vite-plugin-pages
  3. npm install @solidjs/router
  4. ```

Vite config


Add to your vite.config.js :

  1. ``` js
  2. import Pages from 'vite-plugin-pages'

  3. export default {
  4.   plugins: [
  5.     // ...
  6.     Pages(),
  7.   ],
  8. }
  9. ```

Overview


By default a page is a Vue component exported from a .vue or .js file in the src/pages directory.

You can access the generated routes by importing the ~pages module in your application.

Vue


  1. ``` js
  2. import { createRouter } from 'vue-router'
  3. import routes from '~pages'

  4. const router = createRouter({
  5.   // ...
  6.   routes,
  7. })
  8. ```

Type

  1. ``` ts
  2. // vite-env.d.ts
  3. ///
  4. ```

React


experimental

  1. ``` js
  2. import { Suspense } from 'react'
  3. import {
  4.   BrowserRouter as Router,
  5.   useRoutes,
  6. } from 'react-router-dom'

  7. import routes from '~react-pages'

  8. const App = () => {
  9.   return (
  10.     <Suspense fallback={<p>Loading...</p>}>
  11.       {useRoutes(routes)}
  12.     </Suspense>
  13.   )
  14. }

  15. ReactDOM.render(
  16.   <Router>
  17.     <App />
  18.   </Router>,
  19.   document.getElementById('root'),
  20. )
  21. ```

Type

  1. ``` ts
  2. // vite-env.d.ts
  3. ///
  4. ```

Solid


experimental

  1. ``` tsx
  2. import { render } from 'solid-js/web'
  3. import { Router, useRoutes } from '@solidjs/router'
  4. import routes from '~solid-pages'

  5. render(
  6.   () => {
  7.     const Routes = useRoutes(routes)
  8.     return (
  9.       <Router>
  10.         <Routes />
  11.       </Router>
  12.     )
  13.   },
  14.   document.getElementById('root') as HTMLElement,
  15. )
  16. ```

Type

  1. ``` ts
  2. // vite-env.d.ts
  3. ///
  4. ```

Configuration


To use custom configuration, pass your options to Pages when instantiating the plugin:

  1. ``` js
  2. // vite.config.js
  3. import Pages from 'vite-plugin-pages'

  4. export default {
  5.   plugins: [
  6.     Pages({
  7.       dirs: 'src/views',
  8.     }),
  9.   ],
  10. }
  11. ```

dirs


Type:string | (string | PageOptions)[]
Default:'src/pages'

Paths to the pages directory. Supports globs.

Can be:

single path: routes point to /
array of paths: all routes in the paths point to /
array of PageOptions, Check below 👇

Specifying a glob or an array of PageOptions allow you to use multiple pages folder, and specify the base route to append to the path and the route name. Additionally, you can specify a pattern to filter the files that will be used as pages.

Example:

  1. ``` shell
  2. # folder structure
  3. src/
  4.   ├── features/
  5.   │  └── dashboard/
  6.   │     ├── code/
  7.   │     ├── components/
  8.   │     └── pages/
  9.   ├── admin/
  10.   │   ├── code/
  11.   │   ├── components/
  12.   │   └── pages/
  13.   └── pages/
  14. ```

  1. ``` js
  2. // vite.config.js
  3. export default {
  4.   plugins: [
  5.     Pages({
  6.       dirs: [
  7.         { dir: 'src/pages', baseRoute: '' },
  8.         { dir: 'src/features/**/pages', baseRoute: 'features' },
  9.         { dir: 'src/admin/pages', baseRoute: 'admin' },
  10.         { dir: 'src/with-pattern/pages', baseRoute: 'pattern', filePattern: '**/*.page.*' },
  11.       ],
  12.     }),
  13.   ],
  14. }
  15. ```

extensions


Type:string[]
Default:
Vue: ['vue', 'ts', 'js']
React: ['tsx', 'jsx', 'ts', 'js']
Solid: ['tsx', 'jsx', 'ts', 'js']

An array of valid file extensions for pages.

exclude


Type:string[]
Default:[]

An array of glob patterns to exclude matches.

  1. ``` shell
  2. # folder structure
  3. src/pages/
  4.   ├── users/
  5.   │  ├── components
  6.   │  │  └── form.vue
  7.   │  ├── [id].vue
  8.   │  └── index.vue
  9.   └── home.vue
  10. ```

  1. ``` js
  2. // vite.config.js
  3. export default {
  4.   plugins: [
  5.     Pages({
  6.       exclude: ['**/components/*.vue'],
  7.     }),
  8.   ],
  9. }
  10. ```

importMode


Type:'sync' | 'async' | (filepath: string, pluginOptions: ResolvedOptions) => 'sync' | 'async')
Default:
Top level index file: 'sync', others: async.

Import mode can be set to either async, sync, or a function which returns one of those values.

To get more fine-grained control over which routes are loaded sync/async, you can use a function to resolve the value based on the route path. For example:

  1. ``` js
  2. // vite.config.js
  3. export default {
  4.   plugins: [
  5.     Pages({
  6.       importMode(filepath, options) {
  7.         // default resolver
  8.         // for (const page of options.dirs) {
  9.         //   if (page.baseRoute === '' && filepath.startsWith(`/${page.dir}/index`))
  10.         //     return 'sync'
  11.         // }
  12.         // return 'async'

  13.         // Load about page synchronously, all other pages are async.
  14.         return filepath.includes('about') ? 'sync' : 'async'
  15.       },
  16.     }),
  17.   ],
  18. }
  19. ```

If you are using async mode with react-router, you will need to wrap your route components with Suspense :

  1. ``` js
  2. const App = () => {
  3.   return (
  4.     <Suspense fallback={<p>Loading...</p>}>
  5.       {useRoutes(routes)}
  6.     </Suspense>
  7.   )
  8. }
  9. ```

routeBlockLang


Type:string
Default:'json5'

Default SFC route block parser.

routeStyle


Type:'next' | 'nuxt' | 'remix'
Default:next

Use file system dynamic routing supporting:

Nextjs Routing
Nuxtjs Routing
Remix Routing

routeNameSeparator


Type:string
Default:-

Separator for generated route names.

resolver


Type:'vue' | 'react' | 'solid' | PageResolver
Default:'auto detect'

Route resolver, support vue, react, solid or custom PageResolver.

moduleId


Type:string
Default:
Vue: '~pages'
React: '~react-pages'
Solid: '~solid-pages'

Module id for routes import, useful when you what to use multiple pages plugin in one project.

extendRoute


Type:(route: any, parent: any | undefined) => any | void

A function that takes a route and optionally returns a modified route. This is useful for augmenting your routes with extra data (e.g. route metadata).

  1. ``` js
  2. // vite.config.js
  3. export default {
  4.   // ...
  5.   plugins: [
  6.     Pages({
  7.       extendRoute(route, parent) {
  8.         if (route.path === '/') {
  9.           // Index is unauthenticated.
  10.           return route
  11.         }

  12.         // Augment the route with meta that indicates that the route requires authentication.
  13.         return {
  14.           ...route,
  15.           meta: { auth: true },
  16.         }
  17.       },
  18.     }),
  19.   ],
  20. }
  21. ```

onRoutesGenerated


Type:(routes: any[]) => Awaitable<any[] | void>

A function that takes a generated routes and optionally returns a modified generated routes.

onClientGenerated


Type:(clientCode: string) => Awaitable<string | void>

A function that takes a generated client code and optionally returns a modified generated client code.

SFC custom block for Route Data


Add route meta to the route by adding a <route> block to the SFC. This will be directly added to the route after it is generated, and will override it.

You can specific a parser to use using <route lang="yaml">, or set a default parser using routeBlockLang option.

Supported parser:JSON, JSON5, YAML
Default:JSON5

JSON/JSON5:

  1. ``` html
  2. <route>
  3. {
  4.   name: "name-override",
  5.   meta: {
  6.     requiresAuth: false
  7.   }
  8. }
  9. </route>
  10. ```

YAML:

  1. ``` html
  2. <route lang="yaml">
  3. name: name-override
  4. meta:
  5.   requiresAuth: true
  6. </route>
  7. ```

Syntax Highlighting <route>


To enable syntax highlighting <route> in VS Code using Vetur's Custom Code Blocks add the following snippet to your preferences...

update setting

  1. ``` sh
  2. "vetur.grammar.customBlocks": {
  3.    "route": "json"
  4. }

  5. ```

Run the command in vscode

Vetur: Generate grammar from vetur.grammar.customBlocks

Restart VS Code to get syntax highlighting for custom blocks.

JSX/TSX YAML format comments for Route Data(In Vue)


Add route meta to the route by adding a comment block starts with route to the JSX or TSX file(In Vue). This will be directly added to the route after it is generated, and will override it.

This feature only support JSX/TSX in vue, and will parse only the first block of comments which should also start with route.

Now only yaml parser supported.

Type:'vue'
Supported parser:YAML

  1. ``` js
  2. /*
  3. route

  4. name: name-override
  5. meta:
  6.   requiresAuth: false
  7.   id: 1234
  8.   string: "1234"
  9. */
  10. ```

File System Routing


Inspired by the routing from NuxtJS 💚

Pages automatically generates an array of routes for you to plug-in to your instance of Vue Router. These routes are determined by the structure of the files in your pages directory. Simply create .vue files in your pages directory and routes will automatically be created for you, no additional configuration required!

For more advanced use cases, you can tailor Pages to fit the needs of your app through configuration.

Basic Routing
Index Routes
Dynamic Routes
Nested Routes
Catch-all Routes

Basic Routing


Pages will automatically map files from your pages directory to a route with the same name:

src/pages/users.vue -> /users
src/pages/users/profile.vue -> /users/profile
src/pages/settings.vue -> /settings

Index Routes


Files with the name index are treated as the index page of a route:

src/pages/index.vue -> /
src/pages/users/index.vue -> /users

Dynamic Routes


Dynamic routes are denoted using square brackets. Both directories and pages can be dynamic:

src/pages/users/[id].vue -> /users/:id (/users/one )
src/pages/[user]/settings.vue -> /:user/settings (/one/settings )

Any dynamic parameters will be passed to the page as props. For example, given the file src/pages/users/[id].vue, the route /users/abc will be passed the following props:

  1. ``` json
  2. { "id": "abc" }
  3. ```

Nested Routes


We can make use of Vue Routers child routes to create nested layouts. The parent component can be defined by giving it the same name as the directory that contains your child routes.

For example, this directory structure:

  1. ``` sh
  2. src/pages/
  3.   ├── users/
  4.   │  ├── [id].vue
  5.   │  └── index.vue
  6.   └── users.vue

  7. ```

will result in this routes configuration:

  1. ``` js
  2. [
  3.   {
  4.     "path": "/users",
  5.     "component": "/src/pages/users.vue",
  6.     "children": [
  7.       {
  8.         "path": "",
  9.         "component": "/src/pages/users/index.vue",
  10.         "name": "users"
  11.       },
  12.       {
  13.         "path": ":id",
  14.         "component": "/src/pages/users/[id].vue",
  15.         "name": "users-id"
  16.       }
  17.     ]
  18.   }
  19. ]
  20. ```

Catch-all Routes


Catch-all routes are denoted with square brackets containing an ellipsis:

src/pages/[...all].vue -> /* (/non-existent-page )

The text after the ellipsis will be used both to name the route, and as the name of the prop in which the route parameters are passed.

Sitemap generation


If you need to generate a sitemap from generated routes, you can use vite-plugin-pages-sitemap. This plugin allow you to automatically generate sitemap.xml and robots.xml files with customization.

License


MIT License © 2021-PRESENT hannoeru
Last Updated: 2023-05-23 11:11:51