Coder Social home page Coder Social logo

vue-cli-plugin-auto-routing's Introduction

vue-cli-plugin-auto-routing

vue-cli-plugin-auto-routing Dev Token

Vue CLI plugin that provides auto routing feature.

Overview

Ensure you are in a project generated by Vue CLI >= v3. You install this plugin by running the following command:

# If you did not install router plugin yet
$ vue add router

# Install vue-cli-plugin-auto-routing
$ vue add auto-routing

After adding the plugin, the file structure will be the below.

src/
├── pages/
├── layouts/
└── router/

Pages

.vue files under the pages/ directory will be automatically resolved to generate routing. Vue Router routes options will be configured with the file structure under the pages/. The generated routing is same with Nuxt's routing.

Note that directories and files started and ended with __ (two underscores, e.g. __foo__.vue) will be ignored.

For example, when you have the following page components:

pages/
├── __partial__.vue
├── index.vue
├── users.vue
└── users/
    └── _id.vue

It is resolved to the below routes. Note that _ prefixed components generate dynamic routing.

export default [
  {
    name: 'index',
    path: '/',
    component: () => import('@/pages/index.vue')
  },
  {
    name: 'users',
    path: '/users',
    component: () => import('@/pages/users.vue'),
    children: [
      {
        name: 'users-id',
        path: ':id?',
        component: () => import('@/pages/users/_id.vue')
      }
    ]
  }
]

If you want to make route param required, create a directory for the param and add index.vue in the directory. In the above example, if you replace users/_id.vue with users/_id/index.vue, :id param will be required.

<route> custom block

If a page component has <route> custom block, the content json will be merged with route config.

For example, if index.vue has the following <route> block:

<route>
{
  "name": "home",
  "meta": {
    "requiresAuth": true
  }
}
</route>

<template>
  <h1>Hello</h1>
</template>

The generated route config is like the following:

module.exports = [
  {
    name: 'home',
    path: '/',
    component: () => import('@/pages/index.vue'),
    meta: {
      requiresAuth: true
    }
  }
]

Layouts

Components under the layouts/ directory will be used as shared layout component in the application. You can choose a layout by specifying layout component option in a page component. The default value of layout is 'default'. That means when you omit layout options, layouts/default.vue will be choosed as the layout component. This is the same concept with Nuxt's layouts.

For example, when you have layouts/foo.vue and pages/index.vue:

<!-- layouts/foo.vue -->
<template>
  <div>
    <h1>Foo Layout</h1>
    <router-view />
  </div>
</template>
<!-- pages/index.vue -->
<template>
  <p>index.vue</p>
</template>

<script>
export default {
  // You can specify layout component name here (default value is 'default')
  layout: 'foo'
}
</script>

The following html will be rendered:

<div>
  <h1>Foo Layout</h1>
  <p>index.vue</p>
</div>

Modifying Chunk Name

A chunk name from auto generated file can be conflicted with your code. You may see the below error log in that case:

 ERROR  Failed to compile with 1 errors
 error  in ./node_modules/vue-auto-routing/index.js
It's not allowed to load an initial chunk on demand. The chunk name "index" is already used by an entrypoint.
 ERROR  Build failed with errors.
error Command failed with exit code 1.

To avoid this error, you can set chunkNamePrefix option to change the auto generated chunk name.

// vue.config.js

module.exports = {
  pluginOptions: {
    autoRouting: {
      // Specify a prefix which will be added to all auto generated chunk name.
      chunkNamePrefix: 'page-'
    }
  }
}

Options

You can specify options for this plugin under pluginOptions.autoRouting in vue.config.js. The options are simply passed to vue-auto-routing options. You can see the available options list here.

// vue.config.js

module.exports = {
  pluginOptions: {
    autoRouting: {
      // Optionally specify a custom output file, relative to the project root
      outFile: "src/router/routes.js",
      // Specify other vue-auto-routing options here
      nested: false
    }
  }
}

Related Projects

License

MIT

vue-cli-plugin-auto-routing's People

Contributors

aggre avatar bencelang avatar dependabot-preview[bot] avatar dependabot[bot] avatar ilyasemenov avatar ktsn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

vue-cli-plugin-auto-routing's Issues

[Feature Request] Default to not use optional parameters

According to the readme:

If you want to make route param required, create a directory for the param and add index.vue in the directory. In the above example, if you replace users/_id.vue with users/_id/index.vue, :id param will be required.

The current implementation automatically append the optional parameters ? to the dynamic routes.
This feels like not so intuitively. I believe people will just expect a normal dynamic route without ? appended.

My suggestion is make the default behavior to not appending the ?, if one wish it be an optional parameter, they could append ? to the filename on demand.

Further more, the route could just be : + filename.substring(1), this way we can define Repeatable params and Custom Regexp in params as well.

@ktsn
If you are OK for this, I'd like send a PR, what do you think?

Can I pass component props to layout component?

I'm wondering if it's possible to pass component props to layout component?

For example:

pages/about.vue

<template>
...
</template>

<script>
export default {
  layout: {
    name: 'foo',
    props: {title: 'bar'}
  }
}
</script>

layouts/foo.vue

<template>
  <div>
    <h1>{{ title }}</h1>
    <router-view />
  </div>
</template>

<script>
export default {
  props: {
    title: String
  }
}
</script>

Syntax Error

Hi,

I get this error after running webpack.

ERROR in ./router.js
Module build failed: SyntaxError: Unexpected token (11:9)

   9 |
  10 | const RouterLayout = createRouterLayout(layout => {
> 11 |   return import ('@/layouts/' + layout + '.vue');
     |          ^
  12 | })

node: v10.2.1
npm: v6.3.0

new files and folders under pages are not detected

I have to stop/start serving on the vue cli ui page to get new items to show up. Also, if the layout is updated, a full reload of the page is required for the changes to show.

I am using the latest version of the plugin.

How to handle 404s?

Well, I have a problem with 404s.

If I create a file pages/_.vue or pages/*.vue it hangs the development server and I cannot test my app.

If I create a file pages/_404.vue it seems to work well but only for urls like /something but not for /some/thing

I don't want to create many files like pages/_404/_404.vue or any other like that. I'd like to handle 404s in one file.

Is there any way to do that?

Error in render: "TypeError: parentVal.concat is not a function"

demo link

Repeatable demo link: https://github.com/Ge-yuan-jun/vue-routing-demo

expectation

change code in router/index.js & main.js, the plugin should still work

When I use this plugin by default config, It works.

But when I change the router config, modify the index.js in router folder like this:

router/index.js

import routes from 'vue-auto-routing'
import { createRouterLayout } from 'vue-router-layout'

const RouterLayout = createRouterLayout(layout => {
  return import('@/layouts/' + layout + '.vue')
})

const generateRoutes = [
  {
    path: '/',
    component: RouterLayout,
    children: routes
  }
]

export default generateRoutes

and add cde like this in main.js

import Vue from 'vue'
import Router from 'vue-router'
import App from './App.vue'
import routes from './router'

Vue.use(Router)

Vue.config.productionTip = false

const router = new Router({
  routes
})

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

result

when I load the page, it shows the error 'Error in render: "TypeError: parentVal.concat is not a function"'

image

what I want

I want to know if the plugin can work if I change export varaible like the demo

Layout doesn't work when using router.push()

I have made a custom layout called HelloLayout.vue and a HelloWorld.vue page using it and works fine.
But, when I try to redirect to it from another page using this.$router.push('helloworld'), it gives error in the console as follow:

[Vue warn]: Failed to resolve async component:
function () { return resolve(name); }
Reason: Error: Cannot find module './default/default.vue'

Looks like it still try to use the default layout.

You may need an additional loader to handle the result of these loaders.

Module parse failed: Unexpected token (3:16)
File was processed with these loaders:
 * ./node_modules/vuetify-loader/lib/loader.js
 * ./node_modules/cache-loader/dist/cjs.js
 * ./node_modules/vue-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| 
| {
>   "requiresAuth": true
| }

cloud support vue3?

when i run npm run serve, it shows:

> vue-cli-service serve

internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'vue-template-compiler'

and i found the sre/router.ts has some error.

import Vue from 'vue'
import Router from 'vue-router'
import routes from 'vue-auto-routing'
import { createRouterLayout } from 'vue-router-layout'

Vue.use(Router)

const RouterLayout = createRouterLayout(layout => {
  return import('@/layouts/' + layout + '.vue')
})

export default new Router({
  routes: [
    {
      path: '/',
      component: RouterLayout,
      children: routes
    }
  ]
})

maybe change it to

import Vue from 'vue'
import Router, { createWebHistory, createRouter } from 'vue-router'
import routes from 'vue-auto-routing'
import { createRouterLayout } from 'vue-router-layout'

// Vue.use(Router)

const RouterLayout = createRouterLayout(layout => {
  return import('@/layouts/' + layout + '.vue')
})

// export default new Router({
export default createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: RouterLayout,
      children: routes
    }
  ]
})

Support vue-router4?

Does this Support vue-router4 or not ?
I didn't find any information about vue-router version.

Does it work with HttpVueLoader?

Is it possible to use this plugin with HttpVueLoader ?

I want to make a vue project that has auto routing feature and doesn't require me to compile/build using webpack everytime I add a new .vuepage.

I'm imagining that it would be cool if I could just put in a new .vue page into the server directory and it instantly works when I access the filename url.

Does it support Vue CLI v4(vue3)?

I saw

Ensure you are in a project generated by Vue CLI v3.

in the readme page.
Does this mean this plugin do not support CLI v4 (with vue3)?

Layout is not applied, if provided via Mixin

I would like to calculate the used layout dynamically for some pages. Therefore I try to provide the layout via mixin, but the default layout is always applied:

./pages/index.vue:

<template>
  <div class="home">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/debug/HelloWorld.vue'
import LayoutMix from '@/mixins/layout'

export default {
  name: 'home',
  mixins: [ LayoutMix ],
  components: { HelloWorld }
}
</script>

./mixins/layout.js

const layoutMixin = {
    layout: 'app'
}

export default layoutMixin;

Probably, at the time the layoutName is fetched, Mixins are not yet applied to the Component (please see:
https://github.com/ktsn/vue-router-layout/blob/1d1ba839755b95af3dd63c3939fa3560ea60a7dd/src/index.ts#L27) ?

Allow to use without RouterLayout

The following code:

import Vue from "vue"
import routes from "vue-auto-routing"
import VueRouter from "vue-router"

Vue.use(VueRouter)

const router = new VueRouter({
	mode: "history",
	base: process.env.BASE_URL,
	routes,
})

export default router

emits this warning:

[vue-router] Non-nested routes must include a leading slash character. Fix the following routes: 

Is there an elegant way to have vue-auto-routing emit non-nested routes, e.g. with a certain webpack loader option? Note that I'm deliberately avoiding the layouts plugin (which surfaced this unwanted coupling between the modules).

For now, I'm using this:

const router = new VueRouter({
	mode: "history",
	base: process.env.BASE_URL,
	routes: routes.map(route => ({ ...route, path: "/" + route.path })),
})

<route-meta> loader

Hi,

i really love your plugin for vue cli. There's one thing i've noticed when using <route-meta> custom block.

When using this custom block, it logically does not have loader registered for it so it throws error such as:

Module parse failed: Unexpected token
You may need an appropriate loader to handle this file type.

I came up with a dirty workaround, basically passing the <route-meta> to a custom loader that does not do anything, like this:

# vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('routeMeta')
      .resourceQuery(/blockType=route-meta/)
      .type('javascript/auto')
      .use('routeMeta')
      .loader('routemeta.js');
  }
}

Did i miss something in the installation? Is there a cleaner way to handle this?

How to use?

I installed according to the Overview section, but I'm not sure how to actually get it to activate. I do see the sample pages, but it doesn't appear to do anything?
The default App.vue page is still there being served, and it's not clear how to replace it with whatever is generated (or if it's generated?).

Auto add global components

Can this plugin(s) be used to automate adding global components? i.e. it reads components folder or some custom path and automatically adds them via app.component("Icon", Icon); based on filename. If not, would it be within the scope of this project to support something like that?

Nothing but index page works with current versions

I just set up a project from scratch, and all that seems to work is the index page. The about page just shows the root index page as well. I ran the sample code from issue #1 just fine, but when I updated to the following versions it, too, broke.

dependencies

"vue": "^2.5.21", "vue-router": "^3.0.1", "vue-router-layout": "^0.1.2"

devDependencies

"vue-auto-routing": "^0.3.0", "vue-cli-plugin-auto-routing": "^0.2.1", "vue-template-compiler": "^2.5.21"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.