wessberg / rollup-plugin-ts

A TypeScript Rollup plugin that bundles declarations, respects Browserslists, and enables seamless integration with transpilers such as babel and swc
MIT License
496 stars 33 forks source link

Types missing due to reference directive bundling #221

Open kevinkucharczyk opened 1 year ago

kevinkucharczyk commented 1 year ago

Reproduction

I have a React component, where I import some React types as:

import { type ReactNode } from 'react';

interface ComponentProps {
  children?: ReactNode;
}

...

tsconfig.json is

{
    "include": ["src/*"],
    "compilerOptions": {
        "baseUrl": ".",
        "esModuleInterop": true,
        "strict": true,
        "skipLibCheck": true,
        "jsx": "react-jsx",
        "module": "ESNext",
        "declaration": true,
        "declarationDir": "dist",
        "sourceMap": true,
        "outDir": "dist",
        "moduleResolution": "node",
        "emitDeclarationOnly": true,
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true
    }
}

rollup config is:

import commonjs from '@rollup/plugin-commonjs';
import ts from 'rollup-plugin-ts';
import terser from '@rollup/plugin-terser';
import peerDepsExternal from 'rollup-plugin-peer-deps-external';

export default [
    {
        input: 'src/react/index.ts',
        output: [
            {
                file: 'dist-react/cjs/index.js',
                format: 'cjs',
                sourcemap: true,
            },
            {
                file: 'dist-react/esm/index.js',
                format: 'esm',
                sourcemap: true,
            },
        ],
        plugins: [
            peerDepsExternal(),
            resolve(),
            commonjs(),
            ts({ tsconfig: './tsconfig.react.json' }),
            terser(),
        ],
        external: ['react', 'react-dom'],
    }
];

Expected Behavior

The bundled index.d.ts file should contain the correct types when referencing 3rd party libraries. It should either be:

/// <reference types="react" />

interface ComponentProps {
  children?: React.ReactNode;
}

export { ComponentProps };

Or provide an option to skip the reference types declaration entirely, and have the .d.ts output be

import { type ReactNode } from 'react';

interface ComponentProps {
  children?: ReactNode;
}

export { ComponentProps };

Actual Behavior

When I run rollup-plugin-ts, the index.d.ts output contains:

/// <reference types="react" />

interface ComponentProps {
  children?: ReactNode;
}

export { ComponentProps };

ReactNode isn't referenced anywhere, and using this component in another repo gives me any types for any props that use React types.

I can use

import React from 'react';

interface ComponentProps {
  children?: React.ReactNode;
}

but I'd prefer not having to import things this way.