【问题标题】:webpack, vue, nuxt - import component if file existwebpack, vue, nuxt - 如果文件存在则导入组件
【发布时间】:2021-05-28 18:24:05
【问题描述】:

我只想在文件存在的情况下加载组件。 有没有办法实现它? 我试过了:

components: {
 MyComponent: () => import(
                    /* webpackMode: "lazy" */
                    /* webpackIgnore: true */
                    'themes/MyComponent'
                   ).catch(() => import('default/MyComponent'))
}

但尽管存在“主题/MyComponent”,但“默认/MyComponent”已加载。

如果我设置 /* webpackIgnore: false */ 并删除 "themes/MyComponent" 然后得到

“未找到模块:错误:无法解析“主题/MyComponent”

【问题讨论】:

    标签: vue.js webpack nuxt.js


    【解决方案1】:

    不确定用例,但这是您正在寻找的解决方案吗? https://forum.vuejs.org/t/how-to-check-if-path-of-file-exist/59345/3?u=kissu

    try {
      this.storyToRead = require('../assets/data/stories/' + this.storyFileName)
      // do something
    } catch (e) {
      // do something else
    }
    

    【讨论】:

    • 无论我使用 import.catch 还是 try/catch 和 import 或 require。我总是出错。所以“Try/catch”是行不通的。
    • 是它的用例吗?另外,检查这个:stackoverflow.com/questions/37389788/…
    • 我在我的应用主题中使用。如果我的主题中不存在某些组件,我想加载“默认”模板。现在 webpack 抛出错误: if(1===2) { import(''PATH_TO_NON_EXISTING MODULE') }
    【解决方案2】:

    我遇到了同样的问题,我想出了一个解决方案:) 基本上我使用 webpack 创建了文件列表,然后检查文件路径是否包含在该列表中。

    <template>
      <div>
        <Component :is="MyComponent" />
      </div>
    </template>
    
    <script>
    export default {
      computed: {
        filesList() {
          const filesList = require
            .context('../components/', true, /.*\.vue$/)
            .keys()
          const itemsList = filesList.map((item) =>
            item.replace('.vue', '').slice(2)
          )
          return itemsList
        },
        path() {
          const filePath = 'MyComponent'
          return this.fileExists(filePath) ? filePath : 'Default'
        },
        MyComponent() {
          return () => import(`~/components/${this.path}`)
        },
      },
      methods: {
        fileExists(path) {
          return this.filesList.includes(path)
        },
      },
    }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2019-12-30
      • 2017-06-04
      • 2016-05-26
      • 2019-08-15
      • 1970-01-01
      • 2020-07-12
      • 2019-05-20
      • 2019-09-25
      • 2020-06-10
      相关资源
      最近更新 更多