Stories

Detail Return Return

解決vue項目導入js報does not provide an export named 'defanlt’錯誤問題 - Stories Detail

問題描述

使用webpack打包的umd格式的js插件導入到vue2項目中無法使用,報錯如下:
SymtaxError: The reguested module '/xxxin js’does not provide an export named 'defanlt’
image.png

vue-cli版本不同現象:

  • vue-cli 4.5.15會報’does not provide an export named 'defanlt’錯誤
  • vue-cli 4.5.12不會報錯,但變量會變成undefined

遇到這個問題後一頓百度+Google搜索,搜索到的答案大部分都説是導入方式的問題,於是按照搜索到的答案改導入方式

一開始的導入方式:import ATest from './test.js
按百度搜索到的導入方式:import * as ATest from './test.js
然後輸出ATest,結果變成了這樣
image.png

解決問題

後面經過各種查詢終於找到了原因,原來vue-cli 3.0及以上版本默認禁止了 commonjs 語法
問題找到了,解決起來也就快了,只需要使用@babel/plugin-transform-modules-commonjs插件即可
解決步驟:

  1. 執行命令安裝babel:npm install --D @babel/plugin-transform-modules-commonjs
  2. 在項目根目錄創建一個 babel.config.js(如沒有的情況下)
  3. 配置 babel.config.js
    然後在babel.config.js文件中配置

    module.exports = {
      plugins: [
     [
       '@babel/plugin-transform-modules-commonjs',
       {
         allowTopLevelThis: true
       }
     ]
      ]
    }

    自此問題完美解決

user avatar golgif Avatar esunr Avatar yuan_life Avatar songxianling1992 Avatar huansheng Avatar yanglinxiao Avatar
Favorites 6 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.