npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

abulo-vite-plugin-pages

v1.0.3

Published

File system base vue-router plugin for Vite

Downloads

9

Readme

abulo-vite-plugin-pages

npm version monthly downloads types license

Open in Visual Studio Code

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

Getting Started

Vue

Install:

npm install -D abulo-vite-plugin-pages
npm install vue-router

React

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

Install:

npm install -D abulo-vite-plugin-pages
npm install react-router react-router-dom 

Solid

Install:

npm install -D abulo-vite-plugin-pages
npm install @solidjs/router

Vite config

Add to your vite.config.js:

import Pages from 'abulo-vite-plugin-pages'

export default {
  plugins: [
    // ...
    Pages(),
  ],
}

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

import { createRouter } from 'vue-router'
import routes from '~pages'

const router = createRouter({
  // ...
  routes,
})

Type

// vite-env.d.ts
/// <reference types="abulo-vite-plugin-pages/client" />

React

experimental

import { Suspense } from 'react'
import {
  BrowserRouter as Router,
  useRoutes,
} from 'react-router-dom'

import routes from '~react-pages'

const App = () => {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      {useRoutes(routes)}
    </Suspense>
  )
}

ReactDOM.render(
  <Router>
    <App />
  </Router>,
  document.getElementById('root'),
)

Type

// vite-env.d.ts
/// <reference types="abulo-vite-plugin-pages/client-react" />

Solid

experimental

import { render } from 'solid-js/web'
import { Router, useRoutes } from '@solidjs/router'
import routes from '~solid-pages'

render(
  () => {
    const Routes = useRoutes(routes)
    return (
      <Router>
        <Routes />
      </Router>
    )
  },
  document.getElementById('root') as HTMLElement,
)

Type

// vite-env.d.ts
/// <reference types="abulo-vite-plugin-pages/client-solid" />

Configuration

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

// vite.config.js
import Pages from 'abulo-vite-plugin-pages'

export default {
  plugins: [
    Pages({
      dirs: 'src/views',
    }),
  ],
}

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:

# folder structure
src/
  ├── features/
  │  └── dashboard/
  │     ├── code/
  │     ├── components/
  │     └── pages/
  ├── admin/
  │   ├── code/
  │   ├── components/
  │   └── pages/
  └── pages/
// vite.config.js
export default {
  plugins: [
    Pages({
      dirs: [
        { dir: 'src/pages', baseRoute: '' },
        { dir: 'src/features/**/pages', baseRoute: 'features' },
        { dir: 'src/admin/pages', baseRoute: 'admin' },
        { dir: 'src/with-pattern/pages', baseRoute: 'pattern', filePattern: '**/*.page.*' },
      ],
    }),
  ],
}

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.

# folder structure
src/pages/
  ├── users/
  │  ├── components
  │  │  └── form.vue
  │  ├── [id].vue
  │  └── index.vue
  └── home.vue
// vite.config.js
export default {
  plugins: [
    Pages({
      exclude: ['**/components/*.vue'],
    }),
  ],
}

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:

// vite.config.js
export default {
  plugins: [
    Pages({
      importMode(filepath, options) {
        // default resolver
        // for (const page of options.dirs) {
        //   if (page.baseRoute === '' && filepath.startsWith(`/${page.dir}/index`))
        //     return 'sync'
        // }
        // return 'async'

        // Load about page synchronously, all other pages are async.
        return filepath.includes('about') ? 'sync' : 'async'
      },
    }),
  ],
}

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

const App = () => {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      {useRoutes(routes)}
    </Suspense>
  )
}

routeBlockLang

  • Type: string
  • Default: 'json5'

Default SFC route block parser.

routeStyle

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

Use file system dynamic routing supporting:

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).

// vite.config.js
export default {
  // ...
  plugins: [
    Pages({
      extendRoute(route, parent) {
        if (route.path === '/') {
          // Index is unauthenticated.
          return route
        }

        // Augment the route with meta that indicates that the route requires authentication.
        return {
          ...route,
          meta: { auth: true },
        }
      },
    }),
  ],
}

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:

<route>
{
  name: "name-override",
  meta: {
    requiresAuth: false
  }
}
</route>

YAML:

<route lang="yaml">
name: name-override
meta:
  requiresAuth: true
</route>

Syntax Highlighting <route>

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

  1. update setting
"vetur.grammar.customBlocks": {
   "route": "json"
 }
  1. Run the command in vscode

Vetur: Generate grammar from vetur.grammar.customBlocks

  1. 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
/*
route

name: name-override
meta:
  requiresAuth: false
  id: 1234
  string: "1234"
*/

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

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:

{ "id": "abc" }

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:

src/pages/
  ├── users/
  │  ├── [id].vue
  │  └── index.vue
  └── users.vue

will result in this routes configuration:

[
  {
    "path": "/users",
    "component": "/src/pages/users.vue",
    "children": [
      {
        "path": "",
        "component": "/src/pages/users/index.vue",
        "name": "users"
      },
      {
        "path": ":id",
        "component": "/src/pages/users/[id].vue",
        "name": "users-id"
      }
    ]
  }
]

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 abulo-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