GithubHelp home page GithubHelp logo

timocov / dts-bundle-generator Goto Github PK

View Code? Open in Web Editor NEW
699.0 699.0 35.0 721 KB

A tool to generate a single bundle of dts with types tree-shaking

License: MIT License

JavaScript 9.84% TypeScript 90.16%
bundle definition dts typescript typescript-definitions

dts-bundle-generator's People

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

dts-bundle-generator's Issues

Could not find a declaration file for module

Bug report

I am importing a specific file from a library on npm, e.g. import file1 from 'someLib/src/file1'. To get its types to work (from @types/someLib), I have to basically reassign its types to that specific file by including a separate someLib.d.ts declaration file in my project that looks like this:

declare module 'someLib/src/file1' {
  import someLib from 'someLib';

  export default someLib;
}

Both tsc and my IDE integration are okay with this and pick up the types, but dts-bundle-generator fails to see it somehow and throws the following error:

src/consumer.ts(1,19): error TS7016: Could not find a declaration file for module 'someLib/src/file1'. 'node_modules/someLib/src/file1.js' implicitly has an 'any' type.

I can get it to pass if I set "strict": false in tsconfig.json, but I don't want to do that. As a workaround, I can prefix the import with a comment to disable type-checking (// @ts-ignore before import someLib from 'someLib/src/file1) or create a separate tsconfig.json just for dts-bundle-generator with strict disabled, but I thought I should bring it up here to see if it's a bug or if there's some configuration I've got wrong.

This might be related to #50 but when I tried a triple-slash referenced as proposed there, it included the contents of someLib.d.ts in the generated .d.ts which threw several errors when it attempted to validate the generated file (and I've been told the community is moving from triple-slash references to modules anyway?). I don't understand enough about the declare module and import interop/compatibility yet to fully grasp what's possible and what isn't, but I don't think I can import my someLib.d.ts manually. Also, the usage of someLib is internal only so the types do not need to appear in the output of dts-bundle-generator.

Additional context

CLI command and options:

dts-bundle-generator --umd-module-name myLib --out-file types/myLib.d.ts src/myLib.ts

P.S. Thanks for your work, this project is great. โค๏ธ

Some imports makes adding unnecessary imports

entry.ts

import { Interface } from 'some-npm-package';
export type Type = Interface | null;

some-npm-package/index.ts

export interface Interface {
  field: MyType;
}
export type MyType = number | string;

Expected output:

import { Interface } from 'some-npm-package';
export declare type Type = Interface | null;

Actual output:

import { Interface, MyType } from 'some-npm-package';
export declare type Type = Interface | null;

MyType should be imported from npm module.

Imports globals from @types/react

Bug report
When using the external-imports flag with react, the tools doesn't seem to recognize that certain types are global and imports them from react in the declaration file. This causes an error during the generated file check.

$ dts-bundle-generator -o index.d.ts index.tsx --external-imports react
Compiling input files...
Processing index.tsx
Adding import with name "HTMLButtonElement" for library "react"
Adding import with name "FunctionComponent" for library "react"
Adding import with name "HTMLAttributes" for library "react"
Writing index.tsx -> index.d.ts
Checking generated files...
index.d.ts(1,45): error TS2305: Module '"./node_modules/@types/react"' has no exported member 'HTMLButtonElement'.
Error: Compiled with errors

Input code

import React, { FunctionComponent, HTMLAttributes } from "react";

interface ButtonProps extends HTMLAttributes<HTMLButtonElement> { }

export const Button: FunctionComponent<ButtonProps> = (props) => <button {...props} />;

Expected output

import { FunctionComponent, HTMLAttributes } from "react";
export interface ButtonProps extends HTMLAttributes<HTMLButtonElement> {
}
export declare const Button: FunctionComponent<ButtonProps>;

Actual output

import { FunctionComponent, HTMLAttributes, HTMLButtonElement } from 'react';
export interface ButtonProps extends HTMLAttributes<HTMLButtonElement> {
}
export declare const Button: FunctionComponent<ButtonProps>;

JSDoc of exported item does not present in output

Input:

/**
 * @description Interface description
 */
export interface MyInterface {
	/**
	 * @description
	 */
	field: string;
}

Actual output:

export interface MyInterface {
	/**
	 * @description
	 */
	field: string;
}

Expected output:

/**
 * @description Interface description
 */
export interface MyInterface {
	/**
	 * @description
	 */
	field: string;
}

`export default Name;` is not handled correctly

Code:

class MyClass {}
export default MyClass;

Actual output:

export declare class MyClass {
}
export default MyClass;

Expected output:

declare class MyClass {
}
export default MyClass;

๐Ÿœ import default from namespace with esmoduleInterop true

Bug report

Input code

There is an issue with import default from a namespace export, or module export related to esModuleInterop: true, and --external-imports i18next

import i18next from "i18next";

export class I18N {
  constructor(config: i18next.InitOptions) {

  }
}

Output code

import { InitOptions, i18next } from 'i18next';

export declare class I18N {
	constructor(config: i18next.InitOptions);
}

Expected output

import i18next from 'i18next';

export declare class I18N {
	constructor(config: i18next.InitOptions);
}

Additional context

  • flags: --external-imports i18next

Generated declaration file contains import statements

Bug report

I'm trying to utilize this tool, but I experience an issue where the generated bundle contains an import statement (which I obviously am trying to avoid by creating a bundle). I've uploaded the example here.

Is this a bug or am I just doing something wrong?

The actual output can be generated with the following commands.

$ git clone https://gist.github.com/badeball/6663e9d2a7437bffadbd488ccfdb4cec
$ cd 6663e9d2a7437bffadbd488ccfdb4cec
$ npm install
$ dts-bundle-generator -o index.d.ts index.ts
$ cat index.d.ts

Input code

// foo.ts
export interface FooNode {
  type: "foo";
  number: number;
}

export default function foo (): FooNode {
  return {
    type: "foo",
    number: 5
  };
}

// index.ts
import foo from "./foo";

export default class SomeClass {
  foo() {
    return foo();
  }
}

Expected output

// index.d.ts
// index.d.ts
export interface FooNode {
	type: "foo";
	number: number;
}
export default class SomeClass {
	foo(): FooNode;
}

Actual output

// index.d.ts
export interface FooNode {
	type: "foo";
	number: number;
}
export default class SomeClass {
	foo(): import("./foo").FooNode;
}

Additional context

dts-bundle-generator: v2.0.0
node: v11.3.0

publish latest version

Hello, thanks for this library ๐Ÿ‘
It appears there is some new code in the repo that has not yet published to [email protected]
Is it ready to publish a patch or minor version?
Thanks!
-Dan

Re-exporting support

Hi! happy with your package. It works well at the moment.
However It would be great some re-exporting support, consider the following example:

Input: local.ts

import { Vue } from 'vue';

export function spyComponent (component: Vue): void { }

export { Vue }

Result: local.d.ts

import { Vue } from 'vue';

export declare function spyComponent (component: Vue): void;

Note: declare in "export function" is not necessary.

Namespaces usage problems

Example 1

Input

// a.ts
export namespace Types {
  export interface TypeA {}
  export interface TypeB {}
}

// b.ts
import { Types } from './a.ts';
export interface Type extends Types.TypeA {}

Output

declare namespace Types {
	interface TypeA {
	}
	interface TypeB {
	}
}
export interface Type extends Types.TypeA {
}

Problems:

  1. Namespace Types contains unused and unexported interface TypeB.
  2. Namespace Types still can be imported by import { Types } from './file'; (but I guess this problem cannot be solved because of TypeScript's declaration files meaning). Solved by adding export {} at the end of generated file

Some examples moved to separated issues: #24

Related issues #1 #6 #24

need option for external default imports

Bug report
When running the generator on a npm module that includes their own types in the package like eventemitter3 vs @types/eventemitter3, there is no way to pass the check option of the dts-bundle-generator due to the fact that eventemitter3 uses a default export and the d.ts file that is generated uses import { moduleA, moduleB } from 'module';.

Including @types/eventemitter3 as a dependency and adding --external-types eventemitter3 will not include a /// <reference types="eventemitter3" /> in the output because @types/eventemitter3 is just a stub.

https://www.npmjs.com/package/@types/eventemitter3

This is a stub types definition for EventEmitter3 (https://github.com/primus/eventemitter3). EventEmitter3 provides its own type definitions, so you don't need @types/eventemitter3 installed!

When adding --external-imports eventemitter3 option you will get the following error:

$ dts-bundle-generator --config=./dtsconfig.json -- src/test.ts
Compiler option `outDir` is not supported and will be removed while generating dts
Adding import with name "EventEmitter" for library "eventemitter3"
Writing generated file to dist/test.d.ts...
Checking the generated file...
dist/test.d.ts(7,29): error TS2304: Cannot find name 'EventEmitter'.
Error: Compiled with errors
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Input code
dtsconfig.json

{
	"sort": false,
	"verbose": false,
	"no-check": false,
	"fail-on-class": false,
	"inline-declare-global": false,
	"disable-symlinks-following": false,
	"out-file": "dist/test.d.ts",
	"umd-module-name": "mylib",
	"external-inlines": [],
	"external-imports": [
        "eventemitter3"
    ],
	"external-types": []
}
import EventEmitter from 'eventemitter3';

class MyEmitter extends EventEmitter {}

class KeyboardService {
    private readonly eventEmitter;
    constructor(eventEmitter: EventEmitter = new EventEmitter()) {
        this.eventEmitter = eventEmitter;
    }
}

const mylib = {
    myEmitter: new MyEmitter(),
    services: {
        KeyboardService,
    },
};

export default mylib;

Expected output

import EventEmitter from 'eventemitter3';

declare class MyEmitter extends EventEmitter {
}
declare class KeyboardService {
	private readonly eventEmitter;
	constructor(eventEmitter?: EventEmitter);
}
export declare const mylib: {
	myEmitter: MyEmitter;
	services: {
		KeyboardService: typeof KeyboardService;
	};
};
export default mylib;

export as namespace mylib;

Actual output

import { EventEmitter } from 'eventemitter3';

declare class MyEmitter extends EventEmitter {
}
declare class KeyboardService {
	private readonly eventEmitter;
	constructor(eventEmitter?: EventEmitter);
}
export declare const mylib: {
	myEmitter: MyEmitter;
	services: {
		KeyboardService: typeof KeyboardService;
	};
};
export default mylib;

export as namespace mylib;

Additional context
I would like to propose another option to fix issues regarding packages that need to be import module from 'module' vs import { moduleA, moduleB } from 'module' or import * as module from 'module'.

Add an option for --external-default-imports eventemitter3 that would add a default import into the generated typedef.

input
dtsconfig.json

{
	"sort": false,
	"verbose": false,
	"no-check": false,
	"fail-on-class": false,
	"inline-declare-global": false,
	"disable-symlinks-following": false,
	"out-file": "dist/test.d.ts",
	"umd-module-name": "mylib",
	"external-inlines": [],
    "external-imports": [
        "awesome-lib"
    ],
	"external-default-imports": [
        "eventemitter3"
    ],
	"external-types": []
}

test.ts

import EventEmitter from 'eventemitter3';
import { AwesomeLib } from 'awesome-lib';

class MyEmitter extends EventEmitter {}

class KeyboardService {
    private readonly eventEmitter;
    private readonly awesome;
    constructor(
        eventEmitter: EventEmitter = new EventEmitter(),
        awesome: AwesomeLib = new AwesomeLib()
    ) {
        this.eventEmitter = eventEmitter;
        this.awesome = awesome;
    }
}

const mylib = {
    myEmitter: new MyEmitter(),
    services: {
        KeyboardService,
    },
};

export default mylib;

Expected output

import EventEmitter from 'eventemitter3';
import { AwesomeLib } from 'awesome-lib';

declare class MyEmitter extends EventEmitter {
}
declare class KeyboardService {
	private readonly eventEmitter;
    private readonly awesome;
	constructor(eventEmitter?: EventEmitter, awesome?: AwesomeLib);
}
export declare const mylib: {
	myEmitter: MyEmitter;
	services: {
		KeyboardService: typeof KeyboardService;
	};
};
export default mylib;

export as namespace mylib;

Need warn about ts files (not dts) in compilation from node_modules

I would like to include the typings for https://github.com/Lusito/typed-signals in my DTS bundle, however the extraction fails with "Error: Cannot find symbol for node: emitCollecting".

app.ts:

import {Signal} from "typed-signals";

export const signal: Signal<(argument) => void> = undefined;

package.json:

{
  "name": "dts-bundle-generator-bugreport",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "build": "npx tsc",
    "typings": "npx dts-bundle-generator -o app.d.ts app.ts"
  },
  "dependencies": {
    "typed-signals": "^1.0.2"
  },
  "devDependencies": {
    "dts-bundle-generator": "^1.6.1",
    "typescript": "^3.1.3"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "declaration": true,
    "lib": ["es2015", "dom"]
  }
}

Run:

npm install
npm run typings

Output:

Error: Cannot find symbol for node: emitCollecting

The method looks like this (see https://github.com/Lusito/typed-signals/blob/master/src/Signal.ts):

export class Signal<CB extends Function> {
  // ...
  protected emitCollecting<RT>(collector: Collector<CB, RT>, args: any) {
    // ...
  }
}

Multiple input files?

How do I specify multiple .ts/.d.ts files as input? Or to specify a directory of d.ts files to merge? My application doesn't have a starting point per se, so some files are being omitted. Please advise.

Not only JSDoc added to exported types

Related to #5

Input:

// comment
export interface MyInterface {}

Actual output:

// comment
export interface MyInterface {
}

Expected output:

export interface MyInterface {
}

Ignoring declares

Bug report
I'm bundling my code with webpack, and I have some declares in my files:
Input code - src/globals.d.ts

declare const __DEV__: boolean;
declare module '*.pem' {
  const pem: string;
  export default pem;
}

Webpack bundles fine, and also my editor (vscode) recognizes everything, but when using you library (which is great btw!) it doesn't consider the d.ts files which are placed in src folder.

Code - src/store/router/index.ts

...
private handleRouteChange(location: Location) {
    const { locationRegexes } = this;

    const foundLocation = locationRegexes.find(({ regex }) => testRegex(regex, location.pathname));

    if (!foundLocation) {
      if (__DEV__) {
        console.warn(`Route for ${location.pathname} not found, check config.`);
      }
...

Actual output

src/store/index.ts(26,5): error TS2304: Cannot find name '__DEV__'.
src/store/router/index.ts(38,11): error TS2304: Cannot find name '__DEV__'.
C:\Users\uv\dev\max-quality\node_modules\dts-bundle-generator\check-diagnostics-errors.js:20
    throw new Error(failMessage);
    ^

Error: Compiled with errors
    at checkDiagnosticsErrors (C:\Users\uv\dev\max-quality\node_modules\dts-bundle-generator\check-diagnostics-errors.js:20:11)
    at Object.checkProgramDiagnosticsErrors (C:\Users\uv\dev\max-quality\node_modules\dts-bundle-generator\check-diagnostics-errors.js:11:5)
    at getDeclarationFiles (C:\Users\uv\dev\max-quality\node_modules\dts-bundle-generator\compile-dts.js:67:32)
    at Object.compileDts (C:\Users\uv\dev\max-quality\node_modules\dts-bundle-generator\compile-dts.js:15:20)
    at generateDtsBundle (C:\Users\uv\dev\max-quality\node_modules\dts-bundle-generator\bundle-generator.js:33:33)
    at compilation.chunks.forEach (C:\Users\uv\dev\max-quality\node_modules\ts-declaration-webpack-plugin\index.js:25:19)
    at Array.forEach (<anonymous>)
    at compiler.plugin (C:\Users\uv\dev\max-quality\node_modules\ts-declaration-webpack-plugin\index.js:22:23)
    at AsyncSeriesHook.eval [as callAsync] (eval at create (C:\Users\uv\dev\max-quality\node_modules\tapable\lib\HookCodeFactory.js:24:12), <anonymous>:7:1)

Cannot find namespace 'fs'

Hi.

When I use node core packages as fs there is issue with generating declaration file via bundle.

When I have in my code this:

import * as fs from 'fs';

export default class TestClass {
    public getStats(path: string): Promise<fs.Stats> {
        ...
    }
}

dts-bundle-generator create declaration similar to this:

/// <reference types="node" />

import { Stats } from 'fs';

declare class TestClass {
	getStats(path: string): Promise<fs.Stats>;
}

I created repository with whole problem here:

https://github.com/Scorpio1337/dts-generator-issue

Maybe I doing something wrong.

For solution I used hack with require (it is in repo too), but it's really ugly.

Error: Debug Failure. False expression

Hello, I'm getting this error Error: Debug Failure. False expression: Paths must either both be absolute or both be relative.

It happens only when I'm trying to add a class that extends another class from another directory.

Can you please explain to me why I'm getting this error?

Add 'declare' to classes

Hi Evgeniy,

Some of the .d.ts files I am using have classes declared without the use of the declare keyword:

class Bounds {
	x1: number;
	y1: number;
	x2: number;
	y2: number;
}

TypeScript does not seem to have any issue with these when they are in module files. However, after generating with dts-bundle-generator, TypeScript is not as forgiving??

image

So, perhaps you might always emit the declare keyword if it is not already present on classes.

Error with tsconfig `extends` option set to a node module path

Bug report

Having the extends option set in tsconfig.json to a path referring to a node module results in an error.

Input code

tsconfig.json

{
  "extends": "my-module/tsconfig",
  "include": ["./src/**/*"],
  "compilerOptions": {
    "baseUrl": "./src/",
    "outDir": "./dist/"
  }
}
$ dts-bundle-generator -o dist/index.d.ts src/index.ts

Expected output

Compiling input files...
Compiler option `outDir` is not supported and will be removed while generating dts
Processing src/index.ts
Writing src/index.ts -> dist/index.d.ts
Checking generated files...
Done in 3.70s

Actual output

Compiling input files...
message TS6096: File 'my-module/tsconfig' does not exist.
Error: Error while processing tsconfig compiler options
error Command failed with exit code 1.

Additional context

After investigation it seems that the basePath argument (3rd) to ts.parseJsonConfigFileContent has to be an absolute path for the extends module resolution to work properly.

I'll submit a pull request in a minute.

Add handling `export =` for namespaces

[email protected]

to reproduce

git clone https://github.com/e2tox/reproduce-dts-bundle-generator-node-imports.git
cd reproduce-dts-bundle-generator-node-imports
npm install
npm test

Error details:

> dts-bundle-generator -o ./index.d.ts ./stoppable.d.ts

Writing generated file to ./index.d.ts...
Checking the generated file...
index.d.ts(1,52): TS2304: Cannot find name 'EventEmitter'.
Error: Compiled with errors
npm ERR! Test failed.  See above for more details.

Empty declaration file when processing entry points using export = class

I'm developing a npm module and I wanted to generate an index.d.ts for including it in the module.
My entry point is like this:

src/index.ts:

import { Cache } from "./lib/main";
export = Cache;

Cache is the main class and is placed in /lib/main/cache.ts
The export = Cache is the only way I found that allows to use the library in the same way in both Typescript and Javascript:

const Cache = require('mylib');
const cache = new Cache();

When executing
dts-bundle-generator -o dtsbundlegeneratortest1.d.ts src/index.ts the output file is empty.
But if I execute:
dts-bundle-generator -o dtsbundlegeneratortest1.d.ts src/cache.ts the output file generates all typings (including public methods and properties but also the private ones...)

Add possibility to import types for libraries with typings from `@types`

For now libraries with typings from @types/ can be only referenced via triple-slash directive /// <reference types="name" />.

We need to add possibility to import such libraries via import statement. The main problem of this for now is using declare module statements to declare module.

Statement `export * from 'other-module'` is not emitted

Hi timocov,

I want share with you the new findings from my testing of yesterday.

In typescript, we can export the types from other module directly as following. But the following two lines are not emitted.

Input File

/// <reference types="node" />
export { Server } from 'http';
export * from 'http2';

Actual Result
export { Server } from 'http';
export * from 'http2';

Expected Result

/// <reference types="node" />
export { Server } from 'http';
export * from 'http2';

Please use this repo to reproduce this finding

git clone https://github.com/e2tox/reproduce-dts-bundle-generator-node-imports.git
cd reproduce-dts-bundle-generator-node-imports
npm install
npm test
cat index.d.ts

Thanks

Types from `@types` is not imported when Error object is introduced

Hi timocov,

It's me again. I found a minor issue that EventEmitter is not imported when Error object is introduced. index.d.ts will be generate only when you removed the Error object from the parameters.

Following is the project to reproduce this issue. Fail with [email protected]

git clone https://github.com/e2tox/reproduce-dts-bundle-generator-node-imports.git
cd reproduce-dts-bundle-generator-node-imports
npm install
npm test

Thanks again

Add possibility to specify multiple entries

For big projects the compilation can take a long time, and when you need to provide multiple declarations you'll run the tool multiple times and it'll compile the same files multiple times.

If we have a way to specify multiple entries, I hope we'll reduce the compilation time.

We need to save current API as well as possible to avoid big breaking changes.

I believe that multiple entries should be available only via config file.

Override `skipLibCheck` option when checking output file validity

normalLog('Checking generated files...');
const preferredConfigFile = bundlerConfig.compilationOptions !== undefined ? bundlerConfig.compilationOptions.preferredConfigPath : undefined;
const compilerOptions = getCompilerOptions(outFilesToCheck, preferredConfigFile);
if (compilerOptions.skipLibCheck) {
warnLog('BEWARE: The generated file could not be properly checked due enabled "skipLibCheck" compiler option');
}
const program = ts.createProgram(outFilesToCheck, compilerOptions);
checkProgramDiagnosticsErrors(program);

It should be trivial to just override that option and check the output file regardless of what was set.

Imports from node_modules are not included

Consider the following code:

import {OnInit} from "@angular/core";
class MyComponent implements OnInit {
    ngOnInit() {};
}

Expected output:

import {OnInit} from "@angular/core";
declare class MyComponent implements OnInit {
    ngOnInit(): void;
}

Actual output:

declare class MyComponent implements OnInit {
    ngOnInit(): void;
}

This results in an error when importing this generated declaration file, because OnInit cannot be found.

Imports from libraries outside @types and typeRoots are inlined

Bug report

Imports from libraries outside of @types and typeRoots are always inlined, even when explicitly specified as external import.

Input code

foo.ts

import { Bar } from "bar";

export interface Foo extends Bar {}

externals/bar.d.ts

export interface Bar {}

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "bar": ["externals/bar"]
    }
  }
}

Expected output

import { Bar } from "bar";

export interface Foo extends Bar {}

Actual output

export interface Bar {}
export interface Foo extends Bar {
}

Additional context
CLI options:

./node_modules/.bin/dts-bundle-generator foo.ts --out-file bundle.d.ts --external-imports=bar

Building typings for a project that imports Three.JS fails

I'm trying to build an amalgamated and flattened typings file with Three.JS as a dependency. I have narrowed down the problem to this minimal example. I would be very thankful for your help with this, the goal is to have a typings file for my own code and let it rely on typings from NPM for dependencies like Three.JS. I would rather not want to inline all the typings.

app.ts:

import {Vector3} from "three";

export function test(): Vector3 {
  return new Vector3();
}

package.json:

{
  "name": "dts-bundle-generator-bugreport",
  "version": "1.0.0",
  "private": true,
  "scripts": {
    "build": "npx tsc",
    "typings": "npx dts-bundle-generator -o app.d.ts app.ts"
  },
  "dependencies": {
    "three": "^0.93.0"
  },
  "devDependencies": {
    "dts-bundle-generator": "^1.2.2",
    "typescript": "^2.9.1",
    "@types/three": "^0.92.3"
  }
}

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "declaration": true,
    "lib": ["es2015", "dom"]
  }
}

Run:

npm install
npm run typings

Output:

Library "three" will be added via reference directive
Library "webvr-api" will be added via reference directive
Writing generated file to app.d.ts...
Checking the generated file...
app.d.ts(4,33): error TS2304: Cannot find name 'Vector3'.
Error: Compiled with errors

app.d.ts looks like:

/// <reference types="three" />
/// <reference types="webvr-api" />

export declare function test(): Vector3;

Question / bug (?): Why is the library added via reference, the documentation states "By default all libraries will be imported (except inlined)"? And why does the check fail? I'm not too familiar with the reference syntax, but I doubt that it makes the type Vector3 available, so the check is probably right.

Next attempt: set --external-imports to a package name from node_modules to force the use of import:

-    "typings": "npx dts-bundle-generator -o app.d.ts app.ts"
+    "typings": "npx dts-bundle-generator -o app.d.ts --external-imports @types/three -- app.ts"

Exactly the same output as before. Next try:

-    "typings": "npx dts-bundle-generator -o app.d.ts app.ts"
+    "typings": "npx dts-bundle-generator -o app.d.ts --external-imports three -- app.ts"

Output:

Adding import with name "Vector3" for library "@types/three"
Library "webvr-api" will be added via reference directive
Writing generated file to app.d.ts...
Checking the generated file...
app.d.ts(3,25): error TS6137: Cannot import type declaration files. Consider importing 'three' instead of '@types/three'.
Error: Compiled with errors

app.d.ts:

/// <reference types="webvr-api" />

import { Vector3 } from '@types/three';

export declare function test(): Vector3;

Almost, it should indeed be from 'three' and not from '@types/three'.

Enum support

I'm trying to use enums that have been extracted into a dts bundle, but it doesn't work. I import the enum like this:

import {MyEnum} from "mybundle";
console.log(MyEnum.FIRST);

The TS file looks like this:

export enum MyEnum {
	FIRST = "FIRST"
}

The generated TSD like this:

declare enum MyEnum {
	FIRST = "FIRST"
}

It fails because the imported MyEnum is undefined. I kind of understand why it fails, because enums are just objects, and TSD is about declarations only. See also https://lukasbehal.com/2017-05-22-enums-in-declaration-files/, it states: "Do not define your enums in your TypeScript Declaration (*.d.ts) files, ever". So I wonder if dts-bundle-generator should be changed (or get an option) to generate one of the alternative solutions suggested in https://stackoverflow.com/q/38335668. For example, export type MyEnum = "FIRST"; or (preferably) another solution where the users of the dts file can use identifiers instead of strings.

I haven't read through all the possibilities so far but wanted to bring it to your attention. Maybe you've encountered the same problem already.

Symlinked node_modules directory confuses dts-bundle-generator

I have to admit, this is probably a quite uncommon use case, but still wanted to report it because maybe it can be fixed easily.

This is based on the same example as #37. Rename your node_modules directory and symlink it:

mv node_modules .node_modules_develop
ln -s .node_modules_develop node_modules

Then extract the typings. You will get a huge definitions file with a lot of inlined types. It seems like the symlink is confusing the logic that figures out how to deal with a dependency.

I've been using the symlink for a long time now as a technique to make it easy and fast to switch between the modules required for my develop and release branches. It hasn't caused any problems with NPM itself or other tools so far.

Sub-Paths in imports and renamed imports generate invalid output

Bug report
When trying to bundle the declaration files for a file with renamed imports and/or imports with sub-paths, the generated declaration file becomes invalid.

Steps to reproduce

  1. Create a new repo
  2. npm init
  3. npm i typescript dts-bundle-generator alcalzone-shared
  4. Create tsconfig.json:
{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "strict": true,
    "esModuleInterop": true
  }
}
  1. create a.ts:
import { Overwrite } from "alcalzone-shared/types";
import { Overwrite as Merge } from "alcalzone-shared/types";

export type Foo = Overwrite<{a: number}, {b: number}>;
export type Bar = Merge<{a: number}, {b: number}>;
  1. node_modules\.bin\dts-bundle-generator -o index.d.ts a.ts

Expected output

import { Overwrite, Overwrite as Merge } from 'alcalzone-shared/types';

export declare type Foo = Overwrite<{
	a: number;
}, {
	b: number;
}>;
export declare type Bar = Merge<{
	a: number;
}, {
	b: number;
}>;

Actual output

import { Overwrite } from 'alcalzone-shared';

export declare type Foo = Overwrite<{
	a: number;
}, {
	b: number;
}>;
export declare type Bar = Merge<{
	a: number;
}, {
	b: number;
}>;

The renamed import for Merge is missing and the import path is wrong (missing /types).

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.