如何在不显式导入的情况下将目录中的所有 "vue" 文件包含到构建中

How to include all "vue" files from directory into the build without explicitly importing them

有没有办法在我的 views/ 文件夹中构建所有 .vue 文件,而无需将它们直接导入到我的 vue 应用程序中? 我想要实现的是一个具有动态路由定义的路由器,它将从配置中填充,该配置是一个 json 填充的名称,路由器路径和应该延迟加载的组件名称。 我现在的问题是:该应用程序只构建在我的应用程序某处导入的文件。我需要的是:在 views/ 中构建 all 文件作为块,以便能够拥有动态路由器定义。

感谢您的帮助:)

没有提供任何代码很难给出正确的解决方案,但我会尝试

使用这样的代码:

// route definition loaded from json
const routeDef = [
  { name: 'about', path: '/about', componentName: 'about' },
  { name: 'profile', path: '/profile', componentName: 'profile' }
]

// we can create routes like this
const routes = routeDef.map(function(def) {
  return {
    name: def.name,
    path: def.path,
    component: () => import('@/views/' + def.componentName + '.vue')
  }
})

const router = new VueRouter({
  routes: routes
})

通过使用 import('@/views/' + def.componentName + '.vue') 你告诉 Webpack 我想导入 views 目录中的 .vue 文件之一,但运行时会知道哪个文件。因此,Webpack 会将所有文件打包到该目录中,并使其在运行时可供导入....

请注意,您传递给 import() 的内容非常重要 - 参数的一部分必须始终是静态字符串,以便 Webpack 至少对目录有一些线索(import(def.componentName) 不会工作) -查看 docs

附加示例 - 在运行时从服务器加载路由定义

router.js

export default createRouter() {
  return axios.get('/getRouteDefinitions').then(function(data) {
    
    const routes = data.routeDef.map(function(def) {
      return {
        name: def.name,
        path: def.path,
        component: () => import('@/views/' + def.componentName + '.vue')
      }
    })

    return new VueRouter({
      routes: routes
    })
  })
}

main.js

import VueRouter from `VueRouter`
import createRouter from `router.js`

Vue.use(VueRouter)

createRouter().then(function(router) {
  const app = new Vue({
    router
  })
  app.$mount("#app")
})