系列
如何用 Rollup 打包 JavaScript / TypeScript (上一章)
如何用 Rollup 打包 Vue2.x UI 组件 (本章节)
如何用 Rollup 打包 Vue3.x UI 组件 (下一章)
如何用 Rollup 打包 React UI 组件 (已完成)
前言
本章节主要以 IconSelect 组件作为实战范例,分享 Rollup
打包 Vue2.x Component
所需的依赖、配置及脚本。
简介
本章节使用 Ant-Design-Vue@1.7.8
的 Icon
和 Select
组件封装成 IconSelect
新组件作为实战范例进行讲解。另本章节尾附有相关链接~
Rollup 打包 Vue2.x 所需依赖 (详见 package.json)
-
@rollup/plugin-alias
- 用途: rollup 路径别名配置
-
@rollup/plugin-babel
-
用途: rollup babel plugin
-
配置: babel.config.js
module.exports = { presets: [ '@vue/babel-preset-jsx' ] }
-
依赖:
@babel/core
babel 核心@vue/babel-preset-jsx
babel 处理 Vue2.x jsx 语法@vue/babel-helper-vue-jsx-merge-props
babel 处理 Vue jsx props
-
-
@rollup/plugin-node-resolve
- 用途: 用于解析 node_modules 中第三方模块
-
rollup-plugin-vue
- 用途: 解析 Vue SFC (Single File Component)
- 版本: Vue2.x时, version = ^5.1.9
- 依赖:
vue
version = ^2.7.14less
version = ^3.0.4less-loader
version = ^5.0.0vue-template-compiler
version = ^2.7.14
-
rollup-plugin-postcss
- 用途: 用于处理 css 样式, 包括 Vue 单文件中
<style>
样式
- 用途: 用于处理 css 样式, 包括 Vue 单文件中
Rollup 打包 Vue2.x 组件 插件选项
-
创建 rollup.config.js 文件
const { defineConfig } = require('rollup') const { nodeResolve } = require('@rollup/plugin-node-resolve') const postcss = require('rollup-plugin-postcss') const babel = require('@rollup/plugin-babel') const alias = require('@rollup/plugin-alias') const vue = require('rollup-plugin-vue') const path = require('path') /** * Rollup Configuration, 建议使用 defineConfig 以支持TS识别 */ module.exports = defineConfig([ { input: 'src/index.vue', output: [ { // import 'xxx' dir: 'dist', format: 'es', entryFileNames: chunk => `[name].mjs` }, { // require('xxx') dir: 'dist', format: 'cjs', exports: 'named', entryFileNames: chunk => `[name].cjs` } ], plugins: [ nodeResolve(), alias({ entries: [{ find: '@', replacement: path.resolve(__dirname, './src') }] }), vue(), postcss(), babel({ // 指定 babel 处理文件类型 babelHelpers: 'bundled', // 如果 vue 存在 jsx 语法, extensions: ['.js', '.vue'] // 则会从 babel.config.js, 调用 @vue/babel-preset-jsx 处理 }) ], // 排除不需要混入代码中的第三方依赖 external: [ /^vue(\/.+|$)/, // 也可以字符串 'vue' /^ant-design-vue(\/.+|$)/ // 也可以字符串 'ant-design-vue' ] } ])
Rollup 打包 Vue2.x 组件 Script 脚本配置
-
在 package.json 里配置
{ "scripts": { "build": "shx rm -rf dist && rollup -c" } }
如何下载使用 IconSelect 组件?
-
发布
{ "name": "@rollup-build-components/icon-select-vue2.x", "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" } }
pnpm publish
-
安装
yarn add @rollup-build-components/icon-select-vue2.x pnpm add @rollup-build-components/icon-select-vue2.x
-
使用
<template> <section class="section-container"> <icon-select v-model="value"/> </section> </template>
import IconSelect from '@rollup-build-components/icon-select-vue2.x' export default { name: 'Index', components: { IconSelect }, data () { return { value: 'down' } } }