Eslint parsing error the keyword interface is reserved

eslint errors on ‘interface’ keyword even when using this parser #620 Comments 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 […]

Содержание

  1. eslint errors on ‘interface’ keyword even when using this parser #620
  2. Comments
  3. Footer
  4. Parsing error: The keyword ‘export’ is reserved #1464
  5. Comments
  6. Ошибка синтаксического анализа: ключевое слово «импорт» зарезервировано.
  7. Код Visual Studio? – Другие текстовые редакторы или IDE?
  8. Предыдущие отчеты об ошибке
  9. использованная литература
  10. использованная литература
  11. 0. Предпосылки
  12. 1. Локально установите ESLint
  13. 2. Создайте .eslintrc.json файл, который работает
  14. Обновите все npm пакеты до последних версий
  15. Заключение
  16. использованная литература
  17. [eslint] Parsing error: The keyword ‘import’ is reserved #666
  18. Comments
  19. Footer

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.

Источник

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:

Источник

Ошибка синтаксического анализа: ключевое слово «импорт» зарезервировано.

В коде Visual Studio я получаю Parsing error: The keyword ‘import’ is reserved . 1

Какие действия вы бы порекомендовали для исправления этой ошибки?

Я предоставляю свои .eslintrc.json и package.json файлы ниже.
Однако их, скорее всего, будет недостаточно для воспроизведения ошибки.
Итак, вот ссылка на zip-файл, содержащий все необходимые файлы проекта . 2

Проект (локально) устанавливается путем запуска npm install — это может занять около 5-9 минут.
Затем npm start следует открыть проект в веб-браузере по умолчанию. 3

Когда я делаю это и нажимаю F12 , я не получаю никаких ошибок, кроме двух предупреждений в консоли браузера.
Предупреждения:

‘unUsedArgument’ is defined but never used. Allowed unused args must match /^_/u no-unused-vars , а также

‘unUsedVariable’ is assigned a value but never used. Allowed unused vars must match /^_/u no-unused-vars .

Ошибка в заголовке Parsing error: The keyword ‘import’ is reserved появляется, когда я открываю App.js в VS Code.

Но эта ошибка никак не связана с моим выбором текстового редактора,
в чем легко убедиться, запустив ESLint из командной строки.
Используйте первую строку, если вы используете Microsoft Windows (обратная косая черта).
Используйте вторую строку, если вы используете любую другую операционную систему (косая черта).

Код Visual Studio? – Другие текстовые редакторы или IDE?

Хотя я использую Visual Studio Code, я также приглашаю к ответам (и обсуждениям) других текстовых редакторов и IDE. Обратите внимание, что — помимо правильной установки ESLint через npm — вам также необходимо установить плагин/расширение для вашей конкретной интегрированной среды разработки (IDE).
В моем случае я использую это расширение VS Code ESLint . 4

Тем не менее, основное внимание здесь должно быть уделено npm команде и установленным пакетам Node.js.

Предыдущие отчеты об ошибке

В ссылках 5-12 из списка ниже я ссылаюсь на некоторые предыдущие отчеты об этой ошибке или подобных ошибках.
Некоторые из этих ссылок (вопросов) явно связаны с проблемой здесь, но, возможно, не все из них.

использованная литература

1 Слово import может быть const — или почти любое другое ключевое слово JavaScript.

2 Поскольку рекомендуется устанавливать ESLint локально , я предполагаю, что все читатели здесь так и делают.

3 В моем случае Google Chrome версии 98.0.4758.102, 64-бит. Запуск на Windows 10.

4 Помимо установки расширения, я добавил «eslint.nodePath»: «C:\Program Files\nodejs», его в свой (пользовательский) settings.json файл в VS Code. Никаких других изменений.

Вот простое решение — просто переместите rules атрибут from .eslintrc.json в eslintConfig атрибут package.json . 1

И не держи .eslintrc.json . Просто удалите его! 2

Теперь package.json файл будет следующим.

Убедитесь, что вы добились успеха.
Используйте первую строку, если вы используете Microsoft Windows (обратная косая черта).
Используйте вторую строку, если вы используете Linux или macOS (косая черта).

Если ваш текстовый редактор (в моем случае VS Code) все еще открыт, убедитесь, что вы перезапустили его, прежде чем вы ожидаете, что ошибка исчезнет!

использованная литература

1 Я получил идею из этого поста .

2 Не беги npm init @eslint/config .
Ошибки останутся, если вы не удалите .eslintrc.json !

3 A. Если вы подозреваете, что у вас может быть глобальная установка ESLint, сначала запустите:
npm uninstall eslint —global

Б. Если вы уже запустили npm install — как указано в строке 6 вопроса — вам не нужно запускать npm install eslint —save-dev для установки ESLint.
Потому что первый npm install также устанавливает ESLint , как я обнаружил при написании этого ответа .

0. Предпосылки

Если сервер запущен, закройте его, нажав Ctrl + C .

Я настоятельно рекомендую удалить все глобальные установки ESLint.
Чтобы увидеть, какие глобальные пакеты установлены, в командной строке выполните: 1

Если ESLint установлен глобально, удалите его, запустив:

Чтобы правильно установить ESLint в ваш локальный проект, я рекомендую выполнить следующие два шага.

Локально установите ESLint.

Создайте работающий .eslintrc.json файл.

Как оказалось, вам также нужно будет сделать третий шаг.

  1. Обновите все npm пакеты до последних версий.

1. Локально установите ESLint

Чтобы локально установить ESLint, запустите: 2

в конце package.json .

2. Создайте .eslintrc.json файл, который работает

ПРИМЕЧАНИЕ! Прежде чем двигаться дальше, сделайте себе одолжение, сохранив копию текущего .eslintrc.json файла, так как следующая команда уничтожит (воссоздаст) этот файл.

Чтобы создать новый .eslintrc.json файл, запустите:

Вам будет задан ряд вопросов, на которые я отвечу, нажав Enter для выбора значения по умолчанию, кроме формата , который я выбираю JSON (вместо JavaScript ).

В дополнение к созданию .eslintrc.json файла это также добавит «eslint-plugin-react»: «^7.29.2» атрибут devDependencies в package.json файл. 3

Команда npm init @eslint/config уничтожает существующий .eslintrc.json файл, поэтому вам придется вручную добавить обратно любые «rules» или другие параметры JSON, которые вы хотите сохранить.
В этом случае я добавляю обратно те правила, которые были в исходном файле .eslintrc.json .
Результат такой, как показано ниже.

Теперь, когда я открываю VS Code, вместо ошибки появляются два предупреждения, что и является желаемым результатом.

Здорово! Но подождите — к сожалению, оказывается, есть ложка дегтя. Проблема в том, что когда я запускаю npm start проект в веб-браузере и нажимаю F12 , в консоли появляются две ошибки.
Сообщения об ошибках:

  • Uncaught ReferenceError: process is not defined , а также
  • Line 0: Parsing error: ImportDeclaration should appear when the mode is ES6 and in the module context .

К счастью, я уже выкладывал решение этой проблемы, а именно:
Обновите все npm пакеты до их последних версий .
Раздел ниже немного краток, поэтому, если вы хотите больше плоти на костях, посетите этот другой ответ .

Обновите все npm пакеты до последних версий

Рассмотрите возможность обновления всех npm пакетов до их последних версий.
Цель состоит в том, чтобы уменьшить риск возникновения конфликтов версий. В этом ответе также содержится
совет обновить все пакеты .

A. Глобальная установка npm-check-updates

В командной строке запустите:

B. Обновление package.json , чтобы содержать последние версии

Следующая команда запишет последние номера версий пакетов в ваш файл package.json :

Вот как это выглядит в Windows 10:

C. Установите последние версии

В командной строке запустите:

D. Проверьте наличие ошибок в браузере и/или в терминале

В командной строке запустите:

И браузер, и терминал теперь отображают пять ошибок .

Дискомфортно, а?

Определенно да! – Но не теряй надежды! Просто закройте сервер ( Ctrl + C ) и пробуйте снова и снова.
Вчера, когда я получил эти ошибки, все, что мне нужно было сделать, это запустить npm start еще раз.
Сегодня пробовал запускать npm start еще 4-5 раз, но все равно получаю ошибки.
Поэтому я попробовал npm install && npm start дважды, и, наконец, он заработал без ошибок.
Не уверен что происходит. Может быть, должно пройти какое-то время, прежде чем это сработает?

Наконец -то в браузере нет ошибок .

И терминал говорит, что скомпилировано успешно!

Заключение

Выполнение описанных выше шагов помогло мне исправить ошибку в заголовке вопроса:
Ошибка синтаксического анализа: ключевое слово «импорт» зарезервировано .

Для проекта с настройками даже немного другими, 5 просто копипаст из .eslintrc.json файла выше вряд ли сработает.
Запуск npm init @eslint/config и обновление всех пакетов с большей вероятностью будет успешным.

использованная литература

1 У меня Windows 10, но я ожидаю, что все приведенные здесь команды будут одинаково хорошо работать как в Linux, так и в macOS.

2 A. Выполнение этой команды займет около 5-10 минут.
Б. Пока ваш исходный код не преобразован Babel, нет необходимости устанавливать @babel/eslint-parser . Обычного eslint должно быть достаточно. См. Когда следует использовать @babel/eslint-parser ?
Если вы используете TypeScript, вам понадобится @babel/eslint-parser .
Команда для установки:
npm install eslint @babel/core @babel/eslint-parser —save-dev
Команда npm init @eslint/config конфигурации должна использоваться так же, как и для обычного ( не [email protected] ) ESLint.

3 Атрибут «eslint-plugin-react» in package.json , похоже, не имеет большого значения.

4 Оба предупреждения по-прежнему отображаются в текстовом редакторе, как и должны.

5 Например, вы можете использовать Angular или Vue вместо React.

Источник

[eslint] Parsing error: The keyword ‘import’ is reserved #666

I’m getting this error on the first import statement of any js file on grommet@0.6.6 (since 0.6.7 is having issues with npm install )

The text was updated successfully, but these errors were encountered:

what is your node and npm version? es6 is enabled via babel that should be installed in both 0.6.6 and 0.6.7.

Was there any issues in the console when you ran npm install ? Also, which environment are you in? Windows, Linux?

I was able to reproduce your issue.

For some weird reason the .babelrc is not present in the init command anymore. This will be fixed in the upcoming 0.6.8.

In the meantime, can you create in the root of your project a .babelrc file with the following content?

That file is already present in my project. Using grommet@0.6.6 I ran grommet init sample-app and without changing any files, I get the error above. I’m using node v6.2.2, npm 3.9.5 on OS X 10.11.5. I’m using a local copy of eslint (not installed globally). I’m running Visual Studio Code 1.2.1 using the ESLint extension.

Thanks for the detailed explaination. Are you able to run gulp dist ? In other words do you get the same issue in the command line?

Also can you try to validate the suggestion in this issue

I was able to run gulp dist without any issues.

I’ve found that adding .eslintrc.json to the root directory solves the problem.

Adding the same rules into customEslintrc.json does not seem to have any effect.

The weird thing is that in the commad line works. It feels to me this is an IDE specific issue.

Well, thanks for helping me through this regardless. I’m not sure why it doesn’t work by default, but having the .eslintrc.json there works.

cool. closing the issue. welcome to grommet. we invite you to join our slack channel for live support.

© 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.

Источник

I am creating a NodeJS and MongoDB library for CRUD operations on APIs. I am trying to create an interface with Typescript for the url and database name, as follows:

but I get the following error:

interface IConfig {
  url: string
  name: string
}

export default IConfig

Parsing error: The keyword 'interface' is reserved

I am using standardjs as a linter, and this is my tsconfig file:

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Enable incremental compilation */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2020",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
    // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    // "rootDir": "./src",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "resolveJsonModule": true,                        /* Enable importing .json files */
    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

    /* Emit */
    "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
    "outDir": "./lib",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
    "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
    "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
    "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
    "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
    "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
    "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
    "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
    "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

Let me show you what dependencies I have already. I am using babel because jest required for compilation:

  "devDependencies": {
    "@babel/core": "~7.16.0",
    "@babel/preset-env": "~7.16.4",
    "@babel/preset-typescript": "~7.16.0",
    "@types/jest": "~27.0.3",
    "@types/mongodb": "^4.0.7",
    "@typescript-eslint/eslint-plugin": "^5.4.0",
    "@typescript-eslint/parser": "^5.4.0",
    "eslint": "^8.3.0",
    "eslint-plugin-jest": "^25.3.0",
    "jest": "~27.4.0",
    "standard": "~16.0.4",
    "test-jest": "~1.0.1",
    "ts-node": "~10.4.0"
  },
  "dependencies": {
    "mongodb": "~4.2.0",
    "typescript": "~4.5.2"
  },

I am sure is any error in my configuration, can you take a look and help me?

>Solution :

You should reconfigure your standardjs to use ts-standard instead.

interface is a «future reserved keyword» in Javascript. Javascript disallows its use as an identifier so that it can be used as a keyword (as it is in TypeScript). The TypeScript compiler removes the interface definition so it doesn’t appear in the compiled Javascript output.

From the standardjs front page FAQs:

standard supports the latest ECMAScript features. However, Flow and
TypeScript add new syntax to the language, so they are not supported
out-of-the-box.

For TypeScript, an official variant ts-standard is supported and
maintained that provides a very similar experience to standard.

In this ongoing series, I am putting together a Github Repository Template for my «Go To» front-end tech stack of Next.js, React, TypeScript etc. In part 1 of the series, I demonstrated how to set up the base Next.js app written in TypeScript. In this post, I will cover linting with ESLInt and auto formatting.

Code linting is the practice of scanning code for potential errors. It also can enforce code standards such as indents, when to use quotes, etc. Most IDEs (such as VSCode) will leverage linting to highlight syntax issues right in the IDE and even fix them. This saves a lot of time and is a great developer experience especially if you are on a team. For me, it is as important an aspect of software development as unit testing (covered in Part 3 of the series).

Just want the Code?
View the full changeset in this Github PR or check out the 0.0.2 release of the repository.

Prerequisites

  • If you are following along, please complete part 1 of the series. I am immediately picking up where that post left off.
  • I am using VSCode for my IDE and several parts of this post refer to VSCode specific things. If you are not using VSCode, I highly recommend it. After years of using Sublime, Atom, WebStorm, I feel like VSCode «just works».

Installing ESLint

First, locally install the ESlint dependency to our project.

npm install --save-dev eslint

Next, I need to initialize ESLint and install the Airbnb presets which is a great starting point for our linting rules

eslint --init

Follow the prompts to:

  • select «❯ Use a popular style guide»
  • select «Airbnb» as the base
  • Enter, yes you are using React
  • Finally, allow the initializer to save the config file
    This will likely prompt to install some additional dependencies

This will generate a file in the project root eslintrc.json that contains only:

{
    "extends": "airbnb"
}

We will need to modify this file shortly to extend ESLint to support TypeScript.

The airbnb presets are handy and will include everything we need including support for React Hooks, etc.

Next, modify our package.json to include a linting command.

  "scripts": {
     ...
    "lint": "eslint . --ext .ts,.tsx",
     ...
  },

This will programmatically run the local ESLint dependency against all files with extensions .ts or .tsx.

Running the following in the command line:

npm run lint

give us the error:

error  Parsing error: The keyword 'interface' is reserved

This means we need to install some additional things for ESLint to understand TypeScript. The keyword «interface» was from me defining a type for our IndexPageProps. Since «interface» is a TypeScript specific syntax feature, we need ESLint to understand it.

//pages/index.tsx 
...
interface IndexProps { // This is the line eslint is failing on because it doesn't speak TS yet
  greeting: string
}
...

Installing ESLint TypeScript dependencies

Note: tslint used to be the preferred way to lint TypeScript for years but has been deprecated. TypeScript support for ESLint has come a long long way and I have been quite happy with it.

To install the TypeScript dev dependencies, simply run:

npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin

Next, I need to tell ESLint to use the plugin. Modify the eslintrc.json generated when initializing ESLint to look like:

{
    "extends": [
        "airbnb",
        "plugin:@typescript-eslint/recommended"
    ]
}

Now when running npm run lint, a bunch of formatting errors are produced. This is good! I’ll leave them for now and get auto-format-on save to magically clean up most of them for me in the next steps.

Screen Shot 2020-07-15 at 3.21.18 PM.png

Auto Formatting

I’ll leverage VSCode’s settings to automatically clean these issues up.

In your project root, create or modify the .vscode/settings.json file. Here is mine currently for comparison sake.

{
    "files.exclude": {
      ".git/": true,
      "node_modules/": false,
      ".next/": false
    },
    "search.exclude": {
      "**/node_modules": true,
      "**/.next": true
    },

    // Personally I like 80 for readability but enforce 100
    "editor.rulers": [80, 100, 120],
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    }
  }

The critical directive to Auto Format on save is:

    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    }

Open up the pages/index.tsx file in VSCode and notice all the ESLint errors highlighted. Mine looks like a sea of red:
Screen Shot 2020-07-15 at 3.51.50 PM.png

Now, hitting save, most of our errors go away!
If I run npm run lint, I will see a far shorter list.
The critical remaining error needing attention is the React sytnax error.

  14:5   error    JSX not allowed in files with extension '.tsx'         react/jsx-filename-extension"

I need to tell ESLint it is OK to allow React’s JSX syntax in files other than those with the .jsx extension. I also need to tell ESLint to understand module extension ending in ts or tsx. This can be resolved by adding a rules directive to the eslintrc.config

{
  "extends": [
    "airbnb",
    "plugin:@typescript-eslint/recommended"
  ],
  "rules": {
    "react/jsx-filename-extension": [1, { "extensions": [".tsx"] }],
    "import/extensions": [
      "error",
      "ignorePackages",
        {
          "js": "never",
          "jsx": "never",
          "ts": "never",
          "tsx": "never"
        }
    ]
   },

  "settings": {
    "import/resolver": {
      "node": {
        "extensions": [".ts", ".tsx"]
      }
    }
  }
}

Aside from the line length warning, all of the ESLint errors are gone. For now I will ignore the unused variable warning.

Screen Shot 2020-07-15 at 4.21.47 PM.png

Screen Shot 2020-07-15 at 4.21.33 PM.png

Closing Thoughts

At this point the Github Template repository contains a Next.js application written in TypeScript that obeys airbnb formatting rules without any errors. That might be a good starting point for most people, but in the next post, I will get Jest Testing set up. If you are following along, you can view the full PR for this changeset or check out the 0.0.2 release of the repository.

Discussion Topic

I didn’t leverage Prettier in this post. I’m unclear any more if Prettier is needed. Feel free to post in the comments your feelings on Prettier.
Note: If you find yourself needing to run ESLint in a mixed TypeScript and Javascript environment, see my previous hashnode post on the topic.

Image Credit: «Strawberries in boxes» by Government of Prince Edward Island is licensed under CC BY-NC-ND 2.0

0. Prerequisites

If the server is running, close it by hitting
Ctrl+C.

I strongly recommend uninstalling any global installations of
ESLint.
To see what global packages are installed, in the command line run:
1

npm list --global --depth 0

If ESLint is globally installed, uninstall by running:

npm uninstall eslint --global

To correctly install ESLint into your local project, I recommend
performing the following two steps.

  1. Locally install ESLint.

  2. Create a functioning .eslintrc.json file.

As it turns out, you will also need to do a third step.

  1. Update all npm packages to their latest versions.

1. Locally install ESLint

To locally install ESLint, run:
2

npm install eslint --save-dev

This will add

  ,
  "devDependencies": {
    "eslint": "^7.32.0"
  }

at the end of package.json.

2. Create a .eslintrc.json file that works

NOTE! Before moving on, do yourself a favor by saving a copy of your
current .eslintrc.json file, as the next command will destroy
(recreate) that file.

To create a new .eslintrc.json file, run:

npm init @eslint/config

You will be asked a number of questions, to which I answer by pressing
Enter to choose the default, except for the format
which I choose to be JSON (instead of JavaScript).

Configuring ESLint

In addition to creating the .eslintrc.json file, this will also add
the "eslint-plugin-react": "^7.29.2" attribute under
devDependencies to the package.json file.
3

The command npm init @eslint/config destroys the existing
.eslintrc.json file, so you will have to manually add back any
"rules" or other JSON settings that you want to keep.
In this case, I add back the rules that were in the original
.eslintrc.json.
The result is as below.

.eslintrc.json :

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "no-unused-vars": [
      "warn",
      {
        "argsIgnorePattern": "^_",
        "varsIgnorePattern": "^_"
      }
    ]
  }
}

Now when I open VS Code, instead of an error there are two warnings,
which is exactly the desired outcome.

VS Code now displaying two warnings but no errors

Great! But wait – unfortunately there turns out to be a fly in the
ointment.
The problem is that, when I now run npm start to open the project in
the web browser and hit F12, two errors show up in the
console.
The error messages are:

  • Uncaught ReferenceError: process is not defined, and
  • Line 0: Parsing error: ImportDeclaration should appear when the mode is ES6 and in the module context.

Luckily, I have already posted a solution to this problem, namely:
Update all npm packages to their latest versions.
The section below is a bit succinct, so if you want more flesh on the
bones, go visit that other answer.

Update all npm packages to their latest versions

Consider updating all npm packages to their latest versions.
The purpose is to decrease the risk of getting version conflicts.
The advice to update all packages has also been put forth in
this answer.

A. Globally install npm-check-updates

In the command line, run:

npm install --global npm-check-updates

B. Update package.json to contain the latest versions

The following command will write the latest package version numbers to
your package.json:

npm-check-updates --upgrade

Here is what it looks like in Windows 10:

Upgrading package.json

C. Install the latest versions

In the command line, run:

npm install

D. Check for errors in the browser and/or in the terminal

In the command line, run:

npm start

Both the browser and the terminal now displays five errors.

Discomforting, eh?

Yes definitely! – But don’t give up hope!
Just close the server (Ctrl+C) and try it over
and over again.
Yesterday when I got these errors, all I needed to do was to run
npm start one more time.
Today I tried runningnpm start 4-5 more times, but still got the
errors.
So I tried npm install && npm start twice, and finally it
ran without errors.
Not sure what is going on. Maybe some time has to pass before it works?

Finally there are no errors in the browser.

NO errors in the web browser!

And the terminal says Compiled successfully!

The terminal says: 'Compiled successfully!'

Yay!
4

Conclusion

Following the steps above helped me remedy the error in the question
title:
Parsing error: The keyword ‘import’ is reserved.

For a project with settings even slightly different,5 just
copy-pasting from the .eslintrc.json file above is unlikely to
work.
Running npm init @eslint/config and upgrading all packages is more
likely to be successful.

A note about deleting package-lock.json and node_modules

I wholeheartedly embrace a frequent use of the npm install command.
As soon as there is a change to package.json or any other
configuration file – such as .eslintrc.json – the npm install
command should immediately be run.

By contrast, I have never ever seen anything gained by deleting the
package-lock.json file and/or the node_modules directory.
6

So my recommendation is: don’t delete any file or directory,
just run npm install.

References

  • npm – get a list of globally installed packages
  • Installation of ESLint using npm
  • Start using @eslint/config in your project
  • When should I use @babel/eslint-parser?
  • Update all npm packages to their latest versions
  • Update all current packages to their lastest versions
  • npm-check-updates – documentation

1 I am on Windows 10, but I expect all the commands
provided here to work just as fine on both Linux and macOS.

2
A. Expect this command to take about 5-10 minutes to complete.
B. As long as your source code is not transformed by Babel,
there is no reason to install @babel/eslint-parser.
Just normal eslint should be enough.
See When should I use @babel/eslint-parser?
If you are using TypeScript, then you will need
@babel/eslint-parser.
The command to install is:
npm install eslint @babel/core @babel/eslint-parser --save-dev
The npm init @eslint/config configuration command should be used
in the same way as for the normal (non[email protected]) ESLint.

3 The "eslint-plugin-react" attribute in package.json
does not seem to be of much relevance though.

4 The two warnings still show up in the text editor –
just as they should.

5
For example, you might be using Angular or Vue instead of React.

6 Every time you delete node_modules, you will pay a
penalty cost of 5-10 minutes of your precious time.

Понравилась статья? Поделить с друзьями:
  • Eslint parsing error import and export may appear only with sourcetype module
  • Eslint optional chaining parsing error unexpected token
  • Eslint npm error
  • Esl4550ro ошибка i20
  • Esia1 код ошибки