项目简介
本项目基于 Rollup 构建工具,对 Vue 组件进行高效打包。它支持多种模块格式输出,集成了 Vue 单文件组件处理和 PostCSS 样式处理,能有效提升前端组件开发和打包效率。
项目的主要特性和功能
- 支持 Vue 单文件组件,借助
rollup-plugin-vue
插件实现打包处理。 - 代码压缩优化,通过
terser
插件在生产环境对代码进行压缩,提高运行效率。 - 样式处理,使用
postcss
插件处理样式文件,支持多种 CSS 预处理器和样式管理。 - 模块解析引入,利用
@rollup/plugin-node-resolve
插件,支持直接引入和解析 Node 模块。 - 可灵活配置,能为每个组件单独配置打包,方便管理和维护。
安装使用步骤
假设用户已下载本项目的源码文件。
1. 安装依赖
在项目根目录下,执行以下命令:
bash
yarn install
yarn add jest @vue/test-utils vue-jest babel-jest -D -W
yarn add babel-core@bridge -D -W
yarn add rollup rollup-plugin-terser rollup-plugin-vue@5.1.9 vue-template-compiler -D -W
yarn add @rollup/plugin-json rollup-plugin-postcss @rollup/plugin-node-resolve -D -W
2. 配置文件
- Jest 配置:创建
jest.config.js
文件,内容如下:js module.exports = { "testMatch": ["**/__tests__/**/*.[jt]s?(x)"], "moduleFileExtensions": [ "js", "json", "vue" ], "transform": { ".*\\.(vue)$": "vue-jest", ".*\\.(js)$": "babel-jest" } }
- Babel 配置:创建
babel.config.js
文件,内容如下:js module.exports = { presets: [ [ '@babel/preset-env' ] ] }
- Rollup 配置:
- 在
button
目录中创建rollup.config.js
文件: ```js import { terser } from 'rollup-plugin-terser' import vue from 'rollup-plugin-vue'
- 在
module.exports = [
{
input: 'index.js',
output: [
{
file: 'dist/index.js',
format: 'es'
}
],
plugins: [
vue({
css: true,
compileTemplate: true
}),
terser()
]
}
]
- 在项目根目录创建 `rollup.config.js` 文件:
js
import fs from 'fs'
import path from 'path'
import json from '@rollup/plugin-json'
import vue from 'rollup-plugin-vue'
import postcss from 'rollup-plugin-postcss'
import { terser } from 'rollup-plugin-terser'
import { nodeResolve } from '@rollup/plugin-node-resolve'
const isDev = process.env.NODE_ENV!== 'production'
const plugins = [ vue({ css: true, compileTemplate: true }), json(), nodeResolve(), postcss({ extract: true }) ]
isDev || plugins.push(terser())
const root = path.resolve(__dirname, 'packages')
module.exports = fs.readdirSync(root) .filter(item => fs.statSync(path.resolve(root, item)).isDirectory()) .map(item => { const pkg = require(path.resolve(root, item, 'package.json')) return { input: path.resolve(root, item, 'index.js'), output: [ { exports: 'auto', file: path.resolve(root, item, pkg.main), format: 'cjs' }, { exports: 'auto', file: path.join(root, item, pkg.module), format: 'es' }, ], plugins: plugins } }) ```
3. 配置 package.json
- 在
button
包的package.json
中添加build
脚本:js "build": "rollup -c"
- 在每个包的
package.json
中设置main
和module
字段:js "main": "dist/cjs/index.js", "module": "dist/es/index.js"
- 在根目录的
package.json
中配置build
脚本:js "build": "rollup -c"
4. 运行打包
打包 button
组件:
bash
yarn workspace lg-button run build
打包所有组件:
bash
yarn build
下载地址
点击下载 【提取码: 4003】【解压密码: www.makuang.net】