首先我的开发环境是基于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.

Logo

前往低代码交流专区

更多推荐