TSLint: how to ignore JS files? - javascript

How can I tell tslint to ignore JS files?
In tsconfig.json I have "allowJs": true because I do want it to compile JS files:
{
"compilerOptions": {
// ...
"allowJs": true,
// ...
},
// ...
}
However I do not want it to lint them.
With this setup, it complains that "No valid rules have been specified for JavaScript files". This is because it tries to lint JS files, but has not been given any rules for doing so.
It has been suggested in another Stack Overflow thread to add the following, so that it has some rules to go by (a bit of a hack really):
"jsRules": {
"no-empty": true
}
But what if I don't want it to check for this rule either? I just don't want it to lint JS files at all.

I've found out how to do this.
To ignore JS files, add the following to your tslint.json (you can, of course, ignore any file type in a similar fashion)
"linterOptions": {
"exclude": [
"**/*.js"
]
}
Note that linterOptions.exclude was introduced in tslint 5.8, so you must have this version or later to use this feature.

Related

Detecting class instance undefined method name in javascript

I'm working in a new-to-me large javascript codebase that is a work-in-progress. As happens often in a large codebase, a variety of people have added code that has not been tested. I just spent way too much time debugging an issue that ended up being caused by a misspelled method name (essentially a missing method):
stream.renegotiate() // this is what is should have been
stream.renogotiate() // this is what it was
The project is bundled using webpack, without linting. So I thought I could just add eslint to the webpack config and it would tell me about the problems. It works for misspelled global methods, but is not checking class member name spelling.
Here is my .eslintrc file:
{
"plugins": [
"eslint-plugin-import"
],
"extends": [
"eslint:recommended",
"plugin:import/recommended",
"plugin:import/typescript"
],
"rules": {
"no-undef": "error",
"no-extra-semi": "off",
"no-unused-vars": "off"
},
"env": {
"browser": true,
"es2022": true
}
}
The typescript option is in there because a few of the newer files in the project are typescript, but still there are 100+ legacy javascript files that have been recently worked on that have issues.
Is there a way to get eslint (or some other checker) to be able to detect and error-report the example above of stream.renogotiate() without doing a fullscale migration to typescript?
Javascript is loosely typed and it's possible to monkeypatch new methods onto existing classes and objects at runtime, so (as far as I know) there's no way to catch these sorts of issues at build time without something like typescript, even if you know the object's type.
Consider the example below. The test function throws on the first invocation but not on the second, despite being passed the same stream instance both times.
class Stream {
renegotiate () {
console.log('renegotiate invoked');
}
}
function test (stream) {
try {
stream.renOgotiate();
}
catch {
console.log('error trying to invoke renOgotiate')
}
}
const stream = new Stream();
test(stream); // throws
Stream.prototype.renOgotiate = () => console.log('renOgotiate invoked');
test(stream); // doesn't throw
Turns out the typescript compiler can be used for exactly what I described above. You can use it in vscode to check individual files by adding this to the top of a .js file:
// #ts-check
If you want to check a whole project, create a jsoncfig.json file wherever the root of the javascript content is, then run the typescript compiler from the command-line with this:
npx tsc -p jsconfig.json
In my case, it did exactly what I was hoping it would do, highlighted a significant number of undefined symbols, including the one originally referenced, with this output:
error TS2339: Property 'renogotiate' does not exist on type 'MediaStream'.
This is a great first-step in porting a large javascript project to typescript. Thanks to the vscode docs for the guidance: https://code.visualstudio.com/docs/nodejs/working-with-javascript
FWIW, here is what I used for my jsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"target": "es2020",
"checkJs": true,
"allowJs": true,
"noEmit": true,
"skipLibCheck": true
},
"exclude": ["node_modules"],
"include": ["src/legacy/**/*"],
}

Importing PostCSS file as module returns SyntaxError

I've been trying to import PostCSS file as module in my TypeScript, using Parcel. I've followed a YouTube video partially (not fully because they're running an older version of Parcel.), and also followed some parts of the Parcel documentation. Parcel is transpiling the PostCSS to CSS properly, and even including the style in the HTML document, but it's also copying and pasting the transpiled CSS in the JavaScript tag instead of converting it to a proper module.export object and therefore causing a SyntaxError. I am very unsure what I could possibly have done wrong. I, either can't seem to find anyone whose had a similar issue, or am just bad at wording my issue.
{
// "modules": true,
"plugins": {
"postcss-import": true,
"postcss-url": true,
"postcss-nested": true
}
}
This is my .postcssrc, it's working as far as I know. When I add the "modules": true, it tells me to remove it and add "cssModules" in package.json instead
{
// ...
"#parcel/transformer-css": {
"cssModules": {
"pattern": "av-[hash]-[local]",
"global": true
}
},
"browserslist": [
"> 0.5%, last 2 versions, not dead"
]
}
This is contents in my package.json which is relevant to parcel. And these are the dependencies that were (mostly) automatically installed by Parcel.
import * as classes from "../css/style.pcss";
console.log(classes);
This is where I try to get the exported class modules, but It doesn't even log anything because of the SyntaxError.

Angular 2 AoT Rollup fails with 'require is not defined'

I have and Angular2 application that I'm compiling to run with AoT.
I've solved the issues I had with the actual compilation and I've also been able to run Rollup from start to end without errors (although there's a lot of warning, which I think are to be expected).
However, when running the application, the browser always states that require is not defined on my app.bundle.js.
What am I doing wrong?
Here's my functional non-AoT sample code/configs:
https://plnkr.co/edit/oCAaeXUKWGyd34YKgho9?p=info
And here is my functional AoT sample configs that throw the require error:
https://plnkr.co/edit/Y1C5HaQS3ddCBrbRaaoM?p=info
Does anyone find any errors here, especially when comparing the non-AoT system.js configs and the AoT rollup configs?
Why am I hitting this error?
I understand that the browser is incapable of working with require but shouldn't rollup attend to that?
Best Regards
So, eventually I was able to solve the issue.
There was a rogue const _ = require("lodash") in the code.
Once I removed it, it all went along without issues.
Two things worth mentioning:
Due to memory limitations on node.js (1.7GB of RAM), the ngc command is run with node --max-old-space-size=8192 ./node_modules/.bin/ngc -p tsconfig-aot.json
Again, for the same reason, rollup is run with node --max-old-space-size=8192 ./node_modules/.bin/rollup -c rollup-config.js
You might be able to get away with --max-old-memory=4096, depending on the size of your project and memory on your computer.
As for my rollup-config.js, though I'm not sure if everything here is really necessary, here's what worked for me:
import builtins from 'rollup-plugin-node-builtins';
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import uglify from 'rollup-plugin-uglify';
export default {
entry: 'app/app.aot.js',
dest: 'www/bundle.js', // output a single application bundle
sourceMap: false,
format: 'iife',
plugins: [
nodeResolve({
jsnext: true,
module: true,
browser: true
}),
commonjs({
// non-CommonJS modules will be ignored, but you can also
// specifically include/exclude files
include: [
'node_modules/**',
'node_modules/primeng/**',
'node_modules/moment/**',
'node_modules/rxjs/**',
'node_modules/lodash/**'
], // Default: undefined
exclude: ['node_modules/ws/**'], // Default: undefined
// search for files other than .js files (must already
// be transpiled by a previous plugin!)
extensions: ['.js'], // Default: [ '.js' ]
// if true then uses of `global` won't be dealt with by this plugin
ignoreGlobal: false, // Default: false
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'node_modules/primeng/primeng.js': [
'PanelModule',
'InputSwitchModule',
'InputMaskModule',
'ProgressBarModule',
'DropdownModule',
'CalendarModule',
'InputTextModule',
'DataTableModule',
'DataListModule',
'ButtonModule',
'DialogModule',
'AccordionModule',
'RadioButtonModule',
'ToggleButtonModule',
'CheckboxModule',
'SplitButtonModule',
'ToolbarModule',
'SelectButtonModule',
'OverlayPanelModule',
'TieredMenuModule',
'GrowlModule',
'ChartModule',
'Checkbox',
'Dropdown',
'Calendar',
'DataGridModule',
'DataTable',
'MultiSelectModule',
'TooltipModule',
'FileUploadModule',
'TabViewModule',
'AutoCompleteModule'
],
'node_modules/ng2-uploader/index.js': ['Ng2Uploader']
},
// if false then skip sourceMap generation for CommonJS modules
sourceMap: false, // Default: true
}),
builtins(),
uglify()
]
}
rollup still complains about default imports on some packages, which can be probably solved using the named exports (if you really want to) but even with those warnings everything seems to be running.
As for my "final" tsconfig.json:
{
"compilerOptions": {
"lib": ["es2015", "dom"],
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"declaration": false,
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": true,
"noImplicitAny": false,
"watch": false,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"suppressImplicitAnyIndexErrors": true,
"baseUrl": ".",
"typeRoots": [
"./node_modules/#types",
"./node_modules"
],
"types": [
"node",
"lodash",
"jasmine",
"bluebird",
"socket.io-client"
]
},
"compileOnSave": false,
"buildOnSave": false,
"files": [
"app/app.module.ts",
"app/app.aot.ts"
],
// "exclude": [
// "node_modules"
// ],
"angularCompilerOptions": {
"genDir": "compiled",
"skipMetadataEmit": true
}
}
Finally, these two links were also helpful in understanding what's going on behind the scenes:
https://code.lengstorf.com/learn-rollup-js/
https://github.com/rollup/rollup/issues/737
Hope this helps someone.
My solution for this problem was the following:
I tracked, what the system wants to require: the modules fs, events, and timer. All of them were referenced in the zone.js.
I've found some zone.js imports hacked into my code in my earlier tries to make in smaller as 5M.
After I removed them, the problem disappeared.
For the googlers of the future with a similar problem:
The cause of the problem is that your npm module uses require() internally. You have to update it, or to recompile it, but this time as ES6 package (which doesn't use require(), it uses import). If a require is really deeply hardcoded into it (for example, it is in .js and uses require), then you have to modify its source.
Additional extension:
It seems, rollup can't correctly handle non-ordinary imports like import 'Zone.js'; and similar! It can handle only import { something } from 'Anything';-like imports!
The root of all problems is that Angular requires zonejs imported on this way, furthermore any typescript decorator require the reflect-metadata package, imported also on this way.
But, it is not really a problem. Things looked so before, like
<script src="...zone.js"></script>
Or with an
import 'zone.js';
, shouldn't be exist in the source (or in the HTML) any more. Instead, you have to compile the sources without them, and then simply concatenate them to the beginning of your source. In my case, I use the following Grunt rule:
concat: {
dev: {
src: [ "node_modules/zone.js/dist/zone.js", "node_modules/reflect-metadata/Reflect.js", "target/MyApp-core.js" ],
dest: "target/MyApp.js"
}
},
It is part of the grunt-contrib-concat Grunt package.
The resulting target/MyApp.js can be further processed by any other tools (uglify, or the best is google closure compiler).

How to ignore a particular directory or file for tslint?

The IDE being used is WebStorm 11.0.3, the tslint is configured and works, but, it hangs because it tries to parse large *.d.ts library files.
Is there a way to ignore a particular file or directory?
Update for tslint v5.8.0
As mentioned by Saugat Acharya, you can now update tslint.json CLI Options:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"lib/*generated.js"
]
}
}
More information in this pull request.
This feature has been introduced with tslint 3.6
tslint \"src/**/*.ts\" -e \"**/__test__/**\"
You can now add --exclude (or -e) see PR here.
CLI
usage: tslint [options] file ...
Options:
-c, --config configuration file
--force return status code 0 even if there are lint errors
-h, --help display detailed help
-i, --init generate a tslint.json config file in the current working directory
-o, --out output file
-r, --rules-dir rules directory
-s, --formatters-dir formatters directory
-e, --exclude exclude globs from path expansion
-t, --format output format (prose, json, verbose, pmd, msbuild, checkstyle) [default: "prose"]
--test test that tslint produces the correct output for the specified directory
-v, --version current version
you are looking at using
-e, --exclude exclude globs from path expansion
Currently using Visual Studio Code and the command to disable tslint is
/* tslint:disable */
Something to note. The disable above disables ALL tslint rules on that page. If you want to disable a specific rule you can specify one/multiple rules.
/* tslint:disable comment-format */
/* tslint:disable:rule1 rule2 rule3 etc.. */
Or enable a rule
/* tslint:enable comment-format */
More in depth on TSLint rule flags
In addition to Michael's answer, consider a second way: adding linterOptions.exclude to tslint.json
For example, you may have tslint.json with following lines:
{
"linterOptions": {
"exclude": [
"someDirectory/*.d.ts"
]
}
}
Starting from tslint v5.8.0 you can set an exclude property under your linterOptions key in your tslint.json file:
{
"extends": "tslint:latest",
"linterOptions": {
"exclude": [
"bin",
"**/__test__",
"lib/*generated.js"
]
}
}
More information on this here.
I had to use the **/* syntax to exclude the files in a folder:
"linterOptions": {
"exclude": [
"src/auto-generated/**/*",
"src/app/auto-generated/**/*"
]
},
As an addition
To disable all rules for the next line // tslint:disable-next-line
To disable specific rules for the next line: // tslint:disable-next-line:rule1 rule2...
To disable all rules for the current line: someCode(); // tslint:disable-line
To disable specific rules for the current line: someCode(); // tslint:disable-line:rule1
There are others who encountered the problem. Unfortunately, there is only an open issue for excluding files: https://github.com/palantir/tslint/issues/73
So I'm afraid the answer is no.
linterOptions is currently only handled by the CLI.
If you're not using CLI then depending on the code base you're using you'll need to set the ignore somewhere else. webpack, tsconfig, etc
Can confirm that on version tslint 5.11.0 it works by modifying lint script in package.json by defining exclude argument:
"lint": "ng lint --exclude src/models/** --exclude package.json"
Cheers!!
add the section in your code example
"linterOptions": {
"exclude": [
"node_modules/**/*.",
"db/**/*.",
"integrations/**/*."
]
},

Webstorm 11 check typescript files without compiling. Using webpack for compilation

i'm trying to use webstorm with webpack and typescript and i have stuck with errors checking.
I want to compile ts files with webpack, so i need to avoid compiling source files via Webstorm, but it seems like Webstorm perform error checking only during compilation process.
Corresponding to webstorm docs "Resolve objects using tsconfig.json" should activate Errors checking without compilation, but is doesnt.
example code, which Webstorm doesnt highlight
{ let z = 4;}
console.log(z);
my tsconfig file:
{
"compilerOptions": {
"module": "commonjs",
"out": "build/tsc.js",
"target": "es5",
"sourceMap": true,
"jsx": "react"
},
"exclude": [
"node_modules"
]
}
In same time Visual studio code display errors fine.
Do i have any errors in my configs ?
Is it possible to highlight errors correct with Webstorm or other JetBrains IDE?
Typescript version 1.7, Webstorm 11.
Original Answer (outdated - see UPDATE below):
As Valery correctly pointed out you can set the "noEmit" property to true to prevent the compiler creating any output files.
However, if your Webpack setup uses the same tsconfig.json file it will also prevent webpack from creating the output files. You'll only notice this the next time webpack is restarted.
In my webpack setup I'm using the "ts-loader" Typescript loader.
As mentioned on the ts-loader github page you can override compiler options.
So this is my setup:
tsconfig.json (used by IDE and Webpack)
"compilerOptions": {
"noEmit": true, // do not emit js and map files
...
webpack.config.json (used by Webpack)
{
test: /\.ts$/,
loader: 'ts-loader',
query: {
'compilerOptions': {
"noEmit": false // make sure js files do get emitted
}
},
...
}
Et voila: IDE compiler checks without js and js.map files polluting your source code folder!
UPDATE: My answer was a valid workaround in January but today the better solution is to use the Typescript service inside Webstorm/IDEA as suggested by anstarovoyt.
Also don't forget to UNcheck "Enable TypeScript Compiler" as shown here:
WebStorm 2016.1 (and other IJ 2016.1 IDEs) supports "compileOnSave" option. Example:
{
"compileOnSave": false,
"compilerOptions": {
"module": "commonjs"
}
}
Update: WebStorm 2016.2 has the new 'TypeScript service' integration.
You don't need the 'TypeScript complier' integration at all. Just check the option 'Use TypeScript service'. Moreover the new integration works much more faster.
Update 2: The integration is enabled by default in WebStorm 2016.3
I found the way to prevent compiler output vis tsconfig - noEmit option.
{
"compilerOptions": {
"module": "commonjs",
"noEmit": true,
"target": "es5",
"sourceMap": true,
"jsx": "react"
},
"exclude": [
"node_modules"
]
}
With this config i have no extra file and correct error highlight in webstorm.
In your Webpack configuration file add this in module.rules:
{
test: /\.tsx?$/,
use: [
{
loader: 'ts-loader',
options: {
compilerOptions: {
noEmit: false,
},
},
},
],
}
Obviously, if you already have a rule for test: /\.tsx?$/, you should combine it with the above.
And note that module.rules is an array of objects, not an object.

Categories