Eslint parsing error import and export may appear only with sourcetype module

error Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’ #10397 Comments Tell us about your environment Fedora release 28 (Twenty Eight) npm 6.0.0 node v8.4.0 eslint v4.19.1 What parser (default, Babel-ESLint, etc.) are you using? default Please show your full configuration: What did you do? Please include the actual source code […]

Содержание

  1. error Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’ #10397
  2. Comments
  3. Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’ #462
  4. Comments
  5. This comment has been minimized.
  6. SyntaxError: ‘import’ и ‘export’ могут появляться только с ‘sourceType: module’ — Подождите, что?
  7. 7 ответов
  8. main.js
  9. Тестовое задание
  10. Тестовый HTML файл
  11. Import and export may appear only with sourcetype module, no import or export statements exist #11560
  12. Comments
  13. ParseError: ‘import’ and ‘export’ may appear only with ‘sourceType: module’ #157
  14. Comments

error Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’ #10397

Tell us about your environment
Fedora release 28 (Twenty Eight)
npm 6.0.0
node v8.4.0
eslint v4.19.1

What parser (default, Babel-ESLint, etc.) are you using?
default
Please show your full configuration:

What did you do? Please include the actual source code causing the issue, as well as the command that you used to run ESLint.

What did you expect to happen?
I thought the linter would report problems w/ my use of semicolons.

What actually happened? Please include the actual, raw output from ESLint.
It reported that it could not parse ‘import’ and ‘export’ due to my configuration.
action@localhost learning-eslint] $ npx eslint ./*.js

/home/action/src/my-stuff/learning/learning-eslint/index.js
1:1 error Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’

/home/action/src/my-stuff/learning/learning-eslint/module-a.js
1:1 error Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’

/home/action/src/my-stuff/learning/learning-eslint/module-b.js
1:1 error Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’

✖ 3 problems (3 errors, 0 warnings)

I changed my configuration to the following:

Now eslint explains that my config is invalid.:

From what I’ve read «sourceType» is an older configuration key that is no longer used in .eslintrc.

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

Источник

Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’ #462

I get this error since the most recent update. is it possible there this is missing somewhere in the package?

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

Are you using import or export ? If so, what is your config file? And, how are you using ESLint (installed in your project, globally, or using the version packaged with linter-eslint ), and what version of ESLint are you using?

My first guess is that you need to add

to your config file.

yes thank you, that solved the issue! 👍

My eslint config is:

and I’m using the packaged version.

We recently upgraded the packaged version from ESLint 1.x to 2.x , which had some breaking changes in the way configurations should be written. Check out ESLint’s migration docs for more details.

HI just a question on es lint. what is the standard way of setting it up? just install the package from atom or setting up es lint locally for each and every project.

HI just a question on es lint. what is the standard way of setting it up?

just install the package from atom or setting up es lint locally for each and every project.

This package is only meant to be a wrapper around ESLint, you should be setting it up in projects so:

  • Others working on the project get the same linting configuration
  • When you come back to the project later, you don’t have to figure out why your code has suddenly started showing errors when it was «fine» before. at least until you update your lint configuration.

I’m locking this issue as the original report has been resolved.

Источник

SyntaxError: ‘import’ и ‘export’ могут появляться только с ‘sourceType: module’ — Подождите, что?

Итак, рассмотрим следующие два файла:

Мне жаль, что? Что это за ошибка? Что я делаю неправильно?

7 ответов

ESLint изначально не поддерживает это, потому что это противоречит спецификации. Но если вы используете анализатор babel-eslint, то внутри вашего конфигурационного файла eslint вы можете сделать это:

Старые версии Babel пришли со всем из коробки. В более новой версии вам необходимо установить какие-либо плагины, которые вам нужны. Во-первых, вам нужно установить предустановку ES2015.

Затем вам нужно сообщить babelify, чтобы использовать установленный вами пресет.

Для правильного компиляции кода es2015-реагирования вы должны установить некоторые модули узлов:

  1. npm установить -g браузеру

в вашем каталоге приложений:

  1. npm установить браузеру —save-dev
  2. npm install babelify —save-dev
  3. npm install babel-preset-es2015 —save-dev
  4. npm install babel-preset-stage-0 —save-dev

npm install babel-preset-react —save-dev Затем создайте задачу gulp:

В каталоге. /public/dest/javascripts вы найдете скомпилированный файл es5 app.js.

По какой-то причине, babelify 8.0.0 не работал для меня ни с предложениями es2015, ни с env. Тем не менее, по состоянию на esmify 2018-07-10, то esmify плагин от mattdesl сделал работу для меня. Мой тестовый пример заключался в экспорте Spinner из spin.js в качестве глобального окна. Мой пример репо находится здесь; основные данные следуют.

main.js

Тестовое задание

В пустом каталоге:

и принять все значения по умолчанию, затем:

Тестовый HTML файл

При загрузке он отображает счетчик в центре страницы.

Примечание. Я не являюсь аффилированным лицом с mattdesl или esmify.

Источник

Import and export may appear only with sourcetype module, no import or export statements exist #11560

Tell us about your environment

  • ESLint Version: 3.12.0
  • Node Version:
  • npm Version:

What parser (default, Babel-ESLint, etc.) are you using? default

Please show your full configuration:

What did you do? Please include the actual source code causing the issue, as well as the command that you used to run ESLint.

This is a strange one. I added an import statement briefly, which I opted to remove due to sketchy browser support for es6 modules. Ran eslint one time via grunt, got the aforementioned error, which is expected behavior due to my config not having the sourcetype modules entry. This is not the problem.

The problem is that after removing the import line, eslint continues to grumble about that specific file trying to import. There is no import statement. Even with an entirely empty file it still errors. Grepped against the entire project, no import or export statements exist anywhere. At all. My only guess is that it must have cached some faulty reference somewhere, although I have no idea where. May possibly be an upstream issue with gruntify-eslint, although I could not find any specific details or evidence that rules out either that package or this one.

What did you expect to happen?

Expected that the linter will lint the literal file as is.

**What actually happened? **

Linter sticks on “Import and export may only appear with sourcetype module”. Seems to be holding some memory reference, as no import or export statements exist anywhere in the project.

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

Источник

ParseError: ‘import’ and ‘export’ may appear only with ‘sourceType: module’ #157

I updated babelify to 7.0.2 and now it throws this error:

Working with 6.4.0.
Do you maybe have any ideas?

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

You upgraded to babelify 7.0, which uses the new babel 6.0, and you’re missing options. Please read the README.

Totally appreciate the help @zertosh.

@sent1nel : Please share solution! Same issue and don’t see what option we are missing. Appreciated.

I too am seeing this problem after updating to Babel 6. @zertosh you have said See README in several answers to this, but yet I cant find anything in the README that specifically states which options we need to provide to avoid this issue. Can you update the README there and put something like NOTE: If you are seeing this error (. ) this is why and here is how to solve it. All the searches I am seeing on google indicate some option is not sent to Babel 6, yet at least from what I have found so far, my webpack includes the es2015, react and state-1/23 options in the loader section of my webpack. I am also including all the correct dependencies in my package.json file. So any pointers to what we need to do would be of HUGE help to many of us that have this problem. Also, what README are you referring to? I looked through the page about migrating from Babel 5 to Babel 6. maybe I am looking at the wrong README?

If people open new issues with their current configurations and what features they want, I’d be more than happy to tell them what’s missing. I don’t know how else to help.

This is what I needed to do to fix this error:

npm install —save-dev babel-preset-es2015

gulpfile.js :
package.json :

MFW people say RTFM and they think they are helping just because some people randomly solve their problems alone after they read the insult.

Sorry @gaboom, that was sarcasm. A colleague of mine fixed this by using preset es2015, the README doesn’t contain an upgrade guide.

Thanks for this @baptistebriel I updated and have been having this issue all night!

Источник

Итак, рассмотрим следующие два файла:

app.js

import Game       from './game/game';
import React      from 'react';
import ReactDOM   from 'react-dom';

export default (absPath) => {
  let gameElement = document.getElementById("container");

  if (gameElement !== null) {
      ReactDOM.render(
          <Game mainPath={absPath} />,
          gameElement
      );
  }
}

index.js

import App from './src/app';

gulpfile.js

var gulp        = require('gulp');
var source      = require('vinyl-source-stream');
var browserify  = require('browserify');
var babelify    = require("babelify");
var watch       = require('gulp-watch');

gulp.task('make:game', function(){
  return browserify({
    entries: [
      'index.js'
    ]
  })
  .transform('babelify')
  .bundle()
  .pipe(source('index.js'))
  .pipe(gulp.dest('app/'));
});

Ошибка:

gulp make:game
[13:09:48] Using gulpfile ~/Documents/ice-cream/gulpfile.js
[13:09:48] Starting 'make:game'...

events.js:154
      throw er; // Unhandled 'error' event
      ^
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'

Мне жаль, что? Что это за ошибка? Что я делаю неправильно?

13 окт. 2016, в 21:29

Поделиться

Источник

7 ответов

Старые версии Babel пришли со всем из коробки. В более новой версии вам необходимо установить какие-либо плагины, которые вам нужны. Во-первых, вам нужно установить предустановку ES2015.

npm install babel-preset-es2015 --save-dev

Затем вам нужно сообщить babelify, чтобы использовать установленный вами пресет.

return browserify({ ... })
  .transform(babelify.configure({
    presets: ["es2015"]
  }))
  ...

Источник

Mike Cluck
13 окт. 2016, в 19:25

Поделиться

Для правильного компиляции кода es2015-реагирования вы должны установить некоторые модули узлов:

глобально

  1. npm установить -g браузеру

в вашем каталоге приложений:

  1. npm установить браузеру —save-dev
  2. npm install babelify —save-dev
  3. npm install babel-preset-es2015 —save-dev
  4. npm install babel-preset-stage-0 —save-dev
  5. npm install babel-preset-react —save-dev Затем создайте задачу gulp:

    var browserify = require("browserify");
    var babelify = require("babelify");
    
    gulp.task('es6-compile', function() {
      browserify({ debug: true })
        .transform(babelify.configure({ presets: ["es2015","react", "stage-0"] }))
        .require("./public/src/javascripts/app.js", { entry: true })
        .bundle()
        .pipe(gulp.dest('./public/dest/javascripts'));
    });
    

    В каталоге. /public/dest/javascripts вы найдете скомпилированный файл es5 app.js.

Red Efire
28 дек. 2016, в 13:39

Поделиться

По какой-то причине, babelify 8.0.0 не работал для меня ни с предложениями es2015, ни с env. Тем не менее, по состоянию на esmify 2018-07-10, то esmify плагин от mattdesl сделал работу для меня. Мой тестовый пример заключался в экспорте Spinner из spin.js в качестве глобального окна. Мой пример репо находится здесь; основные данные следуют.

main.js

import {Spinner} from 'spin.js';
window.Spinner = Spinner;

Тестовое задание

В пустом каталоге:

npm init

и принять все значения по умолчанию, затем:

npm install --save spin.js
npm install --save-dev browserify esmify
npx browserify -p esmify main.js -o main-packed.js

Тестовый HTML файл

<html><head>
    <link rel="stylesheet" href="node_modules/spin.js/spin.css" />
    <script src="main-packed.js"></script>    <!-- <== the browserify output -->
</head>
<body>
    <div id="x"></div>
    <script>
    var target = document.getElementById('x');
    var spin = new Spinner().spin(target);
    </script>
</body></html>

При загрузке он отображает счетчик в центре страницы.

Примечание. Я не являюсь аффилированным лицом с mattdesl или esmify.

cxw
04 сен. 2018, в 15:43

Поделиться

В .eslintrc вам может потребоваться указать параметры парсера, например:

{
"rules": {
    "indent": [
        2,
        4
    ],
    "linebreak-style": [
        2,
        "unix"
    ],
    "semi": [
        2,
        "always"
    ]
},
"env": {
    "es6": true,
    "browser": true,
    "node": true,
    "mocha": true
},
"extends": "eslint:recommended",
"parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
        "jsx": true
    }
}

}

Пожалуйста, ознакомьтесь с руководством по документации от Eslint.

Stefan Ciprian Hotoleanu
04 апр. 2019, в 11:56

Поделиться

в моем случае я использовал экспорт вместо экспорта.

изменить экспорт на экспорт.

saigopi
30 сен. 2018, в 05:27

Поделиться

Эта ошибка может быть вызвана не включением плагина tsify для компиляции typescript в задачу gulp.

Пример

    var tsify = require('tsify');

    return browserify({ ... })
      .plugin(tsify)
      .transform(babelify.configure({
        presets: ["es2015"]
      }))
      ...

См. установку и использование здесь:
https://www.npmjs.com/package/tsify

Stuart Bentley
07 фев. 2017, в 12:35

Поделиться

Ещё вопросы

  • 0Все переключается на стиль переключения
  • 0Предпочтительный выбор и визуальный разделитель в Symfony 2
  • 1как установить sbt прокси в windows
  • 0Как сделать MYSQL-запрос на выбор из двух таблиц на основе долготы, широты и радиуса?
  • 0ожидание завершения работы службы http angularJS перед началом следующей итерации цикла
  • 0Как это можно изменить, чтобы показать 2 видео?
  • 1Как сделать сериализацию с рекурсивным обходом?
  • 0HTML CSS — почему это место становится неразборчивым в мобильных телефонах
  • 12 односвязных пересечения списка
  • 0Symfony перенаправить для входа через контроллер
  • 1Node.js Выполнить после построчного чтения
  • 1Используя карту с queue.put ()?
  • 0получение выбранного значения для списка выбора в угловом виде из $ firebaseArray ()
  • 1убить сервер узла после тестирования gitlab
  • 0reCaptcha не проверяет
  • 1Android AudioRecord фильтр диапазона частот
  • 1Существует ли свободный способ выполнения критериев запросов в Fluent Nhibernate?
  • 0C ++, оператор valgrind new (без знака int)
  • 0ng-show не работает angular.js
  • 1Как поставить еще одну кнопку в окне быстрого поиска Android?
  • 0JQuery: получить выбор внутри строки таблицы
  • 0Подсветка ввода с высотой значения
  • 1Базовый класс из Windows Service
  • 0Найдите символ в заданной позиции в строке
  • 0Intellisense: аргумент типа «HWND» несовместим с параметром типа «rawData :: HWND»
  • 2Python получает имя контейнера Docker изнутри контейнера Docker
  • 0Анимация «высота» Jquery на дне
  • 1Java с плавающей точкой в IEEE-754 шестнадцатеричной?
  • 0Mysql два, где условие на общую сумму один столбец
  • 0Почему мой метод результата JSON возвращает ошибку ответа (500) [duplicate]
  • 1проверка БД, если записи существуют только в течение 13 месяцев
  • 1Моя страница JSP не перенаправляет на Myservlet, используя форму
  • 1Проблемы с загрузкой случайного изображения при нажатии кнопки
  • 0HTML таблица с всплывающим javascript
  • 0$ (document.body) .css не работает
  • 1Сохранение и восстановление состояния в Android
  • 1Обновление двухсторонней привязки данных между C # и XAML
  • 1Тестирование аудио файла с использованием C #
  • 1Как динамически создать новый фрейм данных из итерации по нескольким значениям?
  • 0Javascript с Twittera typeahead.js разрушает макет моей формы
  • 0Использование ссылок для доступа к объектам класса C ++
  • 1Разница между двумя последовательностями моделей кера последовательностей (с и без RepeatVector)
  • 0Как использовать JavaScript, возвращаемый сокращенными частями AngularJS
  • 1ContainsKey из HashMap не работает с пользовательским классом в качестве ключа
  • 1Доступно ли гео-фехтование с полигонами и динамическими объектами на Android?
  • 0Mysql, создать вид из 2 таблиц [дубликата]
  • 0Изменение массива зависит от установленного / снятого флажка
  • 1Поменять слова
  • 1Ищите Wildcard (‘<‘, ‘>’), посчитайте его и получите позицию в java
  • 0Я хочу расширить строку в таблице?

Сообщество Overcoder

When I run the command browserify ./js/test1.js -o build.js in the terminal to bundle some js files into one, it throws the error message like ParseError: ‘import’ and ‘export’ may appear only with ‘sourceType: module’. This article will tell you how to fix it using babel to transcompile the js file source code to ES 2015 syntax.

1. How To Fix ParseError: ‘import’ and ‘export’ may appear only with ‘sourceType: module’.

1.1 The Reason Of The Error.

  1. Below is the detailed error message.
    PS D:Workdev2qa.com-example-codePythonExampleProjecthtmlbrowserify-example> browserify ./js/test1.js -o build.js
    
    D:Workdev2qa.com-example-codePythonExampleProjecthtmlbrowserify-examplejstest1.js:1
    import helloFromTest2, { moduleName } from "./test2.js";
    ^
    ParseError: 'import' and 'export' may appear only with 'sourceType: module'
  2. The reason for this error is that Browserify does not support your javascript source code syntax in the file test1.js. The js code syntax maybe ES6 + style.
  3. So you should use babel to transcompile the source code to the downgrade syntax such as es2015 that Browserify supports.

2. How To Use Babel To Transcompile JavaScript Code To ES2015.

2.1 Install Babel Modules.

  1. Babel can be used to translate your ES6+ syntax javascript source code to lower version javascript code that can be used in most older version web browsers.
  2. Open a terminal and run the command npm init to create a package.json file in the current folder.
  3. Run the command npm install –save-dev @babel/core @babel/cli @babel/preset-env in the terminal to install the @babel/core, @babel/cli, and @babel/preset-env plugin modules.
  4. You can run the command npm list @babel/core, npm list @babel/cli, and npm list @babel/preset-env in the terminal to confirm the module installation.
  5. You can also see the above babel plugin modules in the project’s package.json file also like below. This is because of the –save-dev parameter when you install them.
    {
      "name": "browserify",
      "version": "1.0.0",
      "main": "index.js",
      "scripts": {
        "test": "echo "Error: no test specified" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "description": "",
      "devDependencies": {
        "@babel/cli": "^7.17.10",
        "@babel/core": "^7.18.2",
        "@babel/preset-env": "^7.18.2"
      }
    }

2.2 Create Babel Configure File.

  1. Create a babel configuration file babel.config.json in the project folder.
  2. Add the below JSON source code in the file babel.config.json.
    {
        "presets": [
          [
            "@babel/preset-env",
            {
              /*
                Define the targets web browsers.
                You can ignore this settings for all web browsers.
    
                "targets": {
                "edge": "17",
                "firefox": "60",
                "chrome": "67",
                "safari": "11.1"
              },
              */
              "useBuiltIns": "usage",
              "corejs": "3.6.5"
            }
          ]
        ]
      }

2.3 Run Babel Command To Transcompile JavaScript Source Files Into One.

    1. In the terminal, run the command ./node_modules/.bin/babel js –out-dir lib in the project folder.
      > ./node_modules/.bin/babel js --out-dir lib
      Successfully compiled 2 files with Babel (394ms).
    2. The above command will create a lib folder in the current project folder and transcompile all the javascript files in js folder to the lib folder.
      ├─js
      │  ├─test1.js
      │  └─test2.js
      ├─lib
      │  ├─test1.js
      │  └─test2.js
    3. Open the file lib/test1.js and lib/test2.js in a text editor, you will find the javascript source code is compatible with the older web browsers.
    4. Now when you run the command browserify ./lib/test1.js -o build.js, you may encounter another error, you can read the article How To Fix Error: Can’t walk dependency graph: Cannot find module from When Run Browserify to learn how to fix it.
    5. Now you can run the command browserify ./lib/test1.js -o build.js successfully in the terminal.

Created new simple project with one file:

    import React from 'react';
    import { render } from 'react-dom';
    import { Router, browserHistory } from 'react-router';

    render((
        <Router history={browserHistory} routes={routes}>
        </Router>
    ), document.getElementById('root'));

created simple .eslintrc with the help eslint —init:

    {
        "env": {
            "es6": true,
            "node": true,
            "browser": true
        },
        "extends": "eslint:recommended",
        "ecmaFeatures": {
            "jsx": true,
            "experimentalObjectRestSpread": true
        },
        "plugins": [
            "react"
        ],
        "rules": {
            "no-console": 0,
            "indent": [
                2,
                4
            ],
            "quotes": [
                2,
                "single"
            ],
            "semi": [
                2,
                "always"
            ]
        }
    }

enabled esLint settings in IDEA and got the error:

Error:(1, 1) ESLint: Parsing error: ‘import’ and ‘export’ may appear only with ‘sourceType: module’

archived due to age
question

You need to add sourceType: "module" to your config. There is no way for us to identify automatically what’s a script and what’s a module, so you have to provide that information in config file. For more details look in the documentation

thanks!
thats fixed one but another one appears

Error:(1, 8) ESLint: ‘React’ is defined but never used (no-unused-vars)
Error:(3, 10) ESLint: ‘Router’ is defined but never used (no-unused-vars)

but React used internally and Router used as jsx tag

<Router history={browserHistory} routes={routes}>

Could you help, please?

You need to include eslint-plugin-react. ESLint doesn’t support React on it’s own, you need plugin to handle that.

it’s installed by eslint —init command and included in .eslintrc

        "plugins": [
            "react"
        ],

You’ll need to enable appropriate rules from eslint-plugin-react package. Not sure which ones, you’ll have to look at the repository for instructions. Also we have gitter channel for questions like that here: https://gitter.im/eslint/eslint

ESLint: The Essential Facts About Essential Front End Tools

Recently, I’ve been getting more involved in front-end development. The more I do, the more my mind and my soul get lost in its chaotic world. Even a simple To–Do–List app can easily require a bunch of tools—ESLint, Babel, Webpack, to name a few—and packages just to get started.

Fortunately, there’re many starter kits out there so we don’t have to do everything from the ground up. With them, everything is already set up so we can start writing the first line of code right away. It saves time on repetitive, boring tasks, which can be great for experienced developers.

However, this benefit comes with a price for beginners. Since everything works out of the box, it seems like magic, and they might not know what’s really happening under the hood, which is important to understand at some level. Although the learning curve is not as steep as others—try to compare with some tools you’ve been learning and using, you’ll get what I mean—in this chaotic world, we need a survival guide for the journey.

This series will cover fundamental tools of front-end development and what essentials we need to know about them. This will allow us to rule the tools instead of being controlled by them.

In it, we’ll focus on the developer experience of each one of these tools. So the goal of this series is to act as a survival guide and to give a high-level overview of each tool, not to serve as documentation.

What will be included:

  • ESLint <- We are here
  • Babel
  • Webpack
  • Flow
  • TypesScript
  • Jest.

Enough of a preface, let’s get started with the first tool: ESLint.

What is ESLint and Why should we use it?

ESLint is, as the name implies, a linter for ECMAScript. And, the definition of a linter is:

a machine for removing the short fibers from cotton seeds after ginning.

Although code and cotton seeds don’t have any relationship, regardless of code or cotton seeds, a linter will help make things cleaner and more consistent. We don’t want to see the code like this:

const count = 1;
const message  =  "Hello, ESLint"
    count += 1

It both looks ugly and has a mistake. Here’s when ESLint steps in to help with that. Instead of letting the error be dumped out to the browser console when we run the code, ESLint will catch it as we’re typing (well not really: we’ll need editor or IDE extensions for this, which will be covered later).

Of course, this error isn’t difficult to figure out, but wouldn’t it be nicer to have an assistant reminding us every time we’re about to make a mistake and perhaps auto-correcting it for us? Although ESLint can’t catch all kinds of errors, it at least spares us some effort so we can spend time on other things that matter and need human attention.

How does ESLint work?

Now that we know what ESLint is and why we need it, let’s go a bit deeper and check out how it works. In essence, we can break it down to three big steps.

Parser

The code that we write is nothing more than a sequence of characters. However, this sequence isn’t just random characters: they need to follow a set of rules or conventions that is the grammar forming a language.

For a human, going from reading text or code to understanding it conceptually takes us little effort. For a computer, this is much more difficult to accomplish. For example:

const tool = 'ESLint' // 1
  const  tool  =  "ESLint" // 2

As we read the two lines above, we immediately know that they are identical, and can be read as «there’s a constant named tool with the value of ESLint». For a computer, which doesn’t understand the meaning, these two lines look quite different. As a result, if we feed in raw code to ESLint, it’s nearly impossible to do anything.

When things get complicated and hard to communicate—think of how we can have a computer to understand what we do—abstraction can be an escape. By abstracting a thing, we hide all unnecessary details, reduce noise, and keep everyone on the same page, which eases the communication. In the above example, one space or two spaces don’t matter, neither do single quotes or double quotes.

In other words, that’s what a parser does. It converts raw code to an Abstract Syntax Tree (AST), and this AST is used as the medium for lint rules to base on. There are still many steps a parser need to do in order to create an AST—if you’re interested in learning more about how an AST is generated, this tutorial has a good overview.

Rules

The next step in the process is to run the AST through a list of rules. A rule is a logic of how to figure out potential existing issues in the code from the AST. Issues here aren’t necessarily syntactic or semantic errors, but might be stylistic ones as well. The output given out from a rule will include some useful information for later use like lines of code, positions, and informative messages about the issue.

In addition to catching issues, a rule can even auto-correct code if possible. For example, when no-multi-spaces is applied to the code above, it will trim all redundant spaces, which makes the code look clean and consistent.

  const  tool  =  "ESLint" // 2
// becomes
const tool = "ESLint" // 2

In different scenarios, a rule can be used at different levels—opted-out, warning only, or strict error—and have various options, which gives us control on how to use the rule.

Result

Here comes the end of the process. With the output from a rule, it’s just the matter of how we display it in a human friendly manner, thanks to all the useful information we mentioned earlier. Then from the result, we can quickly point out the issue, where it is, and make a fix, or maybe not.

Integration

ESLint can be used as a standalone tool with its robust CLI, but that’s a bare-bones way to use ESLint. We don’t want to type in a command every time we want to lint code, especially in a development environment. The solution for this is to integrate ESLint into our development environment so we can write code and see issues caught by ESLint all in one place.

This kind of integration comes from extensions specific to IDEs or editors. These extensions require ESLint to work since they run ESLint behind the scene—no wonder that we still need to install ESLint along with them, they are nothing without ESLint. This principle applies to other IDE or editor extensions we are using daily.

Remember the output from a rule we talked above? An extension will use it to display in the IDE or editor. How exactly the output is displayed depends on how the extension is implemented and how the IDE or editor is open to its extensions. Some extensions also take advantage of the abilities of issue correction from rules to change code on save if we enable it.

Configuration

Configuration is the main power that gives versatility to a tool. ESLint is not different from that, except it has the most comprehensive configuration among other tools. In general, we need a file or a place to put the configuration, and there’s a couple of options of us.

All of them boil down to two main ways: either we have a separate configuration file for each tool, or we bundle them all in package.json.  .eslintrc.js is one of the files that ESLint will be looking for its configuration, and also the one with the highest priority.

The next thing we need to know about configuration is its hierarchy and cascading behavior. Thanks to these features, we don’t need to have a configuration file in every single folder in the project.

If a configuration file doesn’t exist in a folder, ESLint simply looks up the folder’s parent for one until it can’t find one. Then it’ll fall back to the user–wide default configuration in ~/.eslintrc. Otherwise, the configuration file will add up or override the ones at upper levels.

There is, however, a special tweak on this. If we specify root: true in a configuration file, the lookup will stop at that file instead of going up like before. Besides, ESLint will use that configuration file as the root configuration, and all child configurations will be based on this one.

This is not only limited to ESLint — these things are common for other tools. Let’s talk about ESLint specific configuration.

Parser

The role of the parser in ESLint has been discussed above. By default, ESLint uses Espree as its parser. We can change this parser to another compatible one like babel-eslint or @typescript-eslint/parser if we use Babel or Typescript, respectively.

To configure the parser, we use parserOptions. Among options supported by Espree, here are some we often use and need to pay attention to:

  • ecmaVersion

We need to specify the appropriate ECMA version to features we want to use. For example, if emcaVersion: 5, the code below will give some errors.

```javascript
let a = [1, 2, 3, 4] // error due to `let` keyword
var b = [...a, 5] // error due to spread syntax
```

The parser can’t parse the code because both the let keyword and spread syntax were just introduced in ES6. Changing emcaVersion to 6 or above will simply resolve the errors.

  • sourceType

Nowadays, we mostly write everything in modules, then bundle them together. So this option, most of the time, should be module.

Another value we can use—as well as the default—is script. The difference is whether we can use JS modules or not, i.e., use import and export keyword. The next time we get this error message Parsing error: 'import' and 'export' may appear only with 'sourceType: module', we know where to look.

  • ecmaFeatures.jsx

There might be additional ES features we want to use, for example JSX syntax. We use ecmaFeatures.jsx: true to enable this feature. Note that, JSX support from Espree isn’t the same as JSX in React. If we want React specific JSX, we should use eslint-plugin-react for better results.

If we use another parser, these options are more or less the same. Some might have fewer options, and others might have more, but they’re all defined under parserOptions.

Environment

It depends on where the code is running: there are different predefined global variables. We have window, document in the browser, for example. It would be irritating if the no-undef rule is enabled, and ESLint keeps telling us window or document is not defined.

The env option is here to help. By specifying a list of environments, ESLint will know about global variables in these environments, and let us use them without a word.

There’s a special environment we need to note, es6. It’ll implicitly set parserOptions.ecmaVersion to 6, and enable all ES6 features except for modules which we still need to use parserOptions.sourceType: "module" separately.

Having the same configuration for rules over and over again across different projects might be tiresome. Luckily, we can reuse a configuration, and only override rules as needed with extends. We call this type of config shareable configs, and ESLint already has two for us: eslint:recommended and eslint:all.

Conventionally, ESLint’s shareable configs have eslint-config prefix so we can easily find them via NPM with eslint-config keyword. Among hundreds of results, there’re some popular ones, like eslint-config-airbnb or eslint-config-google, you name it.

Out of the box, ESLint has a bunch of rules to serve different purposes from possible errors, best practices, ES6 to stylistic issues. Moreover, to supercharge its ability, ESLint has a great number of 3rd-party rules provided by almost a thousand plugins. Similar to shareable configs, ESLint’s plugins are prefixed with eslint-plugin, and are available on NPM with the eslint-plugin keyword.

A plugin defines a set of new rules, and in most cases it exposes its own handy configs. For example, the eslint-plugin-react gives us two shareable configs, eslint-plugin-react:recommended and eslint-plugin-react:all just like eslint:recommended and eslint:all. To use one of them, we need to, firstly, define the plugin name, and secondly extend the config.

{
  plugins: ["react"],
  extends: "plugin:react/recommended"
}

// Note that we need to prefix the config by `plugin:react`

One common question to ask is what plugins or configs to use. While it largely depends on our needs, we can use Awesome ESLint as a reference to find useful plugins as well as configs.

Prettier

We’re almost there — we’ve almost gotten to the end. Last but not least, we’ll discuss a popular pair of ESLint, Prettier. In short, Prettier is an opinionated code formatter. Though Prettier can be used alone, integrating it to ESLint enhances the experience a lot, and eslint-plugin-prettier does this job.

The difference between using Prettier alone and using Prettier with ESLint can be summarized to code formatting as an issue. Instead of giving format issues separately, running Prettier with ESLint will treat format issues just like other issues. However, these issues are always fixable, which is equivalent to formatting the code.

That’s how eslint-plugin-prettier works. It runs Prettier, as a rule, behind the scene and compares the code before and after being run through Prettier. Finally, it reports differences as individual ESLint issues. To fix these issues, the plugin simply uses the formatted code from Prettier.

To have this integration, we need to install both prettier and eslint-plugin-prettier. eslint-plugin-prettier also comes with eslint-plugin-prettier:recommended config—which extends eslint-config-prettier. Therefore we also need to install eslint-config-prettier to use it.

{
  "plugins": ["prettier"],
  "extends": "plugin:prettier/recommended"
}

Conclusion

Code linters or formatters have become the de facto standard in software development in general, and ESLint, specifically, in front-end development.

Its benefits go far beyond what it does technically, as it helps developers focus on more important matters. Thanks to delegating code styling to a machine, we can avoid opinionated styles on code review, and use that time instead for more meaningful code review. Code quality also benefits, and we get more consistent and less error-prone code.

This article was originally posted at my blog.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Eslint optional chaining parsing error unexpected token
  • Eslint npm error
  • Esl4550ro ошибка i20
  • Esia1 код ошибки
  • Esia 910313 код ошибки