rollup打包简单的ts库问题记录

690 阅读1分钟

一、背景:

第一次完整地用 rollup 给我的 npm 包 separated-directives 打包,遇到了很多问题,这里记录一下大概步骤和问题解决办法

二、记录

1. 依赖

pnpm i rollup rollup-plugin-typescript2 rollup-plugin-terser rollup-plugin-dts -D

rollup:最好下载在项目中,用 pnpm rollup 启动,不然会依赖全局包
rollup-plugin-typescript2:处理 ts 文件
rollup-plugin-terser:压缩输出内容
rollup-plugin-dts:输出 .d.ts 文件

2. 使用 rollup.config.ts

  • pnpm i @rollup/plugin-typescript -D,只需要下载不用导入
    pnpm rollup -c --configPlugin typescript 运行

    对应 rollup 报错:
    [!] Error: Cannot find entry for plugin "typescript". The plugin needs to export a function either as "default" or "typescript" for Rollup to recognize it.

  • 如果 tsconfig 使用 references,比如在 vite 默认的 vue3 项目中,会导致 rollup 读不到 tsconfig,从而无法解析 rollup.config.ts

    对应 rollup 报错(无法识别 ts 语法):
    [!] RollupError: rollup.config.ts (8:6): 'const' declarations must be initialized (Note that you need plugins to import files that are not JavaScript

3. tsconfig 的 references

tsconfig 通过多个 reference 对不同的文件使用不同的配置

// 在 tsconfig.json 中

{
  "files": [],
  "references": [
    { "path": "./tsconfig.node.json" },
    { "path": "./tsconfig.test.json" },
    { "path": "./tsconfig.src.json" }
  ]
}

因为 references,插件调用都要手动指定 tsconfig

// 在 rollup.config.js 中

import typescript from 'rollup-plugin-typescript2'
import { terser } from 'rollup-plugin-terser'
import dts from 'rollup-plugin-dts'

/** @type {import('rollup').RollupOptions[]} */
export default [
  {
    input: 'src/main.ts',
    output: {
      file: 'lib/index.js',
      format: 'esm',
      plugins: [terser()]
    },
    plugins: [typescript({ tsconfig: 'tsconfig.rollup.json' })]
  },
  {
    input: 'src/main.ts',
    output: {
      file: 'lib/index.d.ts',
      format: 'esm'
    },
    plugins: [
      typescript({ tsconfig: 'tsconfig.rollup.json' }),
      dts({ tsconfig: 'tsconfig.rollup.json' })
    ]
  }
]

4. 手动下载依赖包

// 在 main.ts 中
import { type ObjectDirective } from 'vue'

// 在 vue.d.ts 中
export * from '@vue/runtime-dom';

这里的 '@vue/runtime-dom' 属于 vue 的依赖包,被 pnpm 放置在 node_modules/.pnpm 目录中,需要 pnpm i @vue/runtime-dom @vue/runtime-core -D