13-配置rollup

178 阅读1分钟

why

我们需要把代码打包成库,供外部使用

  • rollup 一般是用来打包代码库
  • webpack 一般是用来打包应用

安装rollup及插件

// 安装rollup
yarn add rollup --dev

// 安装typescript plugin,支持ts转义
yarn @rollup/plugin-typescript --dev

// 安装tslib,支持ts
yarn add tslib --dev

配置rollup

rollup.config.js

/*
 * @Author: Lin zefan
 * @Date: 2022-03-22 15:34:06
 * @LastEditTime: 2022-03-22 16:17:29
 * @LastEditors: Lin zefan
 * @Description:
 * @FilePath: \mini-vue3\rollup.config.js
 *
 */
import typescript from "@rollup/plugin-typescript";
import pkg from "./package.json";

export default {
  // 入口文件
  input: "./src/index.ts",
  // 出口文件,可以配多个
  output: [
    // cjs - common.js
    {
      // 输出的模块类型
      format: "cjs",
      // 输出的文件名
      file: pkg.cjs,
    },
    // esm - ES-Module
    {
      format: "esm",
      file: pkg.esm,
    },
  ],
  plugins: [
    // 解析ts
    typescript(),
  ],
};

package.json

{
  "name": "mini-vue3",
  "version": "1.0.0",
+  "cjs": "./lib/mini-vue.cjs.js",
+  "esm": "./lib/mini-vue.esm.js",
  "scripts": {
    "test": "jest",
+    "build": "rollup -c rollup.config.js"
  },
  "repository": "git@github.com:linzefan0612/mini-vue3-model.git",
  "author": "linzefan0612",
  "license": "MIT",
  "devDependencies": {
    "@babel/core": "^7.17.5",
    "@babel/preset-env": "^7.16.11",
    "@babel/preset-typescript": "^7.16.7",
    "@rollup/plugin-typescript": "^8.3.1",
    "@types/jest": "^27.4.1",
    "babel-jest": "^27.5.1",
    "jest": "^27.5.1",
    "rollup": "^2.70.1",
    "tslib": "^2.3.1",
    "typescript": "^4.6.2"
  },
  "dependencies": {}
}

配置rollup入口文件

index.js

/*
 * @Author: Lin zefan
 * @Date: 2022-03-22 15:40:00
 * @LastEditTime: 2022-03-22 16:22:54
 * @LastEditors: Lin zefan
 * @Description: 打包入口文件
 * @FilePath: \mini-vue3\src\index.ts
 *
 */
 
// 暴露runtime-core模块
export * from "./runtime-core/index";

runtime-core/index.js

/*
 * @Author: Lin zefan
 * @Date: 2022-03-22 16:22:33
 * @LastEditTime: 2022-03-22 16:22:33
 * @LastEditors: Lin zefan
 * @Description: 
 * @FilePath: \mini-vue3\src\runtime-core\index.ts
 * 
 */

export * from "./createdApp";
export { h } from "./h";

执行打包

yarn build

image.png