owned mediaウェブ制作に役立つコンテンツを発信中!

webpackでESLintが使える環境を構築してみる

最終更新日: Update!!
前回記事「webpackでStylelintが使える環境を構築してみる」では、Stylelintを使ってCSSの構文チェックを行いました。今回はJavaScriptやTypeScriptの構文チェックをESLintを使って実施できるようにwebpackの環境を構築していきます。   webpackにおいてESLintを使う上でTypeScriptやJavaScriptをバンドルする作業が必要になります。過去記事ではwebpackでTypeScriptのコンパイルやBabelを使ったJavaScriptのトランスパイルに関する記事をまとめており、今回はそれを準備している前提で進めていますので、下記のリンクからご参考ください。 【参考記事】 webpackでTypeScriptの自動コンパイル環境を作成してみる webpackでBabelを使ったJavaScriptトランスパイルの環境構築   それではまず必要なパッケージをインストールしていきます。下記のようにコマンドを実行していきます。まずは「eslint」本体に、ESLintをwebpackで使う際に必要となる「eslint-webpack-plugin」のパッケージをインストールします。
$ npm install --save-dev eslint eslint-webpack-plugin
  また、下記のようなパースエラーが発生する際の対応として、TypeScript用のESLint関連のモジュールも合わせてインストールしておきます。
error Parsing error: Unexpected token
.....

$ npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser
  インストールが完了するとpackage.jsonにパッケージが追加されているのが確認できます。これで準備は完了ですので、引き続きwebpackの設定を行なっていきます。 【package.json】
{
  .......
  "devDependencies": {
    .......
    "@typescript-eslint/eslint-plugin": "^4.24.0",
    "@typescript-eslint/parser": "^4.24.0",
    "eslint": "^7.26.0",
    "eslint-webpack-plugin": "^2.5.4",
    .......
  },
  .......
}
  Stylelintと同様、ESLintの設定ファイルである「.eslintrc.js」が必要になります。この設定ファイルのフォーマットですが、JavaScriptでオブジェクトとして記述する形以外でもjsonでもいいですし、YAML形式でも使えるそうです。今回はこのような構成で、.eslintrc.jsをルートディレクトリ直下に配置しておきます。そしてESLint用のtsconfig.jsonである「tsconfig.eslint.json」も今回は合わせて用意しておきます。
node_modules
dist
┗(main.js)
src
┗ main.ts
.eslintrc.js
tsconfig.eslint.json
webpack.config.js
tsconfig.json
  それでは引き続きwebpackの設定をしていきます。ここではTypeScriptもしくはJavaScriptのコンパイルのみの内容となっていますが、過去記事で紹介している設定等も適宜必要に合わせて追加していきます。まずは「eslint-webpack-plugin」を読み込んでいき、そしてプラグインの設定を行うだけでESLintが使えるようになります。 【webpack.config.js】
const path = require('path');
const ESLintPlugin = require('eslint-webpack-plugin');
module.exports = {
  mode: 'development',
  devtool: 'source-map',
  entry: './src/main.ts',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js'
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader'
      },
      {
        test: /\.js$/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              presets: [ '@babel/preset-env' ]
            }
          }
        ]
      }
    ]
  },
  resolve: {
    extensions: [ '.ts', '.js', '.json' ]
  },
  plugins: [
    new ESLintPlugin({
      extensions: [ '.ts', '.js' ],
      exclude: 'node_modules'
    }),
  ]
}
  続いて、ESlint用のtsconfig.jsonにあたる「tsconfig.eslint.json」のファイルも設定していきます。下記のように、tsconfig.jsonを継承する形で、このあと作成するESLint用の設定ファイルである「.eslintrc.js」を読み込むように指定しておきます。 【tsconfig.eslint.json】
{
  "extends": "./tsconfig.json",
  "include": [
    "src/**/*.ts",
    ".eslintrc.js"
  ],
  "exclude": [
    "node_modules",
    "dist"
  ]
}
  最後にESLint用の設定ファイルである「.eslintrc.js」を作成していきます。今回はTypeScriptの場合とJavaScriptの場合でESLintの設定が異なるということもあり、フラグメント用の変数を作成し、その値によってJavaScript用の設定かTypeScript用の設定かを切り替えられるようになっています。 【.eslintrc.js】
const useTypeScript = true;

const lintEs = {
  env: {
    'browser': true,
    'jquery': true,
    'node': true,
    'es6': true
  },
  globals: {},
  parserOptions: {
    'sourceType': 'module',
    'ecmaVersion': 2015
  },
  rules: {
    'no-console': 'warn',
    'no-extra-semi': 'warn',
    'no-undef': 'warn',
    'quotes': [
      'warn', 'single'
    ],
    'space-before-blocks': [
      'warn', { 
        'functions': 'always' 
      }
    ] 
  }
};

const lintTs = {
  root: true,
  env: {
    es6: true,
    node: true,
  },
  parser: '@typescript-eslint/parser',
  parserOptions: {
    sourceType: 'module',
    ecmaVersion: 2019,
    tsconfigRootDir: __dirname,
    project: [ 
      './tsconfig.eslint.json' 
    ]
  },
  plugins: [
    '@typescript-eslint',
  ],
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
  ],
  rules: {
    'no-console': 'warn',
    'no-extra-semi': 'warn',
    'no-undef': 'warn',
    'quotes': [
      'warn', 'single'
    ],
    'space-before-blocks': [
      'warn', { 
        'functions': 'always' 
      }
    ],
  '@typescript-eslint/no-unsafe-call': 'warn',
  '@typescript-eslint/no-unsafe-member-access': 'warn',
  '@typescript-eslint/no-unsafe-return' : 'warn'
  },
};

module.exports = useTypeScript ? lintTs : lintEs;
  基本的な記述ルールは変わりませんが、JavaScriptとTypeScriptそれぞれに合わせた設定を行います。ルールについてはStylelint同様にかなりの数があるようですので、プラグインとして用意されたものを使った上で追加ルールを設定していくのが一般的なようですね。ルールの内容について詳しくは下記の公式ドキュメントをご参考ください。 【List of available rules - ESLint - Pluggable JavaScript linter】 https://eslint.org/docs/rules/   それでは早速ビルドして試してみます。上記では関数のブロック直前にスペースを入れることや、consoleへの出力を「warning」となるように設定していますので、実際に該当箇所が存在する場合には下記のように出力されることが確認できました。
WARNING in 
/Users/...../src/main.ts
19:13 warning Missing space before opening brace space-before-blocks
20:3 warning Unexpected console statement no-console
 
  今回はwebpackでESLintを導入する方法についてまとめてみました、ESLintも前回のStylelintと合わせて用いられることが多く、構文チェックを行うことでコーディングルールの統一に役立ちますね。ぜひ忘れず導入しておきたいですね! (参考にさせて頂いた記事) TypeScript + Node.jsプロジェクトにESLint + Prettierを導入する手順2020
  • はてなブックマーク
  • Pocket
  • Linkedin
  • Feedly

この記事を書いた人

Twitter

sponserd

    keyword search

    recent posts

    • Twitter
    • Github
    contact usscroll to top
      • Facebook
      • Twitter
      • Github
      • Instagram