You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3项目启动报错:无法从非ECMAScript模块导入命名导出

Vue3项目启动ES模块错误的解决思路

问题描述

使用vue-cli创建的Vue3应用启动时出现错误:无法从非ECMAScript模块导入命名导出(仅默认导出可用)。尝试过相关方案后无效,项目配置如下:

package.json

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "lint-no-mercy": "vue-cli-service lint --max-warnings 0"
  },
  "dependencies": {
    "@popperjs/core": "^2.9.2",
    "@vueform/multiselect": "^1.5.0",
    "axios": "^0.21.1",
    "bootstrap": "^5.0.1",
    "bootstrap-icons": "^1.5.0",
    "core-js": "^3.6.5",
    "dayjs": "^1.10.6",
    "jwt-decode": "^3.1.2",
    "v-calendar": "^3.0.0-alpha.5",
    "vue": "^3.0.0",
    "vue-axios": "^3.2.4",
    "vue-router": "^4.0.8",
    "vuex": "^4.0.1",
    "vuex-persistedstate": "^4.0.0-beta.3"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-airbnb": "^5.0.2",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-vue": "^7.0.0"
  }
}

vue.config.js

module.exports = {
  publicPath: process.env.VUE_PUBLIC_PATH,
  chainWebpack: (config) => {
    config.module
      .rule('pdf')
      .test(/\.pdf$/)
      .use('file-loader')
      .loader('file-loader');
  },
};

解决思路

  • 定位问题依赖并调整导入方式:查看错误栈明确指向的依赖,从当前依赖列表看,jwt-decode@3.1.2这类旧版本为CommonJS导出,若使用命名导入会触发错误,改为默认导入:

    // 替换原命名导入
    import jwtDecode from 'jwt-decode'
    
  • 修改webpack配置适配CommonJS模块:在vue.config.js中添加规则,让babel处理指定依赖的模块格式:

    module.exports = {
      publicPath: process.env.VUE_PUBLIC_PATH,
      chainWebpack: (config) => {
        config.module
          .rule('pdf')
          .test(/\.pdf$/)
          .use('file-loader')
          .loader('file-loader');
        // 添加模块转译规则
        config.module
          .rule('js')
          .include.add(/node_modules\/(jwt-decode|v-calendar)/)
          .end()
          .use('babel-loader')
          .loader('babel-loader')
          .options({
            presets: ['@vue/cli-plugin-babel/preset']
          });
      },
      configureWebpack: {
        resolve: {
          mainFields: ['browser', 'module', 'main']
        }
      }
    };
    
  • 升级或替换不稳定依赖:

    • 将jwt-decode升级至4.x稳定版,新版本原生支持ES模块;
    • 替换v-calendar的alpha版本为v2.x稳定版,预发布版本易存在模块导出不规范问题。
  • 升级vue-cli版本:当前使用的@vue/cli-service为4.5.x,Vue3推荐搭配vue-cli 5.x使用,升级可修复底层webpack模块处理兼容性问题:

    npm update @vue/cli-service --save-dev
    
  • 统一导入语法规范:确保所有依赖的导入方式与模块导出格式匹配,CommonJS模块仅使用默认导入,ES模块可按需使用命名导入。

内容的提问来源于stack exchange,提问作者Raf1k

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:27:18