解決Vue中使用Element UI編譯時babel-preset-es2015報錯問題

首先我的開發環境是基於webpack4.X,配置好開發環境之後,按照Element UI官方文檔配置出現編譯錯誤,詳細步驟如下。
webpack4 + Vue 開發環境配置參考

1、安裝element-ui

npm i element-ui -S

2、通過按需引入方式

藉助 babel-plugin-component,我們可以只引入需要的組件,以達到減小項目體積的目的。

首先,安裝 babel-plugin-component:

npm install babel-plugin-component -D

然後,手動創建 .babelrc 文件(注意前面的‘ . ’前綴),寫入以下配置:

  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

接下來,就是按需引入了,比如 Button 和 Select,那麼需要在 main.js入口文件中定義:

import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
/* 或寫爲
 * Vue.use(Button)
 * Vue.use(Select)
 */

new Vue({
  el: '#app',
  render: h => h(App)
});

最後,在App.vue中使用:

<template>
  <div>
    {{ massage }}
    <el-row>
      <el-button>默認按鈕1</el-button>
      <el-button type="primary">主要按鈕</el-button>
      <el-button type="success">成功按鈕</el-button>
      <el-button type="info">信息按鈕</el-button>
      <el-button type="warning">警告按鈕</el-button>
      <el-button type="danger">危險按鈕</el-button>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      massage: "Hello word!"
    };
  }
};
</script>

3、執行npm start之後,報出以下錯誤

Error: Cannot find module 'babel-preset-es2015' from xxx

一看就知道缺少了babel-preset-es2015,於是安裝:

npm install babel-preset-es2015 -D

安裝完,重新啓動,然後又報錯了,意思是插件/預設文件不允許導出對象:

Error: Plugin/Preset files are not allowed to export objects, only functions. In xxx

百度了下,說是因爲 babel 的版本衝突,參考babel版本兼容報錯處理,反正按照這個我是沒解決問題,只好另求他法。

4、終於找到解決問題的辦法
根據babel官方介紹,推薦使用更新的babel-preset-env插件:

babel-preset-es2015 -> babel-preset-env

We’re super 😸 excited that you’re trying to use ES2015 syntax, but instead of continuing yearly presets, the team recommends using babel-preset-env. By default, it has the same behavior as previous presets to compile ES2015+ to ES5. Please check out the v1.x readme for more info. (For Babel 7, we have moved the preset into the main babel repo.
Babel 7
If you are using Babel version 7 you will need to run npm install @babel/preset-env and have “presets”: ["@babel/preset-env"] in your configuration.

因此,修改.babelrc文件如下,把es2015改成@babel/preset-env(先安裝@babel/preset-env):

  "presets": [["@babel/preset-env", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

最後,npm start,Compiled successfully.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章