【问题标题】:Can't use "import * as name from './module', webpack returns error in Vue无法使用“import * as name from './module', webpack 在 Vue 中返回错误
【发布时间】:2021-10-15 21:19:08
【问题描述】:

鉴于以下文件:

mutation-types.js

export const SET_VALUE = 'SET_VALUE'
export const SET_PLACEHOLDER = 'SET_PLACEHOLDER'

my-file.js

import * as types from './mutation-types'

给出一个错误提示 Uncaught TypeError: types__WEBPACK_IMPORTED_MODULE_1_.default is undefined。甚至官方的 vuex repo 也使用了这个语法,和 Vue 3 的版本一样。Here你可以查一下。

为什么不能使用 import * as name from './something' 这样的导入?

【问题讨论】:

    标签: vue.js webpack


    【解决方案1】:

    你可以看到 VueX 是从 ../api (api/index.js) 导入的,它不像你那样写 export const

    如果您仔细阅读该消息,它会显示“.default 未定义”。所以用export default试试吧。

    举个例子来自
    Canonical way to define common constants in Vue.js

    const SET_VALUE = 'SET_VALUE'
    const SET_PLACEHOLDER = 'SET_PLACEHOLDER'
    
    export default {
      SET_VALUE: SET_VALUE,
      SET_PLACEHOLDER: SET_PLACEHOLDER
    }
    

    【讨论】:

    • 我不认为你理解我的意思。这复制了行。在我给出的示例中并非如此。尽管我知道这是一种解决方案,但我不想使用export default 并再次编写相同的行。我想通过 import * as xxx 导入所有定义的变量/函数,就像在那个 repo 中一样,所以我可以使用 xxx.something 而没有 export default 重复。
    • 您链接到的 repo 不会导出常量变量,它使用 const 导出函数。导入的 ../api 确实使用了 const 值,但不导出它们。从../api 导入的脚本不使用常量,只使用导出的函数。它不能按照您想要的方式工作。错误消息绝对不是“.default 未定义”.. 所以它需要一个export default
    • 我现在明白了。所以这是关于const。感谢您的澄清。
    猜你喜欢
    • 2023-02-25
    • 2021-11-08
    • 1970-01-01
    • 2022-12-02
    • 2014-09-08
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多