[ESLint] eslint-plugin-import で、特定のフォルダをまたいだimportを防ぐ
ESLint のプラグインのひとつに、 import
/ export
周辺の記法について設定することができる、 eslint-plugin-import というものがあります。
このプラグインで設定できるルールのひとつに、 no-restricted-paths という項目があります。
これは、例えば Atomic Design のような atoms / molecules / organisms がというコンポーネントレイヤーが存在し、フォルダも同様に分けられているときに、「atomsではmoleculesのフォルダに入っているファイルをimportできない」というルールを設定することができます。
以下のようなディレクトリを考えます。
components/
atoms/
molecules/
organisms/
.eslintrc.cjs
package.json
package-lock.json
まずは npm i -D eslint-plugin-import
でインストールします。
.eslintrc.cjs
に次のような設定項目を追加します。
module.exports = { plugins: ['import'], // 追加 rules: { // 追加 'import/no-restricted-paths': [ 'error', { zones: [ { from: './components/atoms', target: './components/molecules', message: 'Cannot import molecule components from atom components.', }, ], }, ], }, }
この状態でプロジェクト内の ESLint を実行した場合に、実際に import している箇所でエラーが出るようになっていたらOKです。