Содержание
- Bug: Parsing error: The keyword ‘const’ is reserved #16174
- <>’s edit
- Environment
- What parser are you using?
- What did you do?
- What did you expect to happen?
- What actually happened?
- Participation
- Additional comments
- Replies: 1 suggested answer
- Insert Link
- Footer
- eslint errors on ‘interface’ keyword even when using this parser #620
- Comments
- Footer
- ERROR: Parsing error: The keyword ‘const’ is reserved #14966
- Comments
- Prerequisites
- Description
- Steps to Reproduce
- Versions
- Parsing error: The keyword ‘const’ is reserved #28
- Comments
- Parsing error: The keyword ‘export’ is reserved #1464
- Comments
Bug: Parsing error: The keyword ‘const’ is reserved #16174
<>’s edit
Environment
Node version: 16.5.0
yarn version: 1.22.10
Local ESLint version: latest
Global ESLint version: latest
Operating System: Widnows
What parser are you using?
What did you do?
What did you expect to happen?
it’s supposed to lint a string that looks like this :
What actually happened?
I received this error:
Participation
- I am willing to submit a pull request for this issue.
Beta Was this translation helpful? Give feedback.
1 You must be logged in to vote
the default ecmaVersion is 5, you’ll need to config it >=6, to use the features like let/const .
the default ecmaVersion is 5, you’ll need to config it >=6, to use the features like let/const .
Beta Was this translation helpful? Give feedback.
Marked as answer
1 You must be logged in to vote
Converted from issue
This discussion was converted from issue #16172 on August 01, 2022 21:44.
Add heading text
Add italic text,
Insert Link
Add a bulleted list,
Add a numbered list,
Add a task list,
Directly mention a user or team
Reference an issue or pull request
Add heading text
Add italic text,
Add a bulleted list,
Add a numbered list,
Add a task list,
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
eslint errors on ‘interface’ keyword even when using this parser #620
I have Babel, ESLint, and Flow all being used in my React Native project. My .eslintrc looks like this:
For some reason, I’m getting an error when I try to declare an interface type in my code:
Not sure why. Could I have setup something wrong?
The text was updated successfully, but these errors were encountered:
Hi @jamesqo, Did you find any solution for this issue?
I got a similar error message.
Eslint version: v5.4.0
@AntonioTsai @jamesqo Did you find out?
I think this is expected behavior. It doesn’t look like Flow supports default exports of types or interfaces. See the bottom of this page for more details.
You can still export the interface, it just has to be named.
It is a reserved keyword, but one who uses Typescript. What’s the solution esp. when eslint runs on pre-commit.
From the documentation linked above it looks like export default interface <> isn’t valid Flow syntax, and so can’t be used with Flow. You’re correct that it is valid in TypeScript though (see microsoft/TypeScript@5ef6192).
I believe the easiest workaround would be to export the interface as a named export.
Thank you for the issue. Now that @babel/eslint-parser has been released, we are making this repository read-only. If this is a change you would still like to advocate for, please reopen this in the babel/babel monorepo.
© 2023 GitHub, Inc.
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
ERROR: Parsing error: The keyword ‘const’ is reserved #14966
Prerequisites
- [ yes] Can you reproduce the problem with Debug -> Reload Without Extensions ?
- [yes] Did you perform a cursory search to see if your bug or enhancement is already reported?
- [yes ] Did you read the Troubleshooting guide?
I change the «brackets-eslint.useLocalESLint»: false, to true in preferences as suggested here:
Expected an identifier and instead saw ‘const’ — Stopping (. % scanned) #11632
Then restarted brackets
For more information on how to write a good bug report read here
For more information on how to contribute read here
Description
ERROR: Parsing error: The keyword ‘const’ is reserved
[Description of the bug or feature]
Unable to continue
Steps to Reproduce
- [First Step]
- [Second Step]
- [and so on. ]
Expected behavior: [What you expected to happen]
No error
Actual behavior: [What actually happened]
ERROR: Parsing error: The keyword ‘const’ is reserved const = require (‘electron’)
Versions
Please include the OS and what version of the OS you’re running.
Ubuntu 18.04 with xubuntu desktop
Please include the version of Brackets. You can find it under Help -> About Brackets (Windows and Linux) or Brackets -> About Brackets (macOS)
Release 1.14 build 1.14.0-17740 (release 329d08f)
The text was updated successfully, but these errors were encountered:
Источник
Parsing error: The keyword ‘const’ is reserved #28
Not sure why but somehow it started giving me this error.
I have es6: true in my .eslintrc.js
Running eslint from command line works fine and setting env inline in the file also works
any ideas on how to fix or debug?
I tried: reinstall (hence how I found the registry error ;)), using root: true , using old .eslintrc
The text was updated successfully, but these errors were encountered:
@AdriVanHoudt if brackets-eslint founds an eslint in your project (https://github.com/zaggino/brackets-eslint/blob/master/domain.js#L62) then it’ll use that version and version installed by npm-registry won’t matter. Check your project if you don’t have an old version of eslint maybe?
it is missing the config file? (version is fine btw)
When useEslintrc: true you shouldn’t need to specify path to config file. I use this extension across about 8-10 projects daily with different configs and it works fine, most of them use const too. But feel free to experiment, maybe you ran into some edge case or something.
yeah I have used it too across many different projects, it somehow broke for some reason 🙁
If I check here: http://eslint.org/docs/user-guide/configuring
With latest eslint, it should be «ecmaVersion»: 6, and not es6: true ?
Does your project work fine if you check it using eslint 2.7.0 from command line? Without Brackets?
es6: true is still a thing, tried with ecmaVersion but no difference, I made a new js file and it does not lint with my config at all
yes it works with running eslint . in project root
I’m guessing it’s not something you have lying around publicly on github? 🙂
the project or config?
also switched to another project with it’s own eslintrc and that uses const and no error, switch back, const error gone but now complains about default rules (like indents), owke.
well, the whole repo with config . or at least a config with a file which replicates the problem when I fetch it
Источник
Parsing error: The keyword ‘export’ is reserved #1464
What code were you trying to parse?
I’m trying to use typescript-eslint , and I followed the Getting Started page. Unfortunately, I’m having problems to make the parser identify very basic TypeScript/JS keywords, like export .
Please see https://github.com/flisboac/ts-promise-scheduler for the project in question. The error is:
My .eslint.js is configured as such:
And here are the first lines of the affected file
What did you expect to happen?
To accept export as a keyword, as per named/default export in TypeScript and the ES6+ standards, in the context of exporting declarations.
What actually happened?
export seems to be identified as a reserved name, regardless of context. Parsing fails.
Versions
Disclaimer:I’m using yarn .
package | version |
---|---|
@typescript-eslint/parser | 2.16.0 |
TypeScript | 3.7.4 |
ESLint | 6.8.0 |
node | 12.13.0 |
npm | 6.12.0 |
yarn | 1.21.1 |
Output of yarn versions`:
Output of yarn list :
The text was updated successfully, but these errors were encountered:
Источник
The error means there are circular references between your modules. You should put the models in a module like index.ts
and make the associations here. Please pay attention to my file directory structure:
E.g.
./models/book.ts
:
import Sequelize from 'sequelize';
import { sequelize } from '../../../db';
export default class Book extends Sequelize.Model {}
Book.init(
{
title: {
allowNull: false,
type: Sequelize.STRING(100),
},
},
{ sequelize, modelName: 'books' },
);
./models/author.ts
:
import Sequelize from 'sequelize';
import { sequelize } from '../../../db';
export default class Author extends Sequelize.Model {}
Author.init(
{
firstName: {
allowNull: false,
type: Sequelize.STRING(100),
},
lastName: {
allowNull: false,
type: Sequelize.STRING(100),
},
},
{ sequelize, modelName: 'authors' },
);
./models/authorbook.ts
:
import Sequelize from 'sequelize';
import { sequelize } from '../../../db';
export default class AuthorBook extends Sequelize.Model {}
AuthorBook.init(
{
authorId: {
type: Sequelize.INTEGER,
allowNull: false,
},
bookId: {
type: Sequelize.INTEGER,
allowNull: false,
},
},
{ sequelize, modelName: 'authorbooks' },
);
./models/index.ts
:
import Author from './author';
import Book from './book';
import AuthorBook from './authorbook';
Author.hasMany(AuthorBook, {
onUpdate: 'CASCADE',
});
Book.hasMany(AuthorBook, {
onUpdate: 'CASCADE',
});
AuthorBook.belongsTo(Author, { foreignKey: 'authorId' });
AuthorBook.belongsTo(Book, { foreignKey: 'bookId' });
export { Author, Book, AuthorBook };
Now, we can use these models.
index.ts
:
import { Author, AuthorBook, Book } from './models';
import { sequelize } from '../../db';
import faker from 'faker';
(async function test() {
try {
await sequelize.sync({ force: true });
// seed
const author = await Author.create({
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
});
const book = await Book.create({
title: faker.lorem.words(3),
});
await AuthorBook.create({ authorId: author.id, bookId: book.id });
} catch (error) {
console.log(error);
} finally {
await sequelize.close();
}
})();
The execution results:
Executing (default): DROP TABLE IF EXISTS "authorbooks" CASCADE;
Executing (default): DROP TABLE IF EXISTS "books" CASCADE;
Executing (default): DROP TABLE IF EXISTS "authors" CASCADE;
Executing (default): DROP TABLE IF EXISTS "authors" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "authors" ("id" SERIAL , "firstName" VARCHAR(100) NOT NULL, "lastName" VARCHAR(100) NOT NULL, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authors' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "books" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "books" ("id" SERIAL , "title" VARCHAR(100) NOT NULL, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'books' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "authorbooks" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "authorbooks" ("id" SERIAL , "authorId" INTEGER NOT NULL REFERENCES "authors" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "bookId" INTEGER NOT NULL REFERENCES "books" ("id") ON DELETE CASCADE ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'authorbooks' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "authors" ("id","firstName","lastName") VALUES (DEFAULT,$1,$2) RETURNING *;
Executing (default): INSERT INTO "books" ("id","title") VALUES (DEFAULT,$1) RETURNING *;
Executing (default): INSERT INTO "authorbooks" ("id","authorId","bookId") VALUES (DEFAULT,$1,$2) RETURNING *;
check the database:
node-sequelize-examples=# select * from "authors";
id | firstName | lastName
----+-----------+----------
1 | Laron | Deckow
(1 row)
node-sequelize-examples=# select * from "books";
id | title
----+-------------------------
1 | facilis molestias sequi
(1 row)
node-sequelize-examples=# select * from "authorbooks";
id | authorId | bookId
----+----------+--------
1 | 1 | 1
(1 row)
Dependencies versions: "sequelize": "^5.21.3"
, postgres:9.6
source code: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples//61163520
Cover image from peforce.com
I decided to write this article to sum up a struggle of mine. We’ve started a new project in the company, Prettier was set up, ESLint was set up and at some point, we added Typescript. By the end, Typescript was also set up. CI was linting, commit hooks were also linting, VSCode was fixing the code, and so on (that is what I thought).
At some point I was playing with the project and realized that some files were being warned by my editor but not when running the linter (npm run lint
in my case). I got triggered. I have a hard time accepting that something works but I can’t understand unless it is an external tool that I didn’t have to set up myself but that was not the case here.
In this article, I will summarize some understandings that I’ve about integrating all the tools above. The main focus is how to set up Prettier, how to set up ESLint, how to integrate both, and by the end how to add Typescript to it.
Prettier
The first tool I want to explore is Prettier. I would leave it to you to read more about what it is but, in short, it is a code formatter. What does it mean? It means that it will keep your codebase consistent (in terms of coding style). Do you use ;
? If yes, it will ensure that all your files have it, for example. I like it for two reasons: we barely have to discuss code formatting and it is easy to onboard new members to the team.
At the time of this writing, Prettier is in version 2.4.1, so keep in mind things might change (especially formatting) in future versions.
How to set up Prettier?
I will consider you have a project set up already so in short, you need to install it:
npm i prettier #--save-dev and --save-exact are recommended
Enter fullscreen mode
Exit fullscreen mode
Right now you can start using Prettier. You don’t need any configuration (if you don’t want it). You can run it against your codebase with:
npx prettier .
Enter fullscreen mode
Exit fullscreen mode
The .
at the end means to run across your whole codebase. You can run for a specific file or pattern if you want.
This command will print the files formatted, nothing special. A more useful command happens when you add --write
flag. Instead of printing the formatted code, it will write to the origin file.
Let’s create a file called index.js
with the following code:
// index.js
const a = 1
Enter fullscreen mode
Exit fullscreen mode
If we run npx prettier index.js
, the output will be:
const a = 1;
Enter fullscreen mode
Exit fullscreen mode
It automatically adds the ;
for us but it is not saved in the file. If we run npx prettier index.js --write
though, the file will change and the ;
will be added to it.
Cool, that is the simplest setup we can have with Prettier. The default rules are documented on their website and can be customized (a bit). We will take a look into it next but before I want to mention another flag: --check
.
The --check
flag, npx prettier index.js --check
, is useful if you just want to check if a file (or the codebase with .
) is Prettier compliant. It is useful for CIs and git hooks, for example, if you just want to warn the user (you can also enable --write
in these scenarios).
If we consider the following code again:
// index.js
const a = 1
Enter fullscreen mode
Exit fullscreen mode
And run npx prettier index.js --check
, we get the following output:
Checking formatting...
[warn] index.js
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
Enter fullscreen mode
Exit fullscreen mode
Prettier configuration
You can configure Prettier to some extend. You can do it via the CLI or via a configuration file, which is more adequate. The configuration file could be in a variety of formats so you can choose the one that fits you best.
Add the configuration file to the root of your project (you can have configurations/folder but I would leave it up to you to explore this path) and start adding rules to it:
// .prettierrc
{
"semi": false
}
Enter fullscreen mode
Exit fullscreen mode
With this configuration file and the following code, again, the --check
run will succeed:
// index.js
const a = 1
Enter fullscreen mode
Exit fullscreen mode
npx prettier index.js --check
:
Checking formatting...
All matched files use Prettier code style!
Enter fullscreen mode
Exit fullscreen mode
On top of that, you can also extend configuration and set up a few other things. Check their configuration documentation for more details.
ESLint
ESLint has been around for a while. In short, it does a bit more than Prettier as it analyzes your code to find problems (or patterns that you don’t want, like variables that are not used should be removed). Again, I invite you to read ESLint documentation if you want to go deeper into the topic. I like ESLint for the simple reason it helps me to find problems and configure some patterns in the project (it might be useful when onboarding new people). It is extremely extensible as well in case you’re interested.
At the time of this writing, ESLint is in version 7.32.0, so keep in mind things might change (especially formatting) in future versions. Version 8 is in beta at the moment.
How to set up ESLint?
In short, quite similar to Prettier but you need the configuration file. I will consider you have a project set up already so, in short, you need to install it:
npm i eslint #--save-dev is recommended
Enter fullscreen mode
Exit fullscreen mode
You need a configuration file. You can create one by yourself or you can run the command below that bootstraps one for you (it can add a lot of presets already):
npx eslint --init
Enter fullscreen mode
Exit fullscreen mode
Let’s start with an empty configuration file though, it is enough to run ESLint:
// .eslintrc.js
module.exports = {
};
Enter fullscreen mode
Exit fullscreen mode
We can now run it, similar to Prettier:
npx eslint .
Enter fullscreen mode
Exit fullscreen mode
One thing to note here: ESLint runs only on .js
files (by default).
Let’s consider the same example as before:
// index.js
const a = 1
Enter fullscreen mode
Exit fullscreen mode
npx eslint index.js
and we get:
1:1 error Parsing error: The keyword 'const' is reserved
✖ 1 problem (1 error, 0 warnings)
Enter fullscreen mode
Exit fullscreen mode
This is simply the issue with a default ESLint configuration. It considers ES5 by default, so const
is not allowed yet, and some older setup might make sense to your project but not in general.
We can spend hours configuring ESLint but in general, we get a default from a style guide (AirBnB for example) and apply it to our project. If you use the init command you can do so.
Let’s install Airbnb ESLint configuration, it also requires eslint-plugin-import
to be installed (following their documentation) so:
npm i eslint-config-airbnb-base eslint-plugin-import # --save-dev is recommended
Enter fullscreen mode
Exit fullscreen mode
Then we extend it in our configuration, so it will look like:
module.exports = {
extends: [
'eslint-config-airbnb-base', // or `airbnb-base`, you can omit `eslint-config-`
]
};
Enter fullscreen mode
Exit fullscreen mode
Running npx eslint index.js
again we get:
1:7 error 'a' is assigned a value but never used no-unused-vars
1:12 error Missing semicolon semi
✖ 2 problems (2 errors, 0 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
Cool! Now we get errors defined by the AirBnB guide. We can use the --fix
option, which works similar to --write
from Prettier, in case we want to fix the errors when possible.
ESLint allows you to extensively configure it if you want. It goes beyond the scope here and I will leave it up to you to explore and play with it: https://eslint.org/docs/user-guide/configuring/
Prettier + ESLint
There are a lot of tutorials online on how to connect both. I want to take a different approach and try to reason about each tool and how they connect.
I will assume that we have the following Prettier configuration:
// .prettierrc
{
"semi": false
}
Enter fullscreen mode
Exit fullscreen mode
I will assume that we have the following ESLint configuration:
// .eslintrc.js
module.exports = {
extends: [
'eslint-config-airbnb-base',
]
};
Enter fullscreen mode
Exit fullscreen mode
I will assume the following script to run both tools:
// index.js
const a = 1
module.exports = { a }
Enter fullscreen mode
Exit fullscreen mode
If we run Prettier check, we get:
Checking formatting...
All matched files use Prettier code style!
Enter fullscreen mode
Exit fullscreen mode
Cool! If we run ESLint, we get:
1:12 error Missing semicolon semi
3:23 error Missing semicolon semi
✖ 2 problems (2 errors, 0 warnings)
2 errors and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
Not so cool! Running ESLint with --fix
will fix these issues. Now if we run Prettier again we get:
Checking formatting...
[warn] index.js
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
Enter fullscreen mode
Exit fullscreen mode
If we run Prettier with --write
it will fix but then ESLint will fail again. It will be like this forever. If the goal were just formatting, I would say pick one of the tools and ignore the other, but we want the power of both tools, especially as ESLint is more than just formatting your code.
Prettier provides two packages that integrate with ESLint.
-
eslint-config-prettier
: turns off rules that might conflict with Prettier. -
eslint-plugin-prettier
: adds Prettier rules to ESLint.
Let’s go step by step. First let’s go and install eslint-config-prettier
:
npm i eslint-config-prettier # --save-dev recommended
Enter fullscreen mode
Exit fullscreen mode
Our new .eslintrc.js
will look like:
module.exports = {
extends: [
'eslint-config-airbnb-base',
'eslint-config-prettier',
]
};
Enter fullscreen mode
Exit fullscreen mode
Considering the file below, again:
const a = 1
module.exports = { a }
Enter fullscreen mode
Exit fullscreen mode
It was a valid file for Prettier but invalid for ESLint. Using the new configuration, it becomes valid as the conflicting rule semi
has been disabled.
It is fine if we want to ignore the rules from Prettier but in general, we want Prettier rules to override ESLint rules.
In case we delete the Prettier configuration file and use its defaults (which requires ;
), running Prettier check will result in:
Checking formatting...
[warn] index.js
[warn] Code style issues found in the above file(s). Forgot to run Prettier?
Enter fullscreen mode
Exit fullscreen mode
The file is not valid anymore as it is missing the ;
but the ESLint run won’t fail, as the Prettier rules have been disabled when running ESLint.
One important thing to note here: the order used by extends
, in the ESLint configuration, matters. If we use the following order we will get an error as AirBnB rules will override Prettier disabled rules when running ESLint:
module.exports = {
extends: [
'eslint-config-prettier',
'eslint-config-airbnb-base',
]
};
Enter fullscreen mode
Exit fullscreen mode
Running npx eslint index.js
:
1:12 error Missing semicolon semi
3:23 error Missing semicolon semi
✖ 2 problems (2 errors, 0 warnings)
2 errors and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
To mitigate this issue let’s install the plugin:
npm i eslint-plugin-prettier # --save-dev recommended
Enter fullscreen mode
Exit fullscreen mode
We can then update our .eslintrc.js
file to:
module.exports = {
extends: [
'eslint-config-airbnb-base',
'plugin:prettier/recommended',
]
};
Enter fullscreen mode
Exit fullscreen mode
We replaced eslint-config-prettier
with plugin:prettier/recommended
. Check ESLint docs about extending a plugin: https://eslint.org/docs/user-guide/configuring/configuration-files#using-a-configuration-from-a-plugin
I also recommend you to check what eslint-plugin-prettier
is doing with our ESLint configuration: https://github.com/prettier/eslint-plugin-prettier/blob/a3d6a2259cbda7b2b4a843b6d641b298f03de5ad/eslint-plugin-prettier.js#L66-L75
Running ESLint again we will get:
1:12 error Insert `;` prettier/prettier
3:23 error Insert `;` prettier/prettier
✖ 2 problems (2 errors, 0 warnings)
2 errors and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
Two things to note here:
- We are getting
;
errors again, that have been disabled earlier witheslint-config-prettier
; - The error is coming from the rule
prettier/prettier
, which is added by the plugin. All prettier validations will be reported asprettier/prettier
rules.
Typescript
Let’s start from the very basic: running ESLint against TS files.
Right now, running ESLint against your codebase would be npx eslint .
. That is fine until you want to run it against files that are not ending with .js
.
Let’s have these two files in our code base:
// index.js
const a = 1
Enter fullscreen mode
Exit fullscreen mode
// index.ts
const a = 1
Enter fullscreen mode
Exit fullscreen mode
Running npx eslint .
we get:
1:7 error 'a' is assigned a value but never used no-unused-vars
1:12 error Insert `;` prettier/prettier
✖ 2 problems (2 errors, 0 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
It runs against our JS file but not our TS file. To run against TS files you need to add --ext .js,.ts
to the ESLint command. By default, ESLint will only check for .js
files.
Running npx eslint . --ext .js,.ts
/index.js
1:7 error 'a' is assigned a value but never used no-unused-vars
1:12 error Insert `;` prettier/prettier
/index.ts
1:7 error 'a' is assigned a value but never used no-unused-vars
1:12 error Insert `;` prettier/prettier
✖ 4 problems (4 errors, 0 warnings)
2 errors and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
Working like a charm so far. Let’s add some real TS code and run it again. The TS file will look like this:
const a: number = 1
Enter fullscreen mode
Exit fullscreen mode
Running ESLint only against the .ts
file:
1:8 error Parsing error: Unexpected token :
✖ 1 problem (1 error, 0 warnings)
Enter fullscreen mode
Exit fullscreen mode
ESLint doesn’t know, by default, how to parse Typescript files. It is a similar problem we faced when running ESLint for the first time with ES5 defaults.
ESLint has a configuration in which you can specify the parser you want to use. There is also a package, as you could imagine, that handles this parsing for us. It is called @typescript-eslint/parser
.
Let’s install it:
npm i @typescript-eslint/parser # --save-dev recommended
Enter fullscreen mode
Exit fullscreen mode
Now let’s configure ESLint to use the new parser:
module.exports = {
parser: "@typescript-eslint/parser",
extends: [
'eslint-config-airbnb-base',
'plugin:prettier/recommended',
]
};
Enter fullscreen mode
Exit fullscreen mode
Running ESLint again (npx eslint index.ts
):
1:7 error 'a' is assigned a value but never used no-unused-vars
1:20 error Insert `;` prettier/prettier
✖ 2 problems (2 errors, 0 warnings)
1 error and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
Cool! Now we can run ESLint on TS files. Nonetheless, we don’t have any rules being used so we need to configure or use some styleguide, like the one we used by AirBnB before.
There is @typescript-eslint/eslint-plugin
that offers us some defaults. Let’s go with it for now:
npm i @typescript-eslint/eslint-plugin # --save-dev recommended
Enter fullscreen mode
Exit fullscreen mode
Adding it to our configuration:
module.exports = {
parser: "@typescript-eslint/parser",
extends: [
'eslint-config-airbnb-base',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
]
};
Enter fullscreen mode
Exit fullscreen mode
Now running npx eslint index.ts
:
1:7 error Type number trivially inferred from a number literal, remove type annotation @typescript-eslint/no-inferrable-types
1:7 warning 'a' is assigned a value but never used @typescript-eslint/no-unused-vars
1:20 error Insert `;` prettier/prettier
✖ 3 problems (2 errors, 1 warning)
2 errors and 0 warnings potentially fixable with the `--fix` option.
Enter fullscreen mode
Exit fullscreen mode
Cool! Now we have also proper linting in our Typescript file. We can also see that the Prettier rule still applies as expected.
Bear in mind that typescript-eslint
is overriding eslint-config-airbnb-base
in this case. It means that some rules won’t work in TS files that are still valid on JS files. Let’s have the files below to see it in action:
// index.js and index.ts
const a = 1;
a = 2;
Enter fullscreen mode
Exit fullscreen mode
Both files are identical. Running npx eslint . --ext .js,.ts
we get:
/index.js
2:1 error 'a' is constant no-const-assign
2:1 warning 'a' is assigned a value but never used @typescript-eslint/no-unused-vars
/index.ts
2:1 warning 'a' is assigned a value but never used @typescript-eslint/no-unused-vars
✖ 3 problems (1 error, 2 warnings)
Enter fullscreen mode
Exit fullscreen mode
The no-const-assign
rule is overwritten by typescript-eslint
for .ts
files so we don’t get the same error for both files.
To overcome it, we need to change the order of the extended configurations, typescript-eslint
comes first and eslint-config-airbnb-base
next. If we do so:
module.exports = {
parser: "@typescript-eslint/parser",
extends: [
"plugin:@typescript-eslint/recommended",
"eslint-config-airbnb-base",
"plugin:prettier/recommended"
]
};
Enter fullscreen mode
Exit fullscreen mode
Running npx eslint . --ext .js,.ts
:
/index.js
2:1 error 'a' is constant no-const-assign
2:1 error 'a' is assigned a value but never used no-unused-vars
2:1 warning 'a' is assigned a value but never used @typescript-eslint/no-unused-vars
/index.ts
2:1 error 'a' is constant no-const-assign
2:1 error 'a' is assigned a value but never used no-unused-vars
2:1 warning 'a' is assigned a value but never used @typescript-eslint/no-unused-vars
✖ 6 problems (4 errors, 2 warnings)
Enter fullscreen mode
Exit fullscreen mode
Cool! Now we get the same error for both files.
One side note: In this example, I have a codebase with JS/TS, it might not be your case and you might also use another style guide where conflicts won’t happen.
That’s all folks!
I hope this article helped you to learn or clarify some concepts behind ESLint, Prettier, and Typescript playing together.
In short, you’ve to understand which files ESLint will analyze and the order of the configurations you want. Image adding now this into a Vue project, for example, you need to add .vue
to --ext .js,.ts,.vue
and add (or configure) some style guide which will add some rules to your project.
Most boilerplates will already have some lint set up and you will mostly disable some rules but in case you want to customize it or update packages (especially major bumps), it is important to understand how to perform the changes and the impacts it might have in your project.
That’s is all! Happy linting!
ESLint defaults to ES5 syntax-checking. You’ll want to override to the latest well-supported version of JavaScript.
Try adding a .eslintrc
file to your project. Inside it:
{ "parserOptions": { "ecmaVersion": 2017 }, "env": { "es6": true }}
Hopefully this helps.
EDIT: I also found this example .eslintrc
which might help.
you also can add this inline instead of config, just add it to the same file before you add your own disable stuff
/* eslint-env es6 *//* eslint-disable no-console */
my case was disable a file and eslint-disable were not working for me alone
/* eslint-env es6 *//* eslint-disable */
I used .eslintrc.js and I have added following code.
module.exports = { "parserOptions": { "ecmaVersion": 6 }};