如何用 Rollup 打包 React UI 组件

系列

  1. 如何用 Rollup 打包 Javascript / Typescript (已完成)
  2. 如何用 Rollup 打包 Vue2.x UI 组件 (已完成)
  3. 如何用 Rollup 打包 Vue3.x UI 组件 (上一章)
  4. 如何用 Rollup 打包 React UI 组件 (本章节)

前言

与之前章节一样以 IconSelect 组件作为实战范例,分享 Rollup 打包 React Component 所需的依赖、配置及脚本。

简介

本章节使用 React18.x@ant-design/icons^5.2.5antd^5.8.5 - Select 组件封装成 IconSelect 新组件作为实战范例进行讲解。另本章节尾附有相关链接~

Rollup 打包 React 所需依赖 (详见 package.json)

  • @rollup/plugin-alias

    • 用途: rollup 路径别名配置
  • @rollup/plugin-node-resolve

    • 用途: 用于解析 node_modules 中第三方模块
  • @rollup/plugin-commonjs

    • 用途: 用于将CommonJS模块转换为ES6,以便 Rollup 解析处理
  • @rollup/plugin-babel

    • 用途: rollup babel plugin

    • 配置: babel.config.js

      javascript 复制代码
        module.exports = {
          presets: [
            ['@babel/preset-env', { modules: false }],
            ['@babel/preset-react']
          ],
          plugins: ['@babel/plugin-transform-runtime'],
          ignore: ['node_modules/**']
        }
    • 依赖:

      • @babel/core babel 核心
      • @babel/runtime 底层依赖,提供各种helper
      • @babel/preset-env ES6 语法转换
      • @babel/preset-react react 语法转换
      • @babel/plugin-transform-runtime 自动移除语法转换后内联的辅助函数
  • rollup-plugin-postcss

    • 用途: 用于处理 css 样式, 包括 Vue 单文件中 <style> 样式
  • rollup-plugin-typescript

    • 用途1: 用于处理 .tx 及 .tsx 文件中 ts 语法的解析
    • 用途2: 用于解析 rollup.config.ts 配置文件 (eg. pnpm build)

Rollup 打包 React 组件 插件选项

  • 创建 rollup.config.ts 配置文件

    javascript 复制代码
      import { defineConfig } from 'rollup'
      import { nodeResolve } from '@rollup/plugin-node-resolve'
      import typescript from '@rollup/plugin-typescript'
      import commonjs from '@rollup/plugin-commonjs'
      import postcss from 'rollup-plugin-postcss'
      import alias from '@rollup/plugin-alias'
      import babel from '@rollup/plugin-babel'
    
      /**
       * Rollup Configuration
       */
      export default defineConfig([
        {
          input: 'src/index.tsx',
          output: [
            {
              dir: 'dist',
              format: 'es',
              entryFileNames: () => `[name].mjs`
            },
            {
              dir: 'dist',
              format: 'cjs',
              exports: 'named',
              entryFileNames: () => `[name].cjs`
            }
          ],
          plugins: [
            alias({
              entries: [{
                find: '@',
                replacement: new URL('./src', import.meta.url).pathname
              }]
            }),
            nodeResolve(),
            commonjs(),
            typescript(),
            postcss(),
            babel({
              babelHelpers: 'runtime', // 因为设置了 runtime, 所以 babel.config.js 配置了 @babel/plugin-transform-runtime
              extensions: ['ts', '.tsx']
            })
          ],
          external: [
            /^react(\/.+|$)/,
            /^@ant-design\/icons/,
            /^antd(\/.+|$)/
          ]
        }
      ])

Rollup 打包 React 组件 Typescript 配置

  • 创建 tsconfig.json 配置文件,需生成声明文件,则需要增加 declaration: true
json 复制代码
  {
    "compilerOptions": {
      "baseUrl": "./",
      "outDir": "dist",
      "target": "ESNext",
      "module": "ESNext",
      "jsx": "preserve", // 由于 @babel/preset-react 已经处理了 react 语法, 所以设置 preserve
      "moduleResolution": "Node",
      "useDefineForClassFields": true,
      "allowSyntheticDefaultImports": true,
      "strict": true,
      "sourceMap": false,
      "resolveJsonModule": true,
      "isolatedModules": true,
      "esModuleInterop": true,
      "skipLibCheck": true,
      "declaration": true,
      "lib": [
        "ESNext",
        "DOM"
      ],
      "paths": {
        "@/*": [
          "src/*"
        ]
      }
    },
    "include": [
      "src/**/*.ts",
      "src/**/*.d.ts",
      "src/**/*.tsx"
    ]
  }

Rollup 打包 React 组件 Script 脚本配置

  • 在 package.json 文件中

    json 复制代码
      {
        "scripts": {
          "build": "shx rm -rf dist && rollup --config rollup.config.ts --configPlugin typescript"
        }
      }

如何下载使用 IconSelect 组件?

  • 发布

    json 复制代码
      {
        "name": "@rollup-build-components/icon-select-react18.x",
        "publishConfig": {
          "access": "public",
          "registry": "https://registry.npmjs.org/"
        }
      }
    shell 复制代码
      pnpm publish
  • 安装

    shell 复制代码
      yarn add @rollup-build-components/icon-select-react18.x
    
      pnpm add @rollup-build-components/icon-select-react18.x
  • 使用

    tsx 复制代码
      import SIconSelect from '@rollup-build-components/icon-select-react18.x'
      import { useState } from 'react'
    
      export default function Demo() {
        const [value, setValue] = useState('')
    
        return (
          <>
            <SIconSelect value={value} onChange={setValue} style={{ width: '280px' }}/>
          </>
        )
      }

项目 icon-select-react18.x

相关推荐
PineappleCoder2 小时前
React 18 开发完全指南:从环境搭建到调试优化
前端·react.js
GISer_Jing10 天前
React Next快速搭建前后端全栈项目并部署至Vercel
前端·react.js·前端框架
伍哥的传说10 天前
React 轻量级状态管理器Zustand
前端·javascript·react.js·小程序·前端框架·ecmascript
一嘴一个橘子10 天前
react 的过渡动画
react.js
巴巴_羊10 天前
React 新钩子useImperativeHandle
前端·javascript·react.js
訾博ZiBo10 天前
开源分享:我开发了一个智能文本提取浏览器插件,彻底解决复制粘贴的烦恼
前端·react.js·html
萌萌哒草头将军10 天前
什么?React 中可以写 SolidJS 了?SolidJS 官方出手了 🚀🚀🚀
前端·vue.js·react.js
今日亦是美好的一天10 天前
使用Tailwind CSS和i18n的react实践
前端·react.js·前端框架
niusir10 天前
彻底搞懂 useEffect:依赖项、清除函数与常见陷阱
前端·javascript·react.js
niusir10 天前
理解 React 的渲染机制:为什么组件会重新渲染?
前端·javascript·react.js