iview 和 element-ui 的按需引入

如果全部引入,这两个库基本上就是1M多,压缩后也有90多k,但一般只需要其中几个组件,所以可以按需引入,极大的减少文件体积

先安装相关插件,然后配置babelrc文件即可

只使用两个组件

由于iview只引入了一个组件,element还引入了其他组件,所以大小有一点区别,总体来看还是减少了一部分体积的

iview按需引用

https://www.iviewui.com/docs/guide/start

借助插件 babel-plugin-import可以实现按需加载组件,减少文件体积。首先安装,并在文件 .babelrc 中配置:

npm install babel-plugin-import --save-dev

// .babelrc
{
  "plugins": [["import", {
    "libraryName": "iview",
    "libraryDirectory": "src/components"
  }]]
}

然后这样按需引入组件,就可以减小体积了:iview目前不能使用use来注册组件

import { Button, Table } from 'iview';
Vue.component('Button', Button);
Vue.component('Table', Table);

element按需引入

http://element-cn.eleme.io/#/zh-CN/component/quickstart

借助 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)
});

babelrc文件

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            "> 1%",
            "last 2 versions",
            "not ie <= 8"
          ]
        }
      }
    ],
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    "transform-runtime",
    [
      "import",
      {
        "libraryName": "iview",
        "libraryDirectory": "src/components"
      }
    ],
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

猜你喜欢

转载自my.oschina.net/ahaoboy/blog/1787653