Visual Studio generates wrong javascript from typescript when saving ts file (works when building project) - visual-studio

I have strange problem with typescript. I have my enums in separate .ts file and when I save the other file that is using enums, visual studio compiles incorrect javascript, but when I build the project, javascript is generated correctly.
Does anyone know how to get saving working (as it's quite tedious to build project everytime I change .ts file while debugging)?
Example:
MyEnums.ts
module MyEnums {
export const enum MyEnum {
val1 = 1,
val2 = 2,
val3 = 3
}
}
App.ts
module App {
console.log(MyEnums.MyEnum.val1);
}
Output (incorrect) when saving App.ts
var App;
(function (App) {
console.log(MyEnums.MyEnum.val1);
})(App || (App = {}));
Output (correct) when building project
var App;
(function (App) {
console.log(1 /* val1 */);
})(App || (App = {}));
I'm using Typescript 1.4 and Visual Studio 2013 Update 4

It's a bug in the TypeScript language service. See this thread where there's a link to an updated typescriptservices.js you can patch in to fix the problem.

Related

How to show Analyzer errors/warnings during msbuild in VS Dev Cmd & using MSBuildWorkspace

I'll explain the situation with an example.
Suppose I have created a Roslyn Analyzer which throws Error when Class name is TestClass. Analyzer code is as below:
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Method, SyntaxKind.ClassDeclaration);
}
private static void Method(SyntaxNodeAnalysisContext context)
{
var node = (ClassDeclarationSyntax)context.Node;
var name = node.TryGetInferredMemberName();
if(name == "TestClass")
{
context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
}
}
So i install the Analyzer nupkg in some ConsoleApp project. Console project has following code in Program.cs file
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
class TestClass
{
static void test()
{
Console.WriteLine("TestClass");
}
}
}
Now if i build the ConsoleApp project in Visual Studio then i get Error as "TestClass name not to be used" which is fine.
But when i try to build the same project using msbuild command in Developer Command Prompt for VS 2017 i don't see any error from Analyzer. I want that all the errors shown in Error list in VS should be shown in Dev Cmd.
My end goal is to create a stand-alone code analysis tool project and then use MSBuildWorkspace to compile ConsoleApp project and get the analyzer errors/warnings. Part of code is as below:
var filePath = #"C:\Users\user\repos\ConsoleApp\ConsoleApp.sln";
var msbws = MSBuildWorkspace.Create();
var soln = await msbws.OpenSolutionAsync(filePath);
var errors = new List<Diagnostic>();
foreach (var proj in soln.Projects)
{
var name = proj.Name;
var compilation = await proj.GetCompilationAsync();
errors.AddRange(compilation.GetDiagnostics().Where(n => n.Severity == DiagnosticSeverity.Error).ToList());
}
var count = errors.Count();
Above code does not show errors/warnings from analyzer.
How can i achieve this?
Thanks in Advance.
To show analyzer errors/warnings during msbuild in VS Dev Cmd, you just have to pass rebuild switch for example
msbuild Tempsolution.sln /t:rebuild
And for MSBuidlWorkspace, this code worked for me. We have to manually specify the analyzer to use by using compilation.WithAnalyzer(ImmutableArray<DiagnosticAnalyzer>);.
MSBuildLocator.RegisterDefaults();
var filePath = #"C:\Users\user\repos\ConsoleApp\ConsoleApp.sln";
var msbws = MSBuildWorkspace.Create();
var soln = await msbws.OpenSolutionAsync(filePath);
var errors = new List<Diagnostic>();
foreach (var proj in soln.Projects)
{
var analyzer = proj.AnalyzerReferences.Where(alz => alz.Display.ToLower() == "Your analyzer name").FirstOrDefault();
var compilation = await proj.GetCompilationAsync();
var compWithAnalyzer = compilation.WithAnalyzers(analyzer.GetAnalyzersForAllLanguages());
var res = compWithAnalyzer.GetAllDiagnosticsAsync().Result;
errors.AddRange(res.Where(r => r.Severity == DiagnosticSeverity.Error).ToList());
}
var count = errors.Count();
How to show Analyzer errors/warnings during msbuild in VS Dev Cmd &
using MSBuildWorkspace
Actually, these warnings are from Code analysis mechanism rather than MSBuild warnings(like MSBxxx). And I think the TestClass name not to be used is just a warning(yellow mark) not an error.
In VS IDE, its environment integrates the MSBuild tool(Developer Command Prompt for VS) and Code Analyzer. Because of this, you can get the warnings in VS IDE.
However, when you use Developer Command Prompt, which is essentially a separate compilation tool for MSBuild, it doesnot have an integrated code analyzer, so you don't have this type of warning except for MSBuild warnings and errors(MSBxxx). This is also the limitation of the tool. Warning by itself does not affect the entire program.
Test
You can test it by input this in an empty console project: int a=1;(It is a code analyzer warning) and I am sure that the warning can be showed in output window in VS IDE and will not be listed in Developer Command Prompt for VS.
Suggestion
As a suggestion, you can try to treat these warnings as errors and Code Analyzer passes these warnings to the msbuild and specifies them as errors so that you can get the error in DEV.
Add these in your xxx.csproj file:
<PropertyGroup>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
Although this approach breaks the build process, it is reliable and practical. And this method is very commonly used, generally used in the final production stage of the project, to exclude all errors and warnings for large projects, so as to prevent subsequent errors that may occur and be foolproof.
Then, you can use your code to build the project.

How to Use nativescript-autocomplete plugin with nativescript angular?

I am not able to make plugin work with angular project template .GitHub shows only code in native and XML .Sample plugin code works but unfortunately no angular support or help given. I am not able show on angular template.
relevant code i am using
detail.component.ts
registerElement("AutoComplete", () => require("nativescript-autocomplete").AutoComplete);
public list :Array = ['1','2','3','4','567'] ;
public itemTapped(args){
console.log("tapped");
}
detail.component.html
<AutoComplete items=""{{list}}"" itemTap="itemTapped($event)"> </AutoComplete>
i am getting exception on console while page loads and autocompletion doesnt work
this.items.forEach is not a function inside plugin code .that line is with definition of AutoComplete.prototype.itemsUpdate inside autocomplete.android.js plugin source
Debugging into plugin source it breaks at initialization time :
'AutoComplete.prototype.itemsUpdate = function (items) {
var arr = Array.create(java.lang.String, this.items.length);
this.items.forEach(function (item, index) {
arr[index] = item;
});
var ad = new android.widget.ArrayAdapter(app.android.context, android.R.layout.simple_list_item_1, arr);
this._android.setAdapter(ad);
};'
In detail.component.html
<AutoComplete [items]="list" (itemTap)="itemTapped($event)"> </AutoComplete>
in details.component.ts add
public list:any= ['1','2','3','4','567'] ;
itemTapped(ev){
//console.log(ev); your code
}
Issue in npm version. Clone the repository.
Replace all the files in node_modules/nativescript-autocomplete ,expect screenshot, demo folders and git related files. And try the solution

How do you use a Typescript Unit Test to test Typescript in Visual Studio?

I'm trying to write a unit test in Typescript to test a Typescript class, but when the test is run, it doesn't know anything about the class.
I'm using Typescript (1.4) with Node Tools for Visual Studio (2013) and the test helpfully appears in Test Explorer. When run it fails with "Reference Error: ClassC not defined."
The class I'm testing:
class ClassC {
functionF() {
return 42;
}
}
Generated Javascript:
var ClassC = (function () {
function ClassC() {
}
ClassC.prototype.functionF = function () {
return 42;
};
return ClassC;
})();
//# sourceMappingURL=ClassC.js.map
The test (created from template Add -> new Item... -> TypeScript UnitTest file):
/// <reference path="ClassC.ts" />
import assert = require('assert');
export function classCTest() {
var foo: ClassC = new ClassC();
var result: number = foo.functionF();
assert.equal(result, 42);
}
Generated Javascript:
var assert = require('assert');
function classCTest() {
var foo = new ClassC();
var result = foo.functionF();
assert.equal(result, 42);
}
exports.classCTest = classCTest;
//# sourceMappingURL=ClassC_tests.js.map
When looking at the generated Javascript for the test it becomes obvious why the error occurs. It does not contain the necessary definition for ClassC. I thought including the reference path would help, but it obviously didn't.
How do I get the unit test to know about the class?
I thought including the reference path would help, but it obviously didn't.
export class ClassC and then use an import statement instead of a reference comment. Also compile with the compiler flag --module commonjs.
More : https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1 and http://basarat.gitbooks.io/typescript/content/docs/project/external-modules.html

How to use SASS in Dart editor

Anyone have a canned solution for integrating SASS or another CSS preprocessor into the Dart editor? Seems to require a custom build.dart, which I would rather copy than code. Thanks.
I stumbled upon this a few days ago
Sass integration for pub
Here is a build.dart file with basic support for SASS:
import 'dart:io';
void main(List<String> args) {
for (String arg in args) {
if (arg.startsWith('--changed=')) {
String file = arg.substring('--changed='.length);
if (file.endsWith('.scss')) {
var result = Process.runSync('sass',
[ '--line-numbers', file,
file.substring(0, file.length - '.scss'.length) + '.css']);
if (result.exitCode != 0) {
// report error (SASS seems to only report first error)
// split error lines
var lines = result.stderr.split('\n');
// escape quotes in error message on first line
var error = lines[0].replaceAll('"', r'\"');
// extract line number from second line
var numMatch = new RegExp(r'\d+').firstMatch(lines[1]);
var lineNum = numMatch == null ? 1 : num.parse(numMatch.group(0));
// Report error via JSON
print('[{"method":"error","params":{"file":"$file","line":$lineNum,"message":"$error"}}]');
}
}
}
}
}
During development (with Dart Editor or another editor...), just use sass the way it's meant to be used, in your directory project :
sass -w .
Put the CSS generated files in the ignore list of your source code management system (aka .gitignore for git).
And for dart2js compilation, use the sass pub package : http://pub.dartlang.org/packages/sass

How to encapsulate User Setting (Options Page) in Visual Studio 2010 AddIn

I'm currently developping a Visual Studio Extension and I have a question about Options Page. Options Page allows user to save setting about your Extension. Visual Studio handle a lot of work for us.
I created the Options Page.
public class VisualStudioParameter : DialogPage
{
private string _tfsServerUrl = DefaultParameter.TfsServerUrl;
[Category("TFS Parameters")]
[DisplayName(#"Server Name")]
[Description("The URL of your TFS Server")]
public string TfsServerUrl
{
get { return _tfsServerUrl; }
set { _tfsServerUrl = value; }
}
}
First, I created a method in the Visual Studio Package to acces to the Options Page.
Okay so now, from my Package, I can easily acces to the settings.
partial class SpecFlowTfsLinkerExtensionPackage : Package : IParameter
{
....
....
public string GetTfsServerUrl()
{
return ((VisualStudioParameter) GetDialogPage(typeof (VisualStudioParameter))).TfsServerUrl;
}
}
Now, I want to be able, in another library (Another project, included in the VSIX Package), to get easily these values. I don't want to reference the Visual Studio AddIn Package in my library.
I also have Unit Test so I'm going to create an Interface. During Unit Test, I going to Mock the object.
public interface IParameter
{
string GetTfsServerUrl();
}
Do you have any idea about how I can develop a clean solution to get these parameters from another assembly ?
Do you think the better solution is to inject the AddIn dependency in my library ?
If you already developed a Visual Studio Extension, How did you encapsulated the user setting from your core assembly ?
Thanks a lot.
You can try something like that:
// Access DTE infrastructure
EnvDTE.DTE dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
// Access options page
var props = dte.get_Properties(#"Your Extension", "General");
var pathProperty = props.Item("TfsServerUrl");
path = pathProperty.Value as string;

Resources