WebEssentials tslint custom rules - visual-studio

I have a tslint.json file in my solution directory and I'm trying to create a custom rule following the guidelines on https://www.npmjs.com/package/tslint
I have created a "nonImportsRule.ts", have copied the code from the link and have added "no-imports": true to my tslint.json file however the rule is not being picked up.
The guide says that a rulesDirectory needs to be specified, but I have no idea where this should be configured?
Also - is it possible to setup Web Essentials to break the build if tslint rules are violated?

I had a same kind of a problem. I wanted to use the TSLint extensions, tslint-microsoft-contrib and codelyzer, together with Web Analyzer. This did not work. The first step to figure out why was to make an adaptation in server.js which can be found in C:\Users\[User]\AppData\Local\Temp\WebAnalyzer1.7.75. I changed the TSLint function into:
tslint: function (configFile, files) {
// Try catch tslint errors
try {
var tslint = require("tslint");
var options = {
formatter: "json",
configuration: JSON.parse(fs.readFileSync(configFile, "utf8").trim())
};
var results = [];
for (var i = 0; i < files.length; i++) {
var file = files[i];
var ll = new tslint(file, fs.readFileSync(file, "utf8"), options);
results = results.concat(JSON.parse(ll.lint().output));
}
} catch(error) {
// Return tslint error to visual studio so we can get some ideas for counter measures.
var result = JSON.parse('[{"endPosition": {"character": 0,"line": 0,"position": 0},"failure": "INSTALL ERROR","name": "/","ruleName": "INSTALL ERROR","startPosition": {"character": 0,"line": 0,"position": 0}}]');
result[0].failure = error.message;
return result;
}
return results;
},
The alternation resulted in error feedback in the visual studio error list when I run the Web Analyzer. Do not forget to force a new instance of node.exe with the task manager after you have applied the alternation. The feedback leaded, for my particular situation, to the following installation of npm packages in the following directories:
Packages:
"codelyzer": "0.0.12"
"tslint": "^3.7.3"
"tslint-microsoft-contrib": "^2.0.2"
"typescript": "^1.8.9"
Directories:
C:\Users\[User]\AppData\Local\Temp\WebAnalyzer1.7.75
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
After this, Web Analyzer was able to use the same tslint rules as my grunt task. Hopefully a newer version of Web Analyzer will solve my problems more elegantly.

Okay, i'm not using Web Essentials extension but Web Analyzer : https://visualstudiogallery.msdn.microsoft.com/6edc26d4-47d8-4987-82ee-7c820d79be1d
So i won't be able to answer on this question 100%, but i want to summarize here my experience with custom tslint rules. First of all, what is not completely clear from documentation is that the whole thing depends on node.js.
So first of all you need to install node js. This will give you npm command to your command line.
After install with npm tslint and typescript. https://github.com/palantir/tslint here are examples. These will create files in : "c:\Users[Username]\AppData\Roaming\npm\node_modules"
Go into "c:\Users[Username]\AppData\Roaming\npm\node_modules\tslint\lib\rules\". Create here noImportRule.ts. Copy the following content:
import * as ts from "typescript";
import * as Lint from "../lint";
export class Rule extends Lint.Rules.AbstractRule {
public static FAILURE_STRING = "import statement forbidden EDE";
public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithWalker(new NoImportsWalker(sourceFile, this.getOptions()));
}
}
// The walker takes care of all the work.
class NoImportsWalker extends Lint.RuleWalker {
public visitImportDeclaration(node: ts.ImportDeclaration) {
// create a failure at the current position
this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
// call the base version of this visitor to actually parse this node
super.visitImportDeclaration(node);
}
}
Note that in the example import lint is not given with relative path that won't work with this approach.
4. Fire the command : "tsc -m commonjs --noImplicitAny .\noImportsRule.ts". This will compile your custom rule's ts. You will get bunch of compilation errors, such as: ../enableDisableRules.d.ts(1,21): error TS2307: Cannot find module 'typescript'. That's a good question why are these thrown, but forget about them, js file will be generated anyway.
5. Put "no-imports": true to your tslint.json(for now this should be custom one). With this command from command line:
tslint -c 'sample.tslint.json' test.ts
you will get:
test.ts[1, 1]: import statement forbidden. So you made the custom rule working!!! :)
That's all for working from command line. In addition I made custom rules working with WebAnalyzer, at least temporary.
I needed to copy my custom rule's files here:
c:\Users[Username]\AppData\Local\Temp\WebAnalyzer1.6.65\node_modules\tslint\lib\rules\ and of course configure WebAnalyzer tslint.json to include custom rules.
I have no idea how Web Essentials extension makes this whole thing working with tslint, but i guess some way similar :). Somewhere there should be a folder (node_modules\tslint\lib\rules) with rules what tslint uses. There you need to copy your custom ones.
Of course the most elegant solution would be to modify Web Essentials extension itself and make the tslint's custom rules directory configurable from visual studio. (so my solution is just a workaround)
Here is my custom rule example in the visual studio warning's list:

Related

How to include SCSS Glob in a Gatsby project?

I am currently working on setting up a boilerplate that uses Gatsby. Everything so far has been very simple and easy to use, but I can't seem to fix one problem, which is getting SCSS glob hooked up with my global SCSS styling.
I currently have localized SCSS styling for each component. However, I also have a styles directory for my global styles(variables, typography...ect). This is also using SCSS and is working great. Now the last thing I want to do is get SCSS glob working so I can do imports like /**/*.scss within my global styles.
Currently, I am using the gatsby-plugin-sass and have included globImporter as an option within my gatsby-config.js file. However, it does not seem to do it for me.
From what I read node-sass-glob-importer should be what I need but no luck so far.
My configuration looks like the following
{
resolve: `gatsby-plugin-sass`,
options: {
importer: globImporter(),
cssLoaderOptions: {
camelCase: false,
},
},
},
I then try to do a global import in my scss like so #import "./**/*.scss"; but I get the following error:
An #import loop has been found:
has anyone set up scss glob on gatsby or see anything wrong with my configurations.
Thanks
If you're still having this issue (or in case anyone else is), here's what worked for me:
options: {
importer: function(url, prev, done) {
// url is the path in import as is, which LibSass encountered.
// prev is the previously resolved path.
// done is an optional callback, either consume it or return value synchronously.
// this.options contains this options hash, this.callback contains the node-style callback
var result = globImporter();
return {file: result.path, contents: result.data};
}
},
It was inspired by the example code on in the node-sass repo.
Make sure to also include var globImporter = require('node-sass-glob-importer') at the top of your file.

'Gulpfile.js - failed to load See output' but output does not show any error information

I am trying to use gulp to copy some JS/CSS from node_modules to wwwroot in an ASP.Net core app.
I have what I thought was a fairly simple gulpfile.js
var gulp = require('gulp');
gulp.task('copy-files', function () {
var assets = {
js: [
'./node_modules/bootstrap/dist/js/bootstrap.js'
],
css: [
'./node_modules/bootstrap/dist/css/bootstrap.css'
]
};
_(assets).forEach(function (assets, type) {
gulp.src(assets).pipe(gulp.dest('./wwwroot/' + type));
});
});
However, when I look at the VS Task Runner, it just shows an error:
But the output window is empty:
How can I get more information about the error?
This answer here worked for me.
Moved up the $(PATH) location above everything. As I did not have (DevEnvDir)|Extensions\Microsoft\Web Tools\External location as mentioned in the answer.
For VS 2015
Tools > Options > Projects and Solutions > External Web Tools
For VS 2017
Tools > Options > Projects and Solutions > Web Package Management > External Web Tools
The problem is not related to path, but actually there must be some problem with gulp file itself either syntax error or some package is missing which unfortunately visual studio does not show that specific error but generic error what you see in task runner "failed to load". And the right way to see the errors is
Open the command prompt (preferably in admin mode, this is what i did).
Goto the same location where gulp file is located.
Run the task through following command example --> gulp default
If there is any error like package is missing, it will show you, fix those issues.
After all errors are fixed, then you will see that gulp task runs successfully.
Go back to visual studio, task runner, and click on refresh (left top button), and it will show you all tasks.
screenshot?
I'm not sure why but opening a cmd prompt at the directory containing gulpfile.js and running npm install has fixed it.
Perhaps someone wiser than I can explain why.
In Output window, make sure you select Task Runner Explorer for Show output from option. This was my problem why I didn't see the error logs from gulpfile. A rookie mistake.
I'm using Visual Studio Community 2019 Version 16.5.4.
I had the same problem and found the answer in the next link:
https://developercommunity.visualstudio.com/content/problem/961170/gulpfile-fails-to-load-after-upgrading-to-vs2019-1.html
Gulp uses node.js but it is important the version to be compatible. I've tried few versions and at the end version 0.12.7 works for me. But had to place absolute path to the place where that node version is installed in VS
Tools > Options > Projects and Solutions > External Web Tools
and move the path to the top. Placing the Path in environment variables and moving $(PATH) to the top didn't help in my case.

Compile error but js get generated

This is a new computer setup. All code compile and run on my old comupter.
I have 2 project in my solution than use typescript.
The first compile without problem.
The second one show error on compile but generate js on save.
I have installed vs 2013 update 5 then installed typescript 1.8.5.
I alsow have vs2015 installed.
After vs2015 was installed i have repair the typescript sdk.
They must have 2 different compiler setup and one in my project is not set correctly.
I have dig into the csproj and compare the 2 project but did not find missing/different parameter for typescript ....
It's like it dont take the new version. I get syntax errors in code i know it compile.
if someone had this problem, please help me.
p.s excuse me for my bad english, im french ...
UPDATE: Exemple of code dont compile
public doSomething(errorCallBack?: (failCallback1?: JQueryPromiseCallback<any> | JQueryPromiseCallback<any>[], ...failCallbacksN: Array<JQueryPromiseCallback<any> | JQueryPromiseCallback<any>[]>) => void)
{}
Error :
Error 218 Build: ',' expected.
A reduced sample code that fails to compile:
class Foo {
public doSomething(errorCallBack?: (failCallback1?: any, ...failCallbacksN: Array<any>[]>) => void)
{ }
}
You have major syntax errors in ...failCallbacksN: Array<any>[]>. You need something like ...failCallbacksN: Array<any> e.g.:
class Foo {
public doSomething(errorCallBack?: (failCallback1?: any, ...failCallbacksN: Array<any>) => void)
{ }
}
but js get generated
This is by design. Valid JavaScript will always generate valid TypeScript (even in the presence of errors). The types are considered invisible to the emitter in TypeScript so even in the presence of type errors TypeScript will try and do graceful recovery and generate JavaScript.
More
See Why TypeScript : https://basarat.gitbooks.io/typescript/content/docs/why-typescript.html
I have found than visual studio IDE was using 1.8.9 and the compiler was 1.0. This is why i had such compilation errors.
when i used "tsc -v" command in vs2013 command prompt, it show 1.0.
when i use "where tsc" it show only directory for 1.0 and not the 1.8.9.
so, i have replaced the 1.0 content with 1.8.9 . I dont use 1.0.
Now i have a 1.0 directory wish have 1.8.9 in it.
I think this is not the way it's supposed to be, but i need it to work.
It have a .target file i can modify, but i dont wish to do that.

Why does command "tsc file.ts" give no output and not produce a js file?

I have just started work on a project with some typescript code, and I'm trying to compile the .ts files to .js files from within Linux Mint, but it's not working as I'd expect.
There is a Makefile, but it's not working. Running make returns an error:
tsc --noImplicitAny --noEmitOnError --out client/welcome.js client/welcome.ts
make: *** [client/welcome.js] Error 1
I have also tried creating an example typescript file greeter.ts (as per this official tutorial) containing:
function greeter(person) {
return "Hello, " + person;
}
var user = "Jane User";
document.body.innerHTML = greeter(user);
and tried compiling the ts file to javascript with the command (as per the same tutorial) tsc greeter.ts however the command completes with no output, and no .js file has been created.
I haven't previously worked with typescript at all, and though I've used Makefile's before I don't know much about them either, so I'm hoping it's something really obvious!
I encountered this problem because I had the following line in my tsconfig.json:
"noEmit": true
It worked after removing it.
--noEmitOnError
This means that if there is an error detected no js will be generated. I highly recommend not using this option (Changes a major benefit of why typescript)
More
Check your tsc version. The code you provided works fine with 1.6:
Update
The --version command should work at the very least. See below:

Is there a JSX formatter for sublime text?

I'm using Sublime Text as a text editor.
There's a jsFormat for formatting javascript files but I can't find one for JSX.
How you guys deal with formatting JSX?
Update 4
Check prettier, not that configurable as esformatter, but currently used to format some big projects (like React itself)
Update 3
Check sublime jsfmt. If you add esformatter-jsx to the config and install the package inside the forlder for sublime-jsfmt. You will be able to format JSX files directly from Sublime. Here is a guide for that
Update 2
from the command line you can also use esbeautifier. It is a wrapper around esformatter that accept a list of globs to format
# install the dependencies globally
npm i -g esbeautifier
# beautify the files under src/ and specs/ both .js and .jsx
esbeautifier src/**/*.js* specs/**/*.js*
Update
So I ended up doing a plugin for esformatter to enable the formatting of JSX files:
https://www.npmjs.com/package/esformatter-jsx
Here is a live demo on requirebin
It should be somehow feasible to call esformatter from Sublime passing the current file as the argument. In any case to use it from the command line you can follow these instructions:
From the command line it can be used like this:
# install the dependencies globally
npm i -g esformatter esformatter-jsx
# call it (this will print to stdout)
esformatter --plugins=esformatter-jsx ./path/to/your/file
# to actually modify the file
esformatter --plugins=esformatter-jsx ./path/to/your/file > ./path/to/your/file
# to specify a config file (where you can also specify the plugins)
# check esformatter for more info about the configuration options
esformatter -c ./path/to/.esformatter ./path/to/your/file > ./path/to/your/file
==== old answer below ===
So if what you're looking is just to make your jsx files to be formatted while allowing the jsx syntax (basically beautify all the javascript syntax and ignore jsx tags, meaning leave them as is), this is what I'm doing using esformatter
// needed for grunt.file.expand
var grunt = require('grunt');
// use it with care, I haven't check if there
// isn't any side effect from using proxyquire to
// inject esprima-fb into the esformatter
// but this type of dependency replacement
// seems to be very fragile... if rocambole deps change
// this will certainly break, same is true for esformatter
// use it with care
var proxyquire = require('proxyquire');
var rocambole = proxyquire('rocambole', {
'esprima': require('esprima-fb')
});
var esformatter = proxyquire('esformatter', {
rocambole: rocambole
});
// path to your esformatter configuration
var cfg = grunt.file.readJSON('./esformatter.json');
// expand the files from the glob
var files = grunt.file.expand('./js/**/*.jsx');
// do the actual formatting
files.forEach(function (fIn) {
console.log('formatting', fIn);
var output = esformatter.format(grunt.file.read(fIn), cfg);
grunt.file.write(fIn, output);
});
I would actually like that esformatter use a version of rocambole that use esprima-fb instead of esprima, to avoid proxyquire.
There is a setting in the HTML-CSS-JS Prettify plugin that allows you to ignore xml syntax in the js/jsx file. That way it doesn't mess up the jsx code.
The setting is: "e4x": true in the "js" section of the settings file
Preferences > Package Settings > HTML\CSS\JS Prettify > Set Prettify Preferences
This does not work well if you have self closing tags eg. tags ending in />
You can install a JsPrettier package for Sublime 2 & 3. It's a fairly new JavaScript formatter (at the time of writing this: Feb-2017). It supports most of the latest developments like: ES2017, JSX, and Flow.
Quickstart
Install prettier globally using terminal: $ npm install -g prettier
In Sublime go to Tools -> Command Palette... -> Package Control: Install Package, type the word JsPrettier, then select it to complete the installation.
Format your file using context menu inside the editor or bind it to a keyboard shortcut: { "keys": ["super+b"], "command": "js_prettier" }
Links:
https://github.com/jonlabelle/SublimeJsPrettier
https://github.com/jlongster/prettier
To add to what #Shoobah said:
There is a setting in the HTML-CSS-JS Prettify plugin that allows you
to ignore xml syntax in the js/jsx file. That way it doesn't mess up
the jsx code. The setting is: "e4x": true in the "js" section of the
settings file
Go to: Preferences > Package Settings > HTML\CSS\JS Prettify > Set
Prettify Preferences
Go to "js" section:
Add "jsx" to the "allowed_file_extension", and then change "e4x" to "true"
the answer in the internet that always told you set 'e4x' to true,
but sometimes, we have to set option of 'format_on_save_extensions' then add 'jsx' in array
modify jsFormat.sublime-settings
{
"e4x": true,
"format_on_save": true,
"format_on_save_extensions": ["js", "json", "jsx"]
}
Using Sublime's Package Installer, install Babel. Then:
Open a .jsx file.
Select View from the menu,
Then Syntax -> Open all with current extension as... -> Babel -> JavaScript (Babel).
Not specifically for Sublime Text, but there is a beautifier in JavaScript for React JSX.
http://prettydiff.com/?m=beautify claims to support JSX at:
http://prettydiff.com/guide/react_jsx.xhtml

Resources