DEV Community

Cover image for How to enforce folder boundaries with Eslint
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

How to enforce folder boundaries with Eslint

Hey folks!

Today I wanted to talk to you about Frontend Architecture and more specifially how you can enforce folder boundaries with Eslint - a tool we usually think is only for making sure we have correct amount of spaces.

Enjoy!

Problem

When a project grows, it is very easy to introduce unwanted cross module dependencies.

Such dependencies will make it much more difficult in the future to touch certain areas as making changes to one place will eventually affect other places.

In FE, a popular circular dependency is something like following:

components → composables → components
Enter fullscreen mode Exit fullscreen mode

Solution

One solution could be using Dependency Cruiser from my previous article but you can also utilize an Eslint rule that will warn you about these dependency issues in your IDE while you are writing code. We can add following config:

settings: {
  "boundaries/elements": [
    { type: "component", pattern: "components/*/*" },
    { type: "composables",    pattern: "composables/*" },
  ],
  "boundaries/files": [
    { pattern: "**/*.spec.js", category: "test" },
  ],
}
Enter fullscreen mode Exit fullscreen mode

(Elements -> Folder, Files -> Files)

Then, we can write rules:

"boundaries/dependencies": [2, {
  default: "disallow",
  policies: [
    { from: { element: { type: "component" } },
      allow: { to: { element: { type: "composable" } } } },
},
    { disallow: { to: { file: { categories: "test" } } },
      message: "Never import test files from {{ from.element.types.[0] }}s" },
  ],
}]
Enter fullscreen mode Exit fullscreen mode

So when we will try to import component inside composable we should get a following error:

src/composables/MyAwesomeComposable.ts
  1:22  error  There is no policy allowing dependencies from
         elements of type "component" to elements of type "composable"
         boundaries/dependencies

✖ 1 problem (1 error, 0 warnings)
Enter fullscreen mode Exit fullscreen mode

You can implement many more rules to enforce best practices and keep your FE architecture in place.

Let me know what other rules you are using to enforce good Architecture :)

Top comments (0)