如何使用 TypeScript、Ant Design 和 Rollup 构建组件库

How to build a component library using TypeScript, Ant Design and Rollup

我正在尝试为 TypeScript 中的可重用组件库创建示例样板,对 UI 元素使用 Ant Design,对捆绑使用 Rollup。

Ant Design documentation 虽然有用,但没有给出配置 Rollup 的具体细节,我也没有运气找到使用相同技术堆栈的示例。

使用来自各种在线资源的信息,我整理了一个大纲样板并将其发布到以下 GitHub repository

但是,构建输出显示了一些来自 Rollup 的警告,这些警告与重写对 'this' 的引用有关。谁能建议更改我的构建配置以解决此问题?

(!) `this` has been rewritten to `undefined`
https://rollupjs.org/guide/en#error-this-is-undefined
node_modules\antd\es\affix\index.js
 6: import _inherits from "babel-runtime/helpers/inherits";
 7: import _typeof from "babel-runtime/helpers/typeof";
 8: var __decorate = this && this.__decorate || function (decorators, target, key, desc) {
                     ^
 9:     var c = arguments.length,
10:         r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc,
...

@Steve,我不知道你是否已经解决了这个问题,但我找到了一个对我有用的解决方案 rollup-plugin-babel:

import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import postcss from 'rollup-plugin-postcss';
import typescript from 'rollup-plugin-typescript2';
import url from 'rollup-plugin-url';

import pkg from './package.json';

const antdVars = require('./src/antd-vars');

export default {
    input: 'src/index.tsx',
    output: [
        {
            file: pkg.main,
            format: 'cjs',
            exports: 'named',
            sourcemap: true,
        },
        {
            file: pkg.module,
            format: 'es',
            exports: 'named',
            sourcemap: true,
        },
    ],
    plugins: [
        peerDepsExternal(),
        url(),
        nodeResolve({
            extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'],
        }),
        typescript({
            exclude: ['*.d.ts', '**/*.d.ts', '**/*.story.tsx', '**/*.spec.tsx'],
            rollupCommonJSResolveHack: true,
            clean: true,
        }),
        babel({
            babelrc: false,
            plugins: [['import', { libraryName: 'antd', style: true }]],
            extensions: ['.js', '.jsx', '.ts', '.tsx'],
            exclude: /\**node_modules\**/,
        }),
        commonjs({
            include: /\**node_modules\**/,
        }),
        postcss({
            extensions: ['.css', '.scss', '.less'],
            use: ['sass', ['less', { javascriptEnabled: true, modifyVars: antdVars }]],
        }),
    ],
};

通过更新汇总配置以使用 rollup-plugin-peer-deps-external 将 antd 依赖项标记为外部来解决问题

更新后的代码可以在Repo on GitHub

中看到