[Vuejs]-Shorter way of importing components in vue-router

1πŸ‘

I ended up using this:

let importComponent = require.context('@/pages/', true, /\.vue$/)
let imports = {}

function importAll (file_paths) {
    file_paths.keys().forEach(file_path => {
        const file_name = file_path.split('/')[1]
        const path = file_path.split('.')[0]
        imports[file_name] = importComponent(file_path).default
  });
}

importAll(require.context('@/pages/', true, /\.vue$/));

So for the below structure:

-pages
 --HomePage
    -- HomePage.vue
--AboutPage
    -- AboutPage.vue

The full example is:

import Vue from 'vue'
import VueRouter from 'vue-router'
import HomePage from './pages/HomePage/HomePage.vue'

Vue.use(VueRouter)

let importComponent = require.context('@/pages/', true, /\.vue$/)
let imports = {}

function importAll (file_paths) {
    file_paths.keys().forEach(file_path => {
        const file_name = file_path.split('/')[1]
        const path = file_path.split('.')[0]
        imports[file_name] = importComponent(file_path).default
  });
}

importAll(require.context('@/pages/', true, /\.vue$/));

export const router = new VueRouter({
    routes: [
        {
            path: '/home',
            component: imports.HomePage
        },
        {
            path: '/about',
            component: imports.AboutPage
        }
    ],
    mode: 'history'
}) 

Note: You can edit this to your needs or make it a service. Please make sure to take a look at webpack require-context

-1πŸ‘

There is no shorter syntax to import components into another component.

For components that you want to use a lot, however, you can import them once globally in your entry file if you’re using Webpack (or Vue CLI 3+, which uses Webpack internally).

Example from the Vue Docs

import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  // The relative path of the components folder
  './components',
  // Whether or not to look in subfolders
  false,
  // The regular expression used to match base component filenames
  /Base[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // Get component config
  const componentConfig = requireComponent(fileName)

  // Get PascalCase name of component
  const componentName = upperFirst(
    camelCase(
      // Strip the leading `./` and extension from the filename
      fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
    )
  )

  // Register component globally
  Vue.component(
    componentName,
    // Look for the component options on `.default`, which will
    // exist if the component was exported with `export default`,
    // otherwise fall back to module's root.
    componentConfig.default || componentConfig
  )
})

This might in some cases not be desirable behaviour. I recommend reading the article.

Short note: You can usually leave the .vue extension off of your import. Easier reading at least.

Leave a comment