GithubHelp home page GithubHelp logo

vscode-gengetset's Introduction

Optimize / Auto Imports, Generate Getters / Setters and Constructors

Simply click on the Light Bulb to add the missing import line

Import

Optimize all your import lines: add missing imports and remove unused

Optimize

Easily create a contructor based on privates.

Constructor

Quickly generate getters and setters for your class.

GetSet

Keep an eye on the eye-icon for quick info about the exports found.

Status

Changelog

v0.5.0

  • Merged contributions: Get/Setter for All at once including comments and a whole list of housekeeping in the code :)

v0.4.2

  • Light Bulb feature added for easy importing
  • Some backend optimizations

v0.4.1

  • Fixed a bunch of bugs including one which stopped optimize imports from running
  • Added ignoredImportList, ignoredDictionaryList, ignoredLibraryPaths and ignoredNodeLibraries to the settings to customize

v0.4.0

  • Fixes for Angular 2 and Ionic 2 (RC) support
  • new npm @types now supported by default
  • ignores hidden directories (like .history and .tmp)
  • Indexing on save disabled by default (setting: scanOnSave)
  • Manual rescanning can be triggered from the context menu

v0.3.4 - v0.3.0

  • Windows users can now finally use the optimize import function
  • added the setting spacedImportLine
  • new name and icon ;-)
  • resolved some issues eg. reported on github
  • fixed @angular related import optimizations
  • fixed command palette issues
  • introducing the statusbar Eye-Icon showing the status of the extension (searching for and exports found)
  • solution for searching through and adding one of the available exports: Add Import
  • now with support for TypeScript based modules (ex. Ionic 2 and Angular 2)
  • import paths / are now completely OS independent
  • intellisense suggestions have been removed (searching for other solution)
  • complete optimized code rewrite of the extension

Install

Get VSCode and grab the extension from the VSCode Extension Market

Settings

  1. genGetSet.scoped (default: enabled) Only show private variables from current class based on cursor position.
  2. genGetSet.filter (default: enabled) Only show private variables which do not have a getter/setter method.
  3. genGetSet.importTypings (default: enabled) Create import lines based on definition files from /typings/.
  4. genGetSet.importNode (default: enabled) Create import lines based on definition files from /node_modules/.
  5. genGetSet.classic (default: disabled) use 'getValue' and 'setValue' instead of 'get value' and 'set value'.
  6. genGetSet.pathStringDelimiter (default: ') sets which quote use to generate import path.
  7. genGetSet.spacedImportLine (default: false) Adds spaces between the beginning and ending of the brackets in an import line.
  8. genGetSet.scanOnSave (default: false) Scan the workspace for imports when a document is saved.
  9. genGetSet.ignoredImportList (check settings) Imports like 'Promise' have many libraries but seldom need an import line.
  10. genGetSet.ignoredDictionaryList (check settings) Dictionaries like 'vscode' and 'tsconfig' which do not need an import line.
  11. genGetSet.ignoredLibraryPaths (check settings) Paths like 'dist' and 'src' which can be omitted in the import line.
  12. genGetSet.ignoredNodeLibraries (check settings) A list of node module libraries like 'chrome' and 'node' which can be ignored as an import line.

Usage

  1. Just place your cursor within a TypeScript class definition in the text editor window
  2. Open the command palette ctrl+shift+P / cmd+shift+P.
  3. Search for 'Import', 'Generate Getter', 'Setter' or 'Constructor'

or

  1. Just place your cursor within a TypeScript class definition in the text editor window
  2. Press alt+shift+G for a quick selection pop-up
  3. Select the preferred function from the pop-up menu

or

  1. Click on the little Eye-Icon in your statusbar
  2. Select the preferred function from the pop-up menu

The generated method will be placed at the cursors position.

Best Practice

Best practice is naming your variables with a _ for private use. The extension will remove the _ when generating the methods.

This: private _name: string;

Will render in:

public get name(): string {
    return this._name;
}

public set name(value: string) {
    this._name = value;
}

If there is no _ the method will start with a $.

This: private name: string;

Will render in:

public get $name(): string {
    return this.name;
}

public set $name(value: string) {
    this.name = value;
}

Known Problems

Always type your variables. Even when your variable is being initialized, else the extension cannot read the typing. Always do this: private _name: boolean = false;

This is a TypeScript only extension.

Contributors

Special thanks to the github users: AngelMunoz, edotassi, Aranir, buehler, EduwHS, Anexon, Tchoupinax, dball-adashi

Enjoy!

vscode-gengetset's People

Contributors

angelmunoz avatar aranir avatar buehler avatar cybertim avatar edotassi avatar tchoupinax 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

Watchers

 avatar

vscode-gengetset's Issues

@angular Router 3.0+ import line includes /src

the import line

import { Router, ActivatedRoute } from '@angular/router';

is completed as

import { Router, ActivatedRoute } from '@angular/router/src';

The /src should be ignored else compilation will fail.

0.3.0: Error "No handler found [for] genGetSet.import"

I just installed the latest version and the import command doesn't fire at all for me. I just get an error suggesting that "An extension might be missing an activation event."

The getter/setter generation does work. I'm on Windows with VS Code 1.1.1.

Add import command shows "There are no entries to pick from" if typings folder is exclude from the Eplorer #3

Thanks for greate plugins. I have a problem with files.eclude setting, though.

Step to reproduce

  1. In settings.json, eclude the typings folder:

    {
      "files.exclude": {
        "typings": true
      }
    }
  2. Reload VS Code to make the setting applied.

  3. Try TypeScript: Add import command. It would ask to wait for build export
    cache. Fine.

  4. After some secs, try the command again. Now it's say There are no entries to pick from.

Also, remove the setting and reload vscode make the addon works again.

Tested on

  • Platform: Ubuntu 16.04
  • VS Code: 1.4.0
  • VS Code Insiders: 1.5.0
Version 1.5.0-insider
Commit 92d3324e3d05a6d2b765c08651d89e9ec1d19f4c
Date 2016-08-29T06:12:13.472Z
Shell 0.37.6
Renderer 49.0.2623.75
Node 5.10.0

Member functions generate import lines

Members

Declaration:

export let createItem = (): () => Promise<CollectionItem> () => {
  return (item: Item) => Promise.resolve(undefined);
};

Usage:

interface X {
  createItem(): Object;
}

Expected result: no import is added
Observed result: import for createItem is added.

Add Imports command is not showing

On 0.3.1, "Add imports" command is not showing.

"Generate constructor" command is working (inserts tabs instead of spaces, but...;), so extension is properly installed.

when i open the typescript file

Cannot read property 'length' of undefined: TypeError: Cannot read property 'length' of undefined
at DefinitionProvider.containsItem (/Users/selcuk/.vscode/extensions/DSKWRK.vscode-generate-getter-setter-0.4.2/out/src/provider.js:52:48)
at /Users/selcuk/.vscode/extensions/DSKWRK.vscode-generate-getter-setter-0.4.2/out/src/bulb.js:10:56
at CompleteActionProvider.provideCodeActions (/Users/selcuk/.vscode/extensions/DSKWRK.vscode-generate-getter-setter-0.4.2/out/src/bulb.js:7:16)
at /Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:23:353679
at /Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:23:57373
at new n.Class.derive._oncancel (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:23:46346)
at Object.d [as asWinJsPromise] (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:23:57336)
at e.provideCodeActions (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:23:353633)
at /Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:23:363513
at t._withAdapter (/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/node/extensionHostProcess.js:23:360077)

imports should ignore `path:`

Improve regex to ignore the object creation variable names.
ex .Express/Hapi routes will always import the 'path' lib from node because the init the 'path:' variable.

Does not seem to work with @types definitions

To reproduce use the d3v4 definitely typed definitions.

npm install @types/d3

example typescript class where it does not work:

import * as d3Selection from 'd3-selection';

class Test {
  private _svgEl: d3Selection.Selection<SVGSVGElement, any, HTMLElement, any>;

}

Feature request: Implement interface/class

Feature request: Implement interface or class

The plug-in is very nice.
It would be great if there is auto interface (or class) implementation feature, similar to Visual Studio.
It should be used on classes which implement interfaces or other classes, and when used, it should generate default method implementations. The default behavior for the methods can be similar to Visual Studio: throw new Error('Not Implemented');.

Additional features

  • Detect which methods are already defined in the class, and not add them again.
  • When VS Code has more advanced cold-folding functionality, it would be nice to have these methods wrapped in // #region InterfaceName - // #endregion block (or whatever code-folding is supported).
  • Explicitly set access modifiers, and persist them for abstract methods.
  • When extending abstract class, the user should be able to choose whether the abstract methods should be kept abstract (with no body) or not (with the default implementation).
  • The user should be able to choose a single interface/class to be implemented.

Example:

When we have this code...

abstract class AbstractClass {
    public regularMethod(): string { return 'test'; }
    protected abstract abstractMethod(a: number): string;
}
// regardless abstract or not
class BaseClass {
    public classMethod(): number { return 1; }
}
abstract class TheInterface {
    abstract interfaceMethodA(): void;
    abstract interfaceMethodB(): void;
}
export class TheClass extends AbstractClass implements BaseClass, TheInterface {
    constructor() { super(); }
}

...and we use the feature, the final code for TheClass should be something like:

export class TheClass extends AbstractClass implements BaseClass, TheInterface {
    constructor() { super(); }

    // #region BaseClass
    public classMethod(): number {
        throw new Error('Not Implemented');
    }
    // #endregion

    // #region AbstractClass
    protected abstractMethod(a: number): string {
        throw new Error('Not Implemented');
    }
    // or (class must be set as abstract)
    protected abstract abstractMethod(a: number): string;
    // #endregion

    // #region TheInterface
    public interfaceMethodA(): void {
        throw new Error('Not Implemented');
    }
    public interfaceMethodB(): void {
        throw new Error('Not Implemented');
    }
    // #endregion
}

Regards,
Kristiyan

Problem autoimplementing Interface

In this case, the autocompletion does it wrong

class InformationElement extends Element implements IInformationElement{}
Where IInformationElement and Element extends from IElement
Note that IInformationElement is an interface.
The autocompletion adds the code contract of the IElement and the IInformationElement. And should only add the code contract of IInformationElement because Element implements already IElement and because inheritance InformationElement has the implementation of IElement

Import are removed although they are used

Hey @cybertim

I'm really happy with your extension, it works (more or less) like it shoud ๐Ÿ˜‰

Although, I have one small issue which makes it unusable :-(

I use giuseppe for my api which makes extensive use of typescript decorators. Now I've got some decorators that use imports, and they are removed from the imports list.
example:

import {/*...*/, isNumber} from 'giuseppe';

@Controller()
class Ctrl {
    @Get()
    public foobar(@Query('foobar', {validator: isNumber()}) queryParam: any): any{
        /*...*/
    }
} 

In the example above, isNumber is clearly use, but when I add another import or use "optimize imports" the reference to isNumber is removed.

Cheers and thanks for your work!
Chris

import from node-modules doesn't work properly

two issues:
1)if using npm-style typings supported by typescript 2, if you try to autocomplete an import statement the resulting line will be something like import {x} from "@types/whatever" instead of import {x} from "whatever"

2)if using normal typings style, according to this https://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html you can have two styles: either put the main declaration file in your root folder, or put a pointer to it under "typings" in your package.json config file. The second one works but it generates the wrong line:
in case of your declaration file being in node_modules/whatever/dist/src, instead of something like import {x} from "whatever" it will generate import {x} from "whatever/dist/src". The compiler will still be happy but obviously this is not good.

Optimize Import leads to errors

I very often get the following error while trying to handle Optimize Import.

No handler found for the command: 'genGetSet.import'. An extension might be missing an activation event.

multiline import-lines are ignored

Structure like:

import {
 stuff, more stuff
} from 'something';

Is ignored when importing.
Workaround is just removing multiline imports and import again to get a single line.

"Organize imports" auto import curent module aswell

When I try to organise imports for a module, the plugin adds current module as an import.

Here is the version info

Version 1.8.0-insider
Commit 2bd85b81138984acd08983df4cb2fbdc1c41aa4d
Date 2016-11-30T07:19:03.134Z
Shell 1.4.6
Renderer 53.0.2785.143
Node 6.5.0

TypeScript Hero

System information

  • OS: Windows 10 AU
  • TypeScript Hero version: 0.10.1
  • VSCode version: 1.7.2

Feature

There are several features in TypeScript Hero that are useful, but also other that collides with this. Maybe you could join an develop just one extension? Idk.

Reason

The reason to join would be for us to have one extension that would really help us as developers.

Cheers!

Should respect source settings in tsconfig

Hi,

I would love to use this great tool but have a serious issue. "organize imports" imports hundreds of duplicate entries. Reason is that I am using a history plugin that makes copies of a file after each modification. Apparently, the toolbox does not respect the excludes that I made in .tsconfig and instead searches all my project folder for possible exports.

In any case, I think the sources settings in tsconfig must be obeyed, because I may intentionally keep some ts files somewhere in the project structure and do not want them to be active.

Add import creates duplicates

Hey, great plugin.

When adding imports, I am using path mapping and I get duplicated imports. If a Type is imported it should not create duplicates.

Command line installation does not work

code --install-extension DSKWRK.vscode-generate-getter-setter

Error:

Found 'DSKWRK.vscode-generate-getter-setter' in the marketplace.
Installing...
(node:66947) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: this._state.then is not a function
(node:66947) DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Should prefix commands with 'TypeScript:'

Commands don't include "typescript" text, so e.g. "Generate Getter" appears in command palette as is - no idea what programming language it applies to.

E.g. Go plugin has "Go: Add Import", so for symmetry typescript plugin should add "TypesScript: Add Import"

Import is not working

Code before using plugin command

import { Component, Input, Renderer, ViewChild } from '@angular/core';

import { SimpleService } from '../services/simple.service'

@component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements AfterViewInit{
showed:boolean = true;
@ViewChild('input') input;

constructor(private renderer:Renderer) {}

ngAfterViewInit() {
console.log(this.input);

  this.renderer.setElementAttribute(
      this.input.nativeElement,
      'placeholder',
      'true'
  );

}

}

`

Code after Add Import 'AfterViewInit'

`
import {console} from '@types/node';
import {Component, AfterViewInit, ViewChild} from '@angular/core';

import { SimpleService } from '../services/simple.service'

@component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements AfterViewInit{
showed:boolean = true;
@ViewChild('input') input;

constructor(private renderer:Renderer) {}

ngAfterViewInit() {
console.log(this.input);

  this.renderer.setElementAttribute(
      this.input.nativeElement,
      'placeholder',
      'true'
  );

}

}

`

As you see, 'Input, Renderer' was deleted, that we don't need.

wildcard imports are ignored

When there is already a wildcard import the parser ignores it and makes another line of separate imports for each export.

Typescript Toolbox Light Bulb does not appear

I have installed Typescript Toolbox 0.4.2 on vscode version 1.17.1 (Shell 1.7.7, Node 7.9.0) on linux host. Toolbox is installed without errors and running without any warnings.
But the Light bulb never appears!
Any ideas what's going wrong. How can I start extension functions (like creating a constructor or an getter, ...) without the bulb?

import doesn't resolve to correct directory

The import statements always refer to the current directory:

import {Test} from './Test';

even if the file is located in a different directory.

Is there a way for the autoimport to work with the correct relative path?

import from node_modules faulty

Importing from index.d.ts within the node_modules (ex. angular2 and ionic2) is faulty.
They are not wildcard imports but normal bracket based imports from a wildecard entry.
ex. import * as vscode from 'vscode';is supported now from node_modules but the entry for ex. angular2 should be:
import {Http} from '@angular/http';

Getter and Setters specify indent setting

I am using tslint with the option:
"indent": [
true,
"spaces"
]

Generating getter/setters defaults to tabs, which then forces me to have to change the tabs to spaces.
image

Could we have a setting to specify the indentation?

Add new Import statements below the file header

The new import statements are added at the beginning of the file. If there is a file header comment, this is before this header. It would be great if the new import statements would be located below the existing import statements.

Wrong slashes on windows and importing 'enum'

I tried your promising import assist, the result is not working as expected. I had the following import statements before running Import Assistant and I wanted to import DataAnalysis and TaskExecutionContext.

import {Content, ContentType} from './content';
import {DataType} from '../model/data-types';
import {Lookup} from '../common/utilities';
import {ItemsLoader, PageResult, ScreenAction, Item} from './interfaces';
import {FilterConfig} from './reference-field-config';
import {Collection} from '../model/collection';
import {Blueprint} from './blueprint';
import {GenericModel} from '../model/model';

The following was the result:

import {GenericModel} from '..\model\model';
import {dataType} from '..\model\data-types';
import {enum} from '..\composers\control-composer';
import {enum, id} from '..\control-library\utilities';
import {type} from '..\implementations\operations\unary\subattributes';
import {Content, ContentType} from './content';
import {DataType} from '../model/data-types';
import {Lookup} from '../common/utilities';
import {ItemsLoader, PageResult, ScreenAction, Item, enum, DataAnalysis, TaskExecutionContext} from './interfaces';
import {FilterConfig} from './reference-field-config';
import {Collection} from '../model/collection';
import {Blueprint} from './blueprint';
import {GenericModel} from '../model/model';

Two errors stand out immediately: the use of backslashes (I am running on a windows platform) and the import of enum from various places.

I hope you can fix this.

Add Imports does no action

Hey there

When I use your plugin and I wanna optimize imports or add import, the plugin does no action at all. The constructor generator does work, but add import only shows the indexed exports. I can search through my stuff, but when I hit enter on my desired class, it just disappears.

Maybe this could be duplicated / related to #19

Cheers

Not working without ';'

Hello,

Thanks for this amazing plug in, but it looks like it doesn't work if we declare private attributes without semicolons

private _id: string
private _date: string
private _numbers: number[]

Honor user's formatting settings

If the user has this line in his/her settings.json:

typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets = true

then the created/optimized imports should contain spaces like:

import { Thing } from './path';

Notice the spaces around "Thing".

Provide IntelliSense Support

It would be nice, if this extension would show the available imports as i type via IntelliSense.
If an unimported module gets selected an automatic import could be created.

Modify the getter setter to not use property setter

First thanks for the extension, forked it and made the fix in my own repo here

user414@34e3c75

All of this is subjective but I tend to agree with basarat here

https://basarat.gitbooks.io/typescript/content/docs/tips/propertySetters.html

for not using property setter but functions. As well I tend to agree with

http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign

about reserving dollar sign variable in a jquery context. So I slightly modified your extension to generate plain set/get method with the standard variable name, thanks again for the extension.

Add Import shows "Sorry, please wait a..."

When I run the command "Add Import", I get a warning saying: "Sorry, please wait a few seconds longer until the export cache has been build.". This won't go away even when I wait several minutes.

This error occurs when I am trying to run the command in an angular cli application.
Works fine if a have an empty project with only a couple of ts-files.

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.