Giter Club home page Giter Club logo

rollup-plugin-dts's Introduction

rollup-plugin-dts

Build Status Coverage Status

This is a plugin that lets you roll-up your .d.ts definition files.

Usage

Install the package from npm:

$ npm install --save-dev rollup-plugin-dts

Add it to your rollup.config.js:

import { dts } from "rollup-plugin-dts";

const config = [
  // …
  {
    input: "./my-input/index.d.ts",
    output: [{ file: "dist/my-library.d.ts", format: "es" }],
    plugins: [dts()],
  },
];

export default config;

NOTE A default import of the plugin using import dts from "rollup-plugin-dts"; is still supported for existing implementations of this package. However, a named import is suggested to avoid the error [!] TypeError: dts is not a function12 in certain rollup config file implementations.

And then instruct typescript where to find your definitions inside your package.json:

  "types": "dist/my-library.d.ts",

NOTE that the plugin will automatically mark any external library (@types for example) as external, so those will be excluded from bundling.

Maintenance Mode

This project is in maintenance mode. That means there will be no more active feature development. There will still be occasional releases to maintain compatibility with future TypeScript releases. Pull Requests are always welcome, however reaction time on both Issues and PRs can be slow.

What to expect

While this plugin is fairly complete, it does not support all imaginable use-cases. In particular, the plugin works best with already existing .d.ts files generated by the typescript compiler from idiomatic code.

Working with .ts(x) or even .js(x) (when setting allowJs: true) does work, but is not recommended.

The plugin does its own import resolution through the typescript compiler, and usage together with other resolution plugins, such as node-resolve can lead to errors and is not recommended.

All external dependencies from node_modules are automatically excluded from bundling. This can be overridden using the respectExternal setting, but it is generally not recommended. While rollup of external @types generally works, it is not recommended.

Why?

Well, ideally TypeScript should just do all this itself, and it even has a proposal to do that. But there hasn’t been any progress in ~3 years.

Some projects, like rollup itself go the route of completely separating their public interfaces in a separate file.

Alternatives

See some discussions about some of these projects and their tradeoffs.

License

The code is licensed under the copyleft LGPL-3.0. I have no intention to license this under any non-copyleft license.

Footnotes

  1. StackOverflow thread of issue

  2. Github issue

rollup-plugin-dts's People

Contributors

aleclarson avatar andykais avatar angeloashmore avatar anion155 avatar await-ovo avatar btea avatar comandeer avatar cprecioso avatar curlykay9527 avatar dependabot[bot] avatar hyrious avatar ilyasv avatar lesyk-lesyk avatar marijnh avatar mattiasbuelens avatar mister-hope avatar mithodin avatar morlay avatar mrm007 avatar nwylzw avatar pi0 avatar privatenumber avatar rdmurphy avatar rebeccastevens avatar renovate-bot avatar renovate[bot] avatar southpolesteve avatar swatinem avatar xiaoxiangmoe avatar yurynix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rollup-plugin-dts's Issues

Is tree-shaking of tripleslash directives even possible?

CC @aleclarson because this came up in #36

I have never used those tripleslash directives manually before.
AFAIUI, they are kind of like import "react", right? So you don’t import any specific item from them, but import them for their side effects, which are to define / extend some items in the global scope?

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/3173adb046702c25a053a3a1a14ba8774763098a/types/react/index.d.ts#L2805-L2806

I think its completely out of scope for this plugin to analyze any of the external dependencies for possible global scope access.

This might also be related to this setting:

moduleSideEffects: "no-external",

This will remove every empty import "react" if there is nothing from that specific import that one uses.

Well personally I consider messing with things in the global scope a red flag anyway, and I would rather discourage people from doing that, instead of putting too much effort into supporting such usecases.

module declarations with label that is not an ID

The following declaration content fails:

declare module 'd3-selection' {
...
}

With the following error:

[!] (plugin dts) Error: Could not load C:\Users\gordon\git\hpcc-js\node_modules\@types\d3-transition\index.d.ts (imported by C:\Users\gordon\git\hpcc-js\packages\graph\types\Graph.d.ts): namespace name should be an "Identifier"

Error: end must be greater than start

This was originally opened in #63, but was closed due to not having a failing test case. I have a simple failing test case.

//index.d.ts
export { foo } from './foo';

//foo.d.ts
export function foo(): {
    bar: (blah: any, hi: any) => void;
};

and here is my rollup config

import dts from "rollup-plugin-dts";

const config = [
  {
    input: "./index.d.ts",
    output: [{ file: "./out.d.ts", format: "es" }],
    plugins: [dts()],
  },
];

export default config;

then i just run rollup -c rollup.config.js

and i get

./index.d.ts → ./out.d.ts...
[!] Error: end must be greater than start
Error: end must be greater than start
    at MagicString.remove (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:7745:27)
    at treeshakeNode (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:8350:10)
    at renderStatementList (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:8441:17)
    at BlockStatement$1.render (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:10923:13)
    at FunctionExpression$1.render (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:8868:23)
    at AssignmentPattern.render (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:11090:20)
    at FunctionDeclaration.render (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:8864:31)
    at renderStatementList (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:8445:25)
    at Program$1.render (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:13055:13)
    at Module.render (/Users/bwain/dev/test/node_modules/rollup/dist/shared/rollup.js:14753:18)

Use-cases of incorrect result for dts-bundle-generator

Hi @Swatinem!

I'm creator of dts-bundle-generator. Actually this isn't an issue of your tool, but just a little question - you've mentioned in the readme file that

dts-bundle-generator which was a good inspiration for this project but in the end didn’t really work as well for my use-cases.

Can you please provide some examples, where dts-bundle-generator doesn't work well for your use-cases? Your cases might be useful to improve dts-bundle-generator and I would appreciated you for providing additional interesting examples.

Thanks in advance!

Spread operator in tuple types not supported

HI! Thanks for the module.

But it's still does not supports spread in tuple type am I right? microsoft/TypeScript#24897

roolup-plugin-dts: 1.1.8
typescript: 3.6.3
pnpm: 3.8.1

Error message:

[!] (plugin dts) Error: Could not load ./packages/lib-draw/build/utils/TypedEventEmitter.d.ts (imported by ./packages/lib-draw/build/Client.d.ts): Syntax not yet supported
1 | import { EventEmitter } from 'events';
> 2 | declare type Constructor<T = any, As extends [...any[]] = [...any[]], St = {}> = {
|                                               ^^^^^^^^
3 |     new (...args: As): T;
4 | } & Pick<St, keyof St>;
5 | declare type Arguments<T> = T extends (...args: any) => any ? Parameters<T> : T extends new (...args: any) => any ? ConstructorParameters<T> : any[];
Error: Could not load ./packages/lib-draw/build/utils/TypedEventEmitter.d.ts (imported by ./packages/lib-draw/build/Client.d.ts): Syntax not yet supported
1 | import { EventEmitter } from 'events';
> 2 | declare type Constructor<T = any, As extends [...any[]] = [...any[]], St = {}> = {
|                                               ^^^^^^^^
3 |     new (...args: As): T;
4 | } & Pick<St, keyof St>;
5 | declare type Arguments<T> = T extends (...args: any) => any ? Parameters<T> : T extends new (...args: any) => any ? ConstructorParameters<T> : any[];
at DeclarationScope.convertTypeNode (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:700:19)
at DeclarationScope.convertTypeNode (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:646:22)
at DeclarationScope.convertTypeParameters (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:617:18)
at Transformer.convertTypeAliasDeclaration (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:988:37)
at Transformer.convertStatement (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:914:25)
at new Transformer (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:849:18)
at transformFile (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:1115:29)
at Object.load (./node_modules/.registry.npmjs.org/rollup-plugin-dts/[email protected][email protected]/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:1146:33)
at Promise.resolve.then (./node_modules/.registry.npmjs.org/rollup/1.22.0/node_modules/rollup/dist/rollup.js:16616:25)

import typeof + import typeof member access

It seems the test case I submitted in issue #49 was not complex enough, here's another one

Test

export type TypeScript = typeof import ("typescript");
export interface Test {
  rollup: import("rollup").RollupOptions;
}

Expect

import * as ɨmport1_typescript__ from 'typescript';
import { RollupOptions } from 'rollup';
declare type TypeScript = typeof ɨmport1_typescript__;
interface Test {
  rollup: RollupOptions;
}
export { Test, TypeScript };

Actual

import * as ɨmport1_typescript__ from 'typescript';
import { RollupOptions } from 'rollup';
declare type TypeScript = typeof ɨmport1_typescript__;
RollupOptions
export { Test, TypeScript };

And these type-aliases are perfectly fine and valid code.

Intellij is going nuts reporting usage of non-ASCII symbols
Maybe it could be ASCII symbol like $import or __import for that?
image

Originally posted by @gavar in #49 (comment)

Support for star export

import { makeExecutableSchema } from 'graphql-tools';
console.log(makeExecutableSchema);
  tsup ./x.ts --bundle
Error parsing: /tmp/x.ts:1:8
'makeExecutableSchema' is not exported by node_modules/graphql-tools/dist/index.js, imported by x.ts
1: import { makeExecutableSchema } from 'graphql-tools';
           ^
2: 
3: console.log(makeExecutableSchema);

This is node_modules/graphql-tools/dist/index.d.ts.

export * from './Interfaces';
export * from './makeExecutableSchema';
export * from './mock';
export * from './stitching';
export * from './transforms';
export { SchemaDirectiveVisitor } from './schemaVisitor';

Here is ./makeExecutableSchema which exports makeExecutableSchema.

import { GraphQLSchema } from 'graphql';
import { IExecutableSchemaDefinition, ILogger } from './Interfaces';
export declare function makeExecutableSchema<TContext = any>({ typeDefs, resolvers, connectors, logger, allowUndefinedInResolve, resolverValidationOptions, directiveResolvers, schemaDirectives, parseOptions, inheritResolversFromInterfaces }: IExecutableSchemaDefinition<TContext>): GraphQLSchema;
export declare function addCatchUndefinedToSchema(schema: GraphQLSchema): void;
export declare function addErrorLoggingToSchema(schema: GraphQLSchema, logger: ILogger): void;
export * from './generate';

Make it possible to export namespaces

Currently re-exporting namespaces creates invalid code, because of the way that rollup handles these things.

It would be good to research if it is even possible at all to solve this usecase.

import * as ns from "./namespace";

export { ns };

imported generics are stripped

// create.d.ts
export default function create<S>(): import('./types').IBuilder<S>
// index.d.ts
import c from './create'
export {c as create}

Expected Result

interface IBuilder<S> {
// ...
}
declare function create<S>(): IBuilder<S>

Actual Result

interface IBuilder<S> {
// ...
}
declare function create<S>(): IBuilder // <--- mising generic

I couldn't really find any workaround. Is this a bug or am I doing something wrong ?

Support non-ambient ".ts" modules

I'm curious why support for non-ambient (eg: .ts not .d.ts) definitions was removed.

I don't want this plugin to emit anything other than the .d.ts bundle, but it would be nice to avoid generating intermediate .d.ts modules. Also, with ts-loader and awesome-typescript-loader, it's not possible to generate .d.ts modules if you want to use a forked process for type checking (eg: with fork-ts-checker-webpack-plugin).

To be clear, I don't want this plugin to perform type checking, either.

Add better errors / logging

There are quite some places where the plugin throws errors either because of assertions on the ts AST, or because certain features are not yet supported. It would be nice to provide better errors, also with a codeframe (tsc definitely has that, not sure if it is exposed via API) and a better explanation what to do in that case.

Error: end must be greater than start

I'm not sure if the bug is in rollup directly or this plugin, but I can bundle my application correctly, but when I try to bundle my declaration files, I get this issue:

./dist/types/module.d.ts → ./dist/sdk.d.ts...
[!] Error: end must be greater than start
Error: end must be greater than start

Config:

{
    input: './dist/types/module.d.ts',
    output: [{ file: './dist/sdk.d.ts', format: 'es' }],
    plugins: [dts()],
  }

I was using Webpack DTS webpack-dts-bundle before with a similar config:

new DtsBundlePlugin({
    name: 'sdk',
    main: resolve('../dist/types/module.d.ts'),
    out: resolve('../dist/sdk.d.ts'),
    externals: true
}))

Error: end must be greater than start

Hi,

I was trying to use this in a fairly large, somewhat older project converted from JS recently and ran into what I believe is a bug. Here's a simple replication case:

index.d.ts

export interface Cache {
  destroy: () => void;
}
export declare const uniqueId: (prefix?: string) => string;
export declare const Cache: () => Cache;

rollup.config.js:

import dts from "rollup-plugin-dts";

const config = [
  {
    input: "./index.d.ts",
    output: [{ file: "./out.d.ts", format: "es" }],
    plugins: [dts()],
  },
];

export default config;

When trying to bundle the above, rollup will throw a end must be greater than start error.

Interestingly, I found if I rearrange the above so the uniqueId function is after the Cache function then it'll work. However, given the size of the project that's not really a viable option for me personally.

So I just thought I'd log this in hopes I could get some help to get it resolved. I'm happy to look into it myself, I'm just not too sure where to start to be honest.

Thanks!

[import ModuleName = require('module-name')] Syntax not yet supported

Error: Could not load /Users/xo/code/scratchdb/database/node_modules/@types/better-sqlite3/index.d.ts (imported by lib/drivers/sqlite.ts): Syntax not yet supported

  10 | // TypeScript Version: 3.0
  11 | 
> 12 | import Integer = require("integer");
     | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  13 | 
  14 | type VariableArgFunction = (...params: any[]) => any;
  15 | type ArgumentTypes<F extends VariableArgFunction> = F extends (...args: infer A) => any
    at Transformer.convertStatement (/Users/xo/code/scratchdb/database/node_modules/tsup/dist/rollup-plugin-dts-a7b98f98.js:972:19)
    at new Transformer (/Users/xo/code/scratchdb/database/node_modules/tsup/dist/rollup-plugin-dts-a7b98f98.js:880:18)
    at transformFile (/Users/xo/code/scratchdb/database/node_modules/tsup/dist/rollup-plugin-dts-a7b98f98.js:1234:29)
    at Object.load (/Users/xo/code/scratchdb/database/node_modules/tsup/dist/rollup-plugin-dts-a7b98f98.js:1280:33)
    at /Users/xo/code/scratchdb/database/node_modules/rollup/dist/shared/rollup.js:18234:25
    at processTicksAndRejections (internal/process/task_queues.js:82:5)

import typeof issue

Test

export type TypeScript = typeof import ("typescript");

Expect

declare type TypeScript = typeof import ("typescript");
export { TypeScript };

Actual

import * as ɨmport1_typescript__ from 'typescript';
declare type TypeScript = typeof ɨmport1_typescript__;
export { TypeScript };

`export as namespace` not yet supported

The following declarion:

export as namespace dagre;

Causes the following error:

[!] (plugin dts) Error: Could not load C:\Users\gordon\git\hpcc-js\node_modules\@types\dagre\index.d.ts (imported by C:\Users\gordon\git\hpcc-js\packages\graph\types\graph2\layouts\dagre.d.ts): Syntax not yet supported

Rollup 1.26.0 regression

I found that upgrading to rollup 1.26.0 breaks my build using this plugin.

Example:

// foo.d.ts
export class A {}
export class B {}
// index.d.ts
export * from './foo';
import dts from 'rollup-plugin-dts';

export default [
    {
        input: './index.d.ts',
        output: {
            file: './out.d.ts',
            format: 'es'
        },
        plugins: [
            dts()
        ]
    }
];

Gives the following error:

./index.d.ts → ./out.d.ts...
[!] TypeError: Cannot read property 'value' of undefined
TypeError: Cannot read property 'value' of undefined
    at Module.addExport (/example/node_modules/rollup/dist/rollup.js:9971:40)
    at ExportNamedDeclaration.initialise (/example/node_modules/rollup/dist/rollup.js:6783:22)
    at new NodeBase (/example/node_modules/rollup/dist/rollup.js:3110:14)
    at new ExportNamedDeclaration (/example/node_modules/rollup/dist/rollup.js:6773:1)
    at Program$1.parseNode (/example/node_modules/rollup/dist/rollup.js:3230:27)
    at new NodeBase (/example/node_modules/rollup/dist/rollup.js:3109:14)
    at new Program$1 (/example/node_modules/rollup/dist/rollup.js:8190:1)
    at Module.setSource (/example/node_modules/rollup/dist/rollup.js:9904:20)
    at Promise.resolve.catch.then.then.then (/example/node_modules/rollup/dist/rollup.js:12641:20)

Question: Is it possible to compile TS files via this plugin

I'm using your module in some projects. I've updated it from v0.13.0 to v1.1.2 and got an error

[!] TypeError: rollupPluginDts.ts is not a function
TypeError: rollupPluginDts.ts is not a function
    at Object.<anonymous> (/Users/microshine/github/pv/asn1-schema/rollup.config.js:15:23)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.require.extensions..js (/Users/microshine/github/pv/asn1-schema/node_modules/rollup/bin/rollup:1035:24)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at rollup__default.rollup.then.then (/Users/microshine/github/pv/asn1-schema/node_modules/rollup/bin/rollup:1042:32)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Here is my rollup config file for [email protected]

import { ts, dts } from "rollup-plugin-dts";

const pkg = require("./package.json");
const external = [...Object.keys(pkg.dependencies)];
const input = "src/index.ts";

export default [
  { // CommonJS
    input,
    plugins: [
      ts({
        compilerOptions: {
          removeComments: true,
        },
      }),
    ],
    external,
    output: [
      {
        file: pkg.main,
        format: "cjs",
      },
      {
        file: pkg.module,
        format: "es",
      }
    ]
  },
  { // Definitions
    input,
    plugins: [
      dts({
        compilerOptions: {
          noResolve: true,
        }
      }),
    ],
    external,
    output: [
      {
        file: pkg.types,
        format: "es",
      }
    ]
  },
];

`OptionalTypeNode` is not supported

Using:

type DateRange = [Date?, Date?];

Gives:

Error: Could not load DateUtils.d.ts (imported by index.d.ts): Syntax not yet supported
 1 | export declare type DateRange = [Date?, Date?];
   |                                  ^^^^^

Getters not supported?

[!] (plugin dts) Error: Could not load ~/dev/wana/src/auto.ts 
(imported by ~/dev/wana/src/core.ts): Syntax not yet supported
> 24 |     get test(): number | null;
     |     ^^^^^^^^^^^^^^^^^^^^^^^^^^

Repo here: https://github.com/alloc/wana

rollup-plugin-dts version: tested both 1.1.5 and 1.1.11

typescript version: 3.7.2

React functional component error

Hi, I'm trying this plugin to bundle a react lib.

I have some function components in different files and would like to bundle it
with rollup along with its dts. Here is the code of one of the component.

export interface AlertProps {
  type: 'info' | 'error';
  children?: React.ReactNode;
}

export const Alert = (props: AlertProps) => {
  const { type, ...rest } = props;
  return (
    <div
      style={{
        background: type === 'info' ? 'blue' : 'red',
      }}
      {...rest}
    />
  );
};
Alert.defaultProps = {
  type: 'info',
};

With my rollup.config.js file

import { dts } from 'rollup-plugin-dts';

export default [
  otherBundleConfig,
  {
    input: 'src/index.ts',
    output: { file: 'dist/lib.d.ts', format: 'esm' },
    plugins: [dts()],
  },
];

It produces error like this:

{ kind: 160, code: '\n    (props: AlertProps): JSX.Element;' }
{ kind: 160, code: '\n    (props: ButtonProps): JSX.Element;' }
[!] (dts plugin) Error: Unknown TypeElement
src/Alert.tsx
Error: Unknown TypeElement
    at DeclarationScope.convertMembers (<rootProject>/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:261:23)
    at DeclarationScope.convertTypeNode (<rootProject>/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:291:25)
    at Transformer.convertVariableStatement (<rootProject>/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:485:19)
    at Transformer.convertStatement (<rootProject>/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:412:25)
    at new Transformer (<rootProject>/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:368:18)
    at Object.transform (<rootProject>/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:682:31)
    at Object.transform (<rootProject>/node_modules/rollup-plugin-dts/dist/rollup-plugin-dts.js:739:29)
    at <rootProject>/node_modules/rollup/dist/rollup.js:16611:25

I tried to change this statement from rollup-plugin-dts distribution (I think it comes from DeclarationScope.ts file)

// before
if (ts.isMethodDeclaration(node) ||
  ts.isMethodSignature(node) ||
  ts.isConstructorDeclaration(node) ||
  ts.isConstructSignatureDeclaration(node)) {
  this.convertParametersAndType(node);
}

// after
if (ts.isMethodDeclaration(node) ||
    ts.isMethodSignature(node) ||
    ts.isConstructorDeclaration(node) ||
    ts.isCallSignatureDeclaration(node) || // added this condition
    ts.isConstructSignatureDeclaration(node)) {
    this.convertParametersAndType(node);
}

Then it works. I'm not experienced with typescript AST though and don't know the implication of that addition.

bundling multiple d.ts files Bug

Hi so I'm not entirely sure if this is a bug of dts plugin or rollup or little of both. Or maybe I'm just doing something wrong :-D

I'm combining many small .js files into 1 index file. All these small files have their .d.ts definition. Therefore, I want to combine those d.ts files as well

get-true.d.ts

export default function getTrue(...args: any): boolean

rollup entry point: index.d.ts or index.ts, it doesn't matter

export {default as getTrue} from './get-true'

Expected Result
In an ideal world, after running this plugin with rollup I would like to have

export function getTrue(...args: any): boolean

Actual Result

declare function getTrue(...args: any): boolean

export { getTrue };
  1. I don't understand why the declare keyword appeared. Someone had an opposite problem #24 . But I can live with that.
  2. What bothers me is the export at the end of the file
    tsc complains about
function getTrue(...args: any): boolean

export { getTrue };

but export function getTrue(...args: any): boolean is just fine. I need such output for another tool: typedoc

If I set the property external: (id) => true in rollup config then, I think, I don't actually need this plugin 😆 . And I get

export { default as getTrue } from './get-true';

tsc does not complain about anything in this last example

Can you advise what can I do about it? Am I doing something wrong?

Cannot set compilerOptions which have enum type

@Swatinem thank you for your amazing plugin. It's very useful tool for TS + Rollup developing

I'm trying to change target via compilerOptions in plugin. But I can't do it cause rollup-plugin-dts doesn't export this enum.

Would it be better to use string for enums like TS options does?

Screenshots

rollup.config.js

image

node console

image

Environment

Name Version
rollup 1.1.2
rollup-plugin-dts 0.13.0
typescript 3.3.3
node 10.13.0
MacOS 10.14.3

Duplicate declaration extension

When bundling a multi-entry package the declaration file extension gets duplicate:

     {
            input: ['build/foo.d.ts', 'build/bar.d.ts'],
            output: [{
                dir: 'build',
                format: 'es'
            }],
            plugins: [dts({respectExternal: true})],
        }

Generates two files foo.d.d.ts and bar.d.d.ts.

Make `.ts` mode compatible with `rollup-watch`

CC @aleclarson

Hm, I completely forgot about #15 when I accepted #32.

Now (again), it uses createProgram ahead of time and queries that program instance inside the load hook. But the program instance is never invalidated based on watch feedback.

Thats also what I always meant when I said that using the typescript api for anything more than very trivial usecases is quite hard…

Honor "external" options.

My package has dependencies on two third party libraries:

  • @hpcc-js/common
  • d3-drag

For my main bundle I have configured rollup to make "@hpcc-js/common" external (not bundled in my output), while "d3-drag" defaults to internal (so IS bundled inside my output).

When I look at the bundled "d" file the imports sections looks like this:

import { SVGWidget, TextBox, Widget, Text, Icon, SVGZoomWidget, SVGGlowFilter, ISize, PropertyExt, Selection, Utility, Palette, publish } from '@hpcc-js/common';
import { DragBehavior } from 'd3-drag';

I was expecting the DragBehavior to be inlined inside the bundled d.ts file?

Note: DragBehavior is a type which is getting auto resolved by tsc to @types/d3-drag/index.d.ts

Unable to get rollup-plugin-dts to reference local d.ts file

Hello! 👋 I'll preface this with that it may be entirely my fault this isn't working, but I've been trying to sort it out for a bit.

I have a few npm installed imports in a .ts file I've written that do not have types available (either locally or via DefinitelyTyped), so I've done what I normally do and have written a local .d.ts file to tell TypeScript to not worry about it. (This import doesn't appear in the types at all, so there's technically nothing for rollup-plugin-dts to "render" based on it.) My tsconfig.json has strict: true set, so it will throw an error otherwise about implicit any. Something like this in a file called vendor.d.ts that sits next to the input file:

declare module 'lib-without-types';

In VSCode and with tsc --noEmit this is enough — my code passes the check. But when I try to run rollup-plugin-dts against my .ts file, It throws TS7016 about not being able to find a declaration file. As far as I can tell rollup-plugin-dts only considers the input script and that alone, even when the tsconfig.json has an includes value set (which should "tell" TypeScript to include my local d.ts file when resolving types).

(Also super weird — rollup-plugin-dts didn't care/complain about this until TypeScript 3.7 landed. If I roll back to TypeScript 3.6 it doesn't throw TS7016, even if I don't have the vendor.d.ts file at all!)

Is there something I'm missing or is that by design? Thank you!

Error: Cannot overwrite a zero-length range – use appendLeft or prependRight instead

I'm not sue is it rollup or plugin error. I'm trying to build this project with your plugin. It works fine for TS. But I've got Error for DTS.

The error occurs if namespace is using for class implementation
image

It works fine if interface is using without namespace
image

Error

src/index.ts → build/index.d.ts...
[!] Error: Cannot overwrite a zero-length range – use appendLeft or prependRight instead
Error: Cannot overwrite a zero-length range – use appendLeft or prependRight instead
    at MagicString.overwrite (node_modules/rollup/dist/rollup.js:1443:33)

Error 'Unknown Expression' when parsing interface/class extending other types using property access

I've found another use case that's either a bug or just not yet covered by this plugin.

When trying to parse an interface/class extending other interface/class like this (common in React use case)

import React from 'react';

export interface MyComponentProps extends React.HtmlHTMLAttributes<HTMLDivElement> {
  foo: string;
}

export class MyComponent extends React.Component<MyComponentProps> {}

It produced error like this:

{ kind: 189, code: ' React.HtmlHTMLAttributes' }
[!] Error: Could not load <rootProject>/src/index.ts: Unknown Expression

It also happened in React.Component node.

Seems like heritage clauses parsing still doesn't cover property access expression like that.

Types only used in generic parameter list are stripped by Rollup

In the following example, ElementType isn't imported in the generated .d.ts bundle, even though the AnimatedComponent type is still using it.

import { ElementType, ComponentPropsWithRef, ForwardRefExoticComponent } from 'react'

export type AnimatedProps<T> = T
export type AnimatedComponent<
  T extends ElementType
> = ForwardRefExoticComponent<AnimatedProps<ComponentPropsWithRef<T>>>

There is a bug in declare abstract class

This is my source definition file:

import MemberTypes from "./memberTypes";
import TypeInfo from "./typeInfo";
export default abstract class MemberInfo {
    abstract readonly name: string;
    abstract readonly declaringType: TypeInfo;
    abstract readonly memberType: MemberTypes;
}

after bundle with other types result is:

default abstract class MemberInfo {
    abstract readonly name: string;
    abstract readonly declaringType: TypeInfo;
    abstract readonly memberType: MemberTypes;
}

Instead, "default abstract" should be "declare abstract" output

Handle TS `namespace`s correctly

See #8 (comment)

export declare function Alert(props: AlertProps): JSX.Element;
export declare namespace Alert {
    var defaultProps: {
        type: string;
    };
}

This is also related to #7

I just recently learned what typescript namespaces actually are and how to use them in declaration files. I think its a little more complicated to make them work correctly.

Consider changing project direction

I have been thinking a lot lately about TS project management in general and even started a small blog series on this topic. This, combined with some issues and requests for this projects made me rethink the project direction.

I would appreciate some feedback on these ideas.
CC @aleclarson @robhicks @timocov @octogonz

How it works now

The plugin currently uses the typescript createProgram and emit APIs to basically typecheck your whole code ahead of time, and emit declaration files for each source file.

This is:

  • not really good for performance
  • a huge pain to manage all the compilerOptions, and to use the ts API in general.
  • I’m sure I miss/supress some useful diagnostics along the way
  • It interferes badly with rollup watch #15

How I think it should work in the future

I think to move forward, its needed to take a step back. Let some other tool worry about compiling typescript, and focus only on bundling pre-generated .d.ts files, similar to how api-extractor works.

So it would use the typescript compiler as a parser only.

Pros

  • would follow do only one thing and do it well
  • would massively simplify the plugin itself
  • should improve performance slightly?
  • would work better with watch mode
  • would give users more freedom about how they want to compile their TS code (--incremental, etc), and about how they want to bundle their .js code.

Cons

  • would not be single-dependency / zero-config anymore
  • would require users to deal with .ts -> .js / .d.ts compilation themselves
  • watch mode would require two separate watchers (tsc --watch and rollup --watch?)

Comments in d.ts dependencies are not included

Hello! 👋

Thank you for an excellent library — it's so cool how this takes advantage of how Rollup works to accomplish tree-shaking for d.ts files.

I noticed when I was experimenting with the plugin that comments that are present in files that are depended on are not included in the final output. I'm not sure if that's intentional, but IMO it may be nice to bring them over too if possible? I tend to use TypeScript primarily through VS Code, and it's really nice that the comments in d.ts are surfaced when you inspect a function.

I've prepared an example repo that shows this happening. If a function has a comment in the entrypoint, it'll be there. If something is commented in a dependency, the comment is dropped.

https://github.com/rdmurphy/rollup-plugin-dts-comments

Thank you!

[feature] keep module declaration with jsdoc @override

Some time we may extends prototype of deps like below:

declare module "rxjs/internal/Observable" {
  interface Observable<T> {
     custom()
  }
}

the module declaration should be keep. (now tsc will keep them, but rollup-plugin-dts dropped).

Error on export function delegates as default

Hi
we have a destination file as below:

export default function autobind(): ClassDecorator | MethodDecorator;
export default function autobind(constructor: Function): void;
export default function autobind(prototype: Object, name: string, descriptor: PropertyDescriptor): PropertyDescriptor;

on compile time get error:

Error: A module can only have one default export

How to fix this error?

Circular dependencies get defined multiple times

First of all: Great plugin :)

I'm working on a project (public soon) where I have the following pattern:

import Foo from './Foo';

export default class FooManager {
    constructor() {
        this.foos = [ new Foo() ];
        // ...
    }
}
import FooManager from './FooManager';

export default class Foo {
    public manager: FooManager;

    constructor(manager: FooManager) {
        this.manager = manager;

        // ...
    }
}

This way I can use config and such from FooManager in the methods of Foo.

This also creates a circular dependency, which works fine. When compiling the typescript down to javascript with rollup-plugin-typescript2 things work as expected. But when compiling the types the following happens:

declare class FooManager {
    // ...
}
declare class Foo {
    // ...
}
declare class FooManager$1 {
    // ...
}

export default FooManager$1;

Despite the unexpected output, it does work as expected when using it. So no rush in fixing this.

This happens when I use FooManager.ts as input, but also when I use the freshly generated FooManager.d.ts as input.

My rollup.conf.js for the sake of completeness:

import pkg from './package.json';
import tslint from "rollup-plugin-tslint";
import typescript from 'rollup-plugin-typescript2';
import dts from 'rollup-plugin-dts';
import cleanup from 'rollup-plugin-cleanup';
import del from 'rollup-plugin-delete';

const config = [
    {
        input: './src/FooManager.ts',
        output: [
            { file: pkg.main, format: 'cjs' },
            { file: pkg.module, format: 'es' },
        ],
        plugins: [
            // Delete contents of target folder
            del({
                targets: pkg.files,
            }),

            // Lint source files
            tslint({
                throwOnError: true,
            }),

            // Compile source (typescript) to javascript
            typescript({
                tsconfig: './tsconfig.json',
            }),

            // Remove things like comments and whitespace
            cleanup({
                extensions: ['.ts', '.js'],
            }),
        ],
    },

    {
        input: './src/FooManager.ts',
        // input: './dist/src/FooManager.d.ts',
        output: [
            { file: pkg.types, format: 'es' }
        ],
        plugins: [
            // Generate types (.d.ts)
            dts(),
        ],
    },
];

module.exports = config;

Edit: Forgot to include the warning that's logged when bundling

./src/FooManager.ts → dist/FooManager.d.ts...
(!) Circular dependency: src\Foo.ts -> src\FooManager.ts -> src\Foo.ts
created dist/FooManager.d.ts in 1.3s

Comment regarding API Extractor

@Swatinem I noticed this text in the README:

  • API Extractor
    an official Microsoft project, which however is super complicated and I was not
    able to get it to work.

As someone who works on API Extractor, I'm curious what problems you encountered, and whether there's anything we could do to address them. API Extractor 7 has been in "beta" for the past few months because the analyzer was overhauled. We're now very close to releasing it. Since it's a new major version, this is a pretty good time to make breaking changes to the command line or config files if something should be improved/simplified.

Support for "incremental" mode

This plugin should respect "incremental": true in the local tsconfig.json module.

Also, tsBuildInfoFile should be supported. 👍

Display better error for unneeded semicolon

Could you replace this error with something nicer that states the actual issue?

[!] (plugin dts) Error: Could not load /Users/xo/code/scratchdb/database/lib/types.d.ts (imported by /Users/xo/code/scratchdb/database/lib/index.ts): Syntax not yet supported

  3 | export interface Connection {
  4 |     uri: string;
> 5 | };

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.