TypeScript compiler not following ESLint rules - javascript

I'm having an issue where the JavaScript produced by the TypeScript compiler doesn't follow the ESLint rules set for the project.
Here is the TypeScript configuration (tsconfig.json):
{
"compilerOptions": {
"lib": ["es2015"],
"module": "commonjs",
"outDir": "dist",
"sourceMap": true,
"strict": true,
"target": "es2015"
},
"include": [
"src"
]
}
Here is the ESLint configuration (.eslintrc.json):
{
"env": {
"browser": true,
"commonjs": true,
"es6": true,
"node": true
},
"extends": [
"standard",
"plugin:#typescript-eslint/recommended"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 11
},
"plugins": [
"#typescript-eslint"
],
"rules": {
}
}
I'm using VS Code and when editing TypeScript the errors from ESLint are shown. However, the problems I am having are: The compiler will allow code which doesn't conform to the ESLint rules to pass through, and the JavaScript code which is produced doesn't conform to the rules either. For example, it will terminate each statement with a semicolon, when it should not.
I'm new to TypeScript and I'm pretty sure it's something basic I'm doing wrong, but haven't been able to find this info (so far) in any documentation.
Your guidance is appreciated.

ESLint is not in the business of type-checking your typescript code. You should rely on TypeScript for checking for type errors like tslint (Configure it accordingly). Example tslint.json
{
"rulesDirectory": ["node_modules/codelyzer"],
"rules": {
"arrow-return-shorthand": true,
"callable-types": true,
.....
}

ESLint is not involved with the bundle build pipeline. you may however run eslint before the bundle build in order to fail the whole build in case there are linting issues.
If you want to make any changes to the code generated it should be done with webpack plugins / typescript.
So for example, if you want to remove semicolons, this probably should be done with your minifier/compressor. such as uglifyjs : https://github.com/mishoo/UglifyJS#output-options

all you are missing is a property call project on the parserOptions of your eslint file.
....
“parserOptions”:{
.....
“project”: [“./tsconfig.json”]
.....
you can algo add more things to both files as well

Related

non existing import stopped breaking build

I have a project based on create react-app, and it seems since an update of the yup dependency, it stopped launching error on invalid import.
The error "module filename has no exported member X", which used to be launched by react-scripts build, as well as by npm start has completely disappeared, though my IDE still finds such error.
react-scripts build and npm start will still launch an error if I try to use the unexisting import as a variable, but not if I try to use it as a type.
I tried looking at i.e this question or this one, or others similar questions, but none was like my case (i.e, the files giving problems DO have import, and the commit introducing the bug was litterally changing just the yup dependency in package.json, and changing package-lock.json accordingly. I also tried updating my #typescript-eslint/no-unused-vars rules to error, but it gave me too many errors, and I have no guarantee it'll catch any unexisting type exported and used as type)
In case it helps, here is my tsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react",
"noFallthroughCasesInSwitch": true
},
"include": [
"src"
]
}
and my .eslintrc.json
{
"parser": "#typescript-eslint/parser",
"parserOptions": {
"tsconfigRootDir": ".",
"project": [
"./tsconfig.json"
]
},
"extends": [
"react-app",
"eslint:recommended",
"plugin:#typescript-eslint/recommended",
"prettier/#typescript-eslint",
"plugin:prettier/recommended"
],
"plugins": [
"filenames"
],
"rules": {
//- https://palantir.github.io/tslint/rules/no-null-undefined-union/ should be added once a typescript-eslint equivalent exists
"#typescript-eslint/explicit-function-return-type": 0,
"#typescript-eslint/no-explicit-any": 0,
// as per https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unused-vars.md, we must disable the base rule to prefer the typescript one
"no-unused-vars": 0,
"filenames/match-exported": 1,
"#typescript-eslint/prefer-as-const": 1,
"#typescript-eslint/ban-types": 1,
"#typescript-eslint/no-unnecessary-type-assertion": 1,
"#typescript-eslint/strict-boolean-expressions": [
1,
{
"allowNullableString": true,
"allowNullableObject": true,
"allowNullableBoolean": true,
"allowNumber": false,
"allowAny": true
// we use lodash, better allow these any
}
],
"#typescript-eslint/no-unused-vars": 1,
"no-return-await": 2,
"curly": 2,
"#typescript-eslint/no-inferrable-types": [
2,
{
"ignoreParameters": true
}
]
}
}
Thank you for any help.
So I ended up fixing this problem by reinstalling my dependencies with a more up to date version. I juste removed my node_module and my package-lock.json before running npm i. I know suppressing node_module and package-lock should have had no effect, but I preferred to be sure.
It made my project have all kind of new errors, but in the lot, there was my error for invalid import, so it was good for me.

How to resolve "Definition for rule '#typescript-eslint/rule-name' was not found"

I'm trying to add TypeScript compilation to an existing Javascript project.
AFAIK this is supposed to be possible (even easy), and you can incrementally spread TS through the codebase. Unfortunately this isn't what I'm seeing - after adding typescript and trying to start the project, I get this error for every single file in the project:
Definition for rule '#typescript-eslint/rule-name' was not found
There is no instance of the string rule-name anywhere in my source code.
This is my tsconfig.json:
{
"compilerOptions": {
"baseUrl": "src",
"noImplicitAny": false,
"sourceMap": true,
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"allowSyntheticDefaultImports": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"esModuleInterop": true,
"jsx": "react",
"skipLibCheck": true
},
"include": [
"src",
"types"
],
"exclude": [
"node_modules",
"build"
]
}
I have tried adding "checkJs": false to the config and restarting but that doesn't change anything.
I haven't been able to track down anything online about this "rule-name" problem. It really looks like this is a placeholder text of some sort, but I can't find the source.
Can anybody suggest anything that might help me get this project to build?
The error that you have is coming from ESLint and means that you have a rule in your .eslintrc which doesn't exist in any of your plugins. This could have happened if you followed the usage guide for #typescript-eslint/eslint-plugin but didn't replace the placeholder rule-name with an actual rule name as seen here https://www.npmjs.com/package/#typescript-eslint/eslint-plugin
For those who do not want to just disable ESLint but make it work, running npm update could resolve the issue. In my case updating just #typescript-eslint/parser and #typescript-eslint/eslint-plugin was not enough but after npm update warnings dissapeared and ESLint was up and running.
Also worth to keep in mind this higlight from package authors:
It is important that you use the same version number for #typescript-eslint/parser and #typescript-eslint/eslint-plugin.
More detailed packages setup on npmjs.
This is because the rule is not declared in your eslint.json file
Add the following line to your RULES in esling.json file
"#typescript-eslint/object-curly-spacing" : "off"
Refer the image below to know more
Refer this image to add the rule to eslint.json file
For me, it was enough to add plugin:#typescript-eslint/recommended
in the .eslintrc file.
"extends": [
...<otherExtentions>...
"plugin:#typescript-eslint/recommended"
]
If you're using react-app-rewired and customize-cra, you need to make sure you use disableEsLint from the latter; otherwise linting errors become typescript errors and prevent compilation.

TypeScript Error Cannot find name on 'SyncClient' Twilio

I am creating an ionic app and everytime I try to use the library twilio-chat on my project via npm install I always got an error on .d.ts files
Import in my provider :
import { Client } from "twilio-chat";
Errors:
it seems the .d.ts files doesnt know where to look for the dependency modules they need. is it related on typings of typescript? I'm quite new to typescript.
but when I try to use the cdn it works perfectly fine.
I'm using
ionic: "3.18.0"
typescript: "2.2.1"
twlio-chat: "1.2.1"
update: I were able to fix the SyncClient and Emc Client by mapping on were exactly .d.ts files. the only problem was there are twilio dependencies that doesn't have .d.ts files like twilio-transport, twilsock and twilio-notifications.
tsconfig.json contains:
{
"compilerOptions": {
"allowSyntheticDefaultImports": true,
"declaration": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"dom",
"es2015"
],
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"target": "es5",
"baseUrl": ".",
"paths": {
"twilio-sync": ["node_modules/twilio-sync/lib"],
"twilio-ems-client": ["node_modules/twilio-ems-client/lib"]
}
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
],
"compileOnSave": false,
"atom": {
"rewriteTsconfig": false
}
}
TIA
How do you compile typescript files? If you use tsconfig.json, make sure it uses "moduleResolution": "node" and node_modules can be found from upper directory. Maybe you want to look this: https://www.typescriptlang.org/docs/handbook/module-resolution.html#node
Twilio Developer Evangelist here. Let me see if I can help you :) Technically this should work right out of the box since both the twilio-sync as well as the twilio-chat library are written in TypeScript. Could you post your tsconfig.json as well as the full list of dependencies you have installed so that we can take a look at it?
In general you'll have to install typings for any module that doesn't ship it's own typings.
Cheers,
Dominik

getting nyc/istanbul coverage report to work with typescript

I'm struggling to get proper coverage with nyc/istanbul for my typescript/mocha/gulp project. I've tried a number of approaches, some of them seem to be unable to use source maps and other fails due to ts-node/tsc errors. My current setup is:
nyc relevant config in package.json
"scripts": {
"test:coverage": "nyc npm run test:unit",
"test:unit": "gulp mocha"
}
"nyc": {
"check-coverage": true,
"all": true,
"extension": [
".js",
".jsx",
".ts",
".tsx"
],
"include": [
"src/**/!(*.test.*).[tj]s?(x)"
],
"reporter": [
"html",
"lcov",
"text",
"text-summary"
],
"report-dir": "docs/reports/coverage"
}
gulpfile.js mocha relevant part
const SRC_DIR = path.join(__dirname, 'src');
const SRC_FILES = path.join(SRC_DIR, '**', '*.[jt]s?(x)');
const TEST_FILES = path.join(SRC_DIR, '**', '*.test.[jt]s?(x)');
const MOCHA_CONFIG = {
src: [
TEST_FILES
],
watchSrc: [
SRC_FILES,
TEST_FILES
],
mocha: {
// compilers: [
// 'ts:ts-node/register',
// 'tsx:ts-node/register'
// ],
require: [
'./tests/setup.js',
'ignore-styles',
'source-map-support/register'
]
}
};
gulp.task('mocha', mocha(MOCHA_CONFIG));
tsconfig.json
{
"compilerOptions": {
"baseUrl": "./",
"rootDir": "./src",
"outDir": "./build",
"allowJs": true,
"module": "commonjs",
"target": "es5",
"lib": ["es5", "es6", "dom"],
"sourceMap": true,
"inlineSourceMap": false,
"inlineSources": false,
"experimentalDecorators": true,
"noUnusedParameters": true,
"noUnusedLocals": true,
"jsx": "react",
"moduleResolution": "node"
},
"exclude": [
"docs",
"tests",
"**/*.test.js",
"**/*.test.jsx",
"**/*.test.ts",
"**/*.test.tsx",
"tools",
"gulpfile.js",
"node_modules",
"build",
"typings/main",
"typings/main.d.ts"
],
"awesomeTypescriptLoaderOptions": {
"useCache": true,
"useBabel": true
}
}
With the above setup coverage produces results for all the files but they are incorrect for TS files most probably due to source maps not being used (i.e. report shows no coverage for lines which are comments and the numbers seems to be wrong as well).
With a number of variant approaches tried with no success one of the most commonly suggested is to add "require": ["ts-node/register"] to nyc configuration yet then I'm getting errors complaining about i.e. gulpfile.js, docs/reports/coverage/lcov-report/prettify.js and number of other JS files to be not under 'rootDir' which is correct yet it is not clear why ts-node tries to process all the files out of src even if they are excluded in tsconfig.json (still the configuration gets really complex).
I'll appreciate any suggestion which way to go to get proper coverage report for TS files.
Recently I found a satisfiable solution by using "target": "es6" instead of es5 in tsconfig.json's compilerOptions. While changing target directly in tsconfig.json may not be an option as it affects build, the other tip is to use TS_NODE_COMPILER_OPTIONS='{"target":"es6"} which can be added directly in package.json scripts as i.e. :
"test:coverage": "TS_NODE_COMPILER_OPTIONS='{\"target\":\"es6\"}' nyc npm run test:unit",
where test:unit is whatever way being used to run actual tests (in my case just gulp mocha.
NOTE: I've also updated nyc to latest 11.1.0 and ts-node to 3.3.0 as suggested on https://github.com/istanbuljs/nyc/issues/618 thread
I'm not sure this is the same problem but I'll put this here in case it helps future developers...
I wasn't getting any coverage data until I added exclude-after-remap=false to the nyc section of my package.json.
This is listed in the documentation but not in a very prominent way (IMO).
Since a lot of changes broke old working setups I created a verbose example project covering typescript + mocha + nyc supporting proper coverage also for non called files (this is often not included in examples) as well as some unit test examples and quality checks using latest versions.
I had several issues whilst going to mocha 8+ nyc 15+. Maybe it also helps someone else stumbling across it.
https://github.com/Flowkap/typescript-node-template
If you're only interested in coverage check the .ncyrc.yml and mocharc.yml as well as the call config in package.json. VsCode launch configs also included:
.nycrc.yml
extends: "#istanbuljs/nyc-config-typescript"
reporter:
- html
- lcovonly
- clover
# those 2 are for commandline outputs
- text
- text-summary
report-dir: coverage
.mocharc.yml
require:
- ts-node/register
- source-map-support/register
recursive: true
color: true
exit: true
extension:
- ts
- test.ts
test job in package.json
"test": "npm run lint && nyc mocha src test",

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