rollup打包vue组件库

493 阅读2分钟
创建vue项目
vue create rollup-vue
全局安装rollup(node版本15及以上)
npm i rollup -g
根目录创建rollup.config.js文件,并安装相关依赖(打包vue2/vue3 rollup-plugin-vue版本不一致
  "rollup-plugin-vue": "^5.1.9",
  "rollup-plugin-css-only": "^4.3.0",
  "rollup-plugin-terser": "^7.0.2",
rollup.config.js文件配置
 
// rollup-plugin-vue用于处理.vue文件。打包vue2和vue3项目所用的rollup-plugin-vue版本不一样,vue的编译器也不一样。
const vue = require('rollup-plugin-vue')
// 分离css
const css = require('rollup-plugin-css-only');
// 压缩
const { terser } = require ('rollup-plugin-terser');

module.exports = {
  input: "./src/components/index.js",
  output: [
    // {
    //   file: 'dist/bundle.iife.js',
    //   format: 'iife',
    //   name: 'MyLibrary', // 对于 iife 格式,给输出的立即调用函数命名(可选)
    // },
    {
      file: './dist/my-lib-es.js',
      format: 'es'//
      sourcemap: true,
    },
  ],
  plugins: [
    vue({
      css: false // This prevents Rollup from including CSS inside the JS bundle
    }),
    css({
      output: 'index.css', // Specify the path for the output CSS file
    }),
    terser(), //压缩js
  ],
  external: [  //外部库, 使用'umd'文件时需要先引入这个外部库
    'vue'
  ]
}
package.json中添加打包指令
  "lib": "rollup -c"
编写组件 src/components/MyBtnComponent.vue
<template>
  <div class="MyBtnComponent">
    <p>count:{{ count }}</p>
    <button @click="onAdd">counter</button>
  </div>
</template>

<script>
export default {
  name: "MyBtnComponent",
  components: {},
  props: {
    initVal: Number,
  },
  data() {
    return {
      count: this.initVal ?? 0,
    };
  },
  created() {},
  watch: {},
  computed: {},
  mounted() {},
  methods: {
    onAdd() {
      console.log("onAdd");
      this.count++;
    },
  },
};
</script>

<style>
button {
  background-color: yellow;
}
</style>
<style lang="scss" scoped>
.MyBtnComponent {
  button {
    background-color: pink;
  }
}
</style>
编写index.js 暴露组件
import MyBtnComponent from "./MyBtnComponent.vue";
const components = [MyBtnComponent];
const install = function (Vue, opts = {}) {
  console.log('opts', opts);
  components.forEach((component) => {
    Vue.component(component.name, component);
  });
};
if (typeof window !== "undefined" && window.Vue) {
  install(window.Vue);
}
export default {
  install
};
export { MyBtnComponent }

执行打包命令 npm run lib
测试打包结果
  • src/main.js
import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

import { MyBtnComponent } from '../dist/my-lib-es'
import '../dist/index.css'
Vue.component(MyBtnComponent.name, MyBtnComponent)
new Vue({
  render: h => h(App),
}).$mount('#app')

  • src/App.vue
<template>
  <div id="app">
    <MyBtnComponent :initVal="9"/>
  </div>
</template>

<script>

export default {
  name: 'App',
  components: {
  }
}
</script>

<style>

</style>

rollup常用的插件(待实验

rollup-plugin-postcss 它支持css文件的加载、css自动加前缀、css压缩、对scss/less的支持等

@rollup/plugin-node-resolve 帮助 Rollup 查找外部模块,然后导入,同时配置external 属性

  • 举例
// 假设你正在开发一个 JavaScript 库,它依赖于 lodash 这个第三方库,
// 在没有 `@rollup/plugin-node-resolve` 插件的情况下,当你运行 Rollup 来打包你的库时,它会报错说找不到 `lodash` 模块,因为默认情况下 Rollup 不知道如何去解析来自 `node_modules` 的模块。
import _ from 'lodash'; 

@rollup-plugin-commonjs 用于将 CommonJS 模块转换为 ES6 模块 @rollup/plugin-babel 使用Babel将ES6+代码转换为ES5,以确保在更旧的浏览器中兼容性

rollup-plugin-url 处理各种图片资源

import postcss from 'rollup-plugin-postcss'; 
import { nodeResolve } from "@rollup/plugin-node-resolve";
import commonjs from '@rollup/plugin-commonjs';
import babel from '@rollup/plugin-babel'; 
import url from "rollup-plugin-url"

export default { 
  input: 'src/main.js', 
  output: { file: 'dist/bundle.js', format: 'es', }, 
  plugins: [ 
  postcss({ 
  // 在这里进行 PostCSS 配置 // 可以添加需要的 PostCSS 插件和配置 
    }), 
    nodeResolve(),
    commonjs(),
    babel({ babelHelpers: 'bundled' }),
    url({ 
        // Specify options for handling images 
        include: ['**/*.png', '**/*.jpg', '**/*.gif'], // Match image file extensions 
        limit: 10 * 1024, // If the image is smaller than 10KB, convert to Data URL 
        emitFiles: true, // Copy images to the output directory 
    }),
   ], 
   external: ['lodash'],
  };