基于rollup的组件库打包体积优化小结(2)

rollup的external配置是支持函数类型的,大概看tranform-runtime这个插件源码可以找到addImport这些方法,可以知道polyfill是通过import来引入的,可以被external,所以只需要在rollup配置的external添加上类似函数就可以达到我们想要的效果

{ external (id) { // 对babel-runtime进行external return /^babel-runtime/.test(id) // 当然别忘了还有很多 比如vue等等,这里就不写了 } }

这里就可以解决问题2和问题3

另外问题5,这个是如何来的呢,比如在写jsx时,可能会这样写

// xx组件 export default { render () { return ( <div> <ToolTip {...{props: tooltipProps}} /> {/* other */} </div> ) } }

在某个组件中依赖了另一个组件,考虑到扩展性,是支持对另一个组件进行props设置的,所以经常会这样写,在template中的话就类似于v-bind="tolltipProps"

这个时候transform-vue-jsx插件是会引入一个helper函数的,也就是babel-helper-vue-jsx-merge-props,大概看看transform-vue-jsx源码也可以得知,这个helper也是import进来的,所以可以把external改成

{ external (id) { return /^babel/.test(id) } }

这样就可以做到对所有helper都使用import的形式来引入,而且使用rollup打包后的代码更可读,大概长这样

// Alert组件 import _defineProperty from 'babel-runtime/helpers/defineProperty'; import Icon from 'gs-ui/lib/icon.js'; var Alert = { render: function render() { var _class; var _vm = this;var _h = _vm.$createElement;var _c = _vm._self._c || _h;return _c('transition', { attrs: { "name": "gs-zoom-in-top" } }, [_vm.show ? _c('div', { class: (_class = { 'gs-alert': true }, _defineProperty(_class, 'gs-alert-' + _vm.type, !!_vm.type), _defineProperty(_class, 'has-desc', _vm.desc || _vm.$slots.desc), _class) }, [_vm.showIcon ? _c('div', { staticClass: "gs-alert-icon", class: { "gs-alert-icon-top": !!_vm.desc } }, [_vm._t("icon", [_c('gs-icon', { attrs: { "name": _vm.icon } })])], 2) : _vm._e(), _vm._v(" "), _c('div', { staticClass: "gs-alert-content" }, [_vm.title || _vm.$slots.default ? _c('div', { staticClass: "gs-alert-title" }, [_vm._t("default", [_vm._v(_vm._s(_vm.title))])], 2) : _vm._e(), _vm._v(" "), _vm.desc || _vm.$slots.desc ? _c('div', { staticClass: "gs-alert-desc" }, [_vm._t("desc", [_vm._v(_vm._s(_vm.desc))])], 2) : _vm._e(), _vm._v(" "), _vm.closable ? _c('div', { staticClass: "gs-alert-close", on: { "click": _vm.close } }, [_vm._t("close", [_vm._v(" " + _vm._s(_vm.closeText) + " "), !_vm.closeText ? _c('gs-icon', { attrs: { "name": "close" } }) : _vm._e()])], 2) : _vm._e()])]) : _vm._e()]); }, staticRenderFns: [], name: 'GsAlert', components: _defineProperty({}, Icon.name, Icon), // props // data // methods }; /* istanbul ignore next */ Alert.install = function (Vue) { Vue.component(Alert.name, Alert); }; export default Alert;

vue插件把vue组件中的template转成render函数,babel插件做语法转换,因为external的存在,保留了模块关系,整个代码看起来很清晰,很舒服,不像webpack,都会添加一个模块加载函数...

优化后和优化前的体积对比

下面的截图是生产环境的版本,也就是没有了代码提示,也已经压缩混淆后的代码体积对比
左边是优化前,右边是优化后

基于rollup的组件库打包体积优化小结

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/6dd366716509d1828f88c787f03f753b.html