Sub topic 12
Enforcing boundaries with ESLint
This chapter assumes you can write React components and hooks in TypeScript. It also assumes you know what a feature module and its index.ts public API are, and that you have set up a path alias such as @/. You should be able to read an ESLint configuration file.
Why conventions need enforcement
A feature module has a public API: the names exported from its index.ts. That API only protects you if other code actually uses it. Nothing in TypeScript or the bundler stops a developer from writing this:
import { CartSummary } from "@/features/cart/components/internal/CartSummary";The import works, the tests pass, and review may not catch it. Six months later, someone renames CartSummary, and three other features break. The boundary existed only in people's heads.
A lint rule turns the convention into an error that appears in the editor and in continuous integration (CI). ESLint is a tool that reads your source files and reports code that breaks configured rules. It is a good fit for import boundaries because imports are plain text statements that it can match against patterns.
This chapter covers three kinds of rule:
- Blocking deep imports into a feature's internals.
- Blocking imports in the wrong direction between layers.
- Blocking one feature from depending on another feature's internals.
The deep-import rule
ESLint's built-in no-restricted-imports rule reports imports whose path matches a pattern you list. The following flat-config file (ESLint's eslint.config.js format) forbids any aliased path with two segments after features:
// eslint.config.js
export default [
{
files: ["src/**/*.{ts,tsx}"],
rules: {
"no-restricted-imports": [
"error",
{
patterns: [
{
group: ["@/features/*/*"],
message: "Import from the feature's index file instead of its internals.",
},
],
},
],
},
},
];The group entries use gitignore-style matching. @/features/*/* matches @/features/cart/components/CartList. It does not match @/features/cart, because that path has only one segment after features. So the public import is allowed and the deep import is an error.
What the pattern does not catch
This rule is simple, and it has gaps you should know about.
- Relative imports.
../../cart/components/CartListdoes not start with@/, so the pattern does not match. Either ban relative imports that climb out of a feature (for example../../*), or add patterns for them. - Imports inside the same feature. Files inside
cartoften need to import each other, and some of those imports use the alias. The pattern above would flag@/features/cart/apiinside the cart feature. The fix is to use relative imports inside a feature and the alias across features, then scope the rule so it applies only outside the feature (see the next section). - Dynamic imports and
require.no-restricted-importscovers staticimportstatements and, in recent versions,import()expressions in many setups. Check your ESLint version, and test with a deliberately bad import rather than assuming. - Re-exports.
export { x } from "@/features/cart/api"is also checked, but only if the rule version you run handles export-from statements. Test that case too.
Scoping rules per feature
A single global rule cannot say "the cart feature may import its own internals but the orders feature may not." Flat config lets you attach rules to file globs. You can generate one block per feature, so each feature forbids deep imports into every other feature.
// eslint.config.js
const features = ["cart", "orders", "settings"];
const featureBlocks = features.map((name) => {
const others = features.filter((other) => other !== name);
return {
files: [`src/features/${name}/**/*.{ts,tsx}`],
rules: {
"no-restricted-imports": [
"error",
{
patterns: others.map((other) => ({
group: [`@/features/${other}/*`],
message: `Import from "@/features/${other}" only. Its internals are private.`,
})),
},
],
},
};
});
export default [
{
files: ["src/**/*.{ts,tsx}"],
rules: {
"no-restricted-imports": [
"error",
{
patterns: [
{
group: ["@/features/*/*"],
message: "Import from the feature's index file instead of its internals.",
},
],
},
],
},
},
...featureBlocks,
];Flat config applies blocks in order, and a later block that sets the same rule replaces the earlier setting for matching files. That replacement is why each per-feature block lists its own patterns in full. It also means any rule you want to keep globally must be repeated in the per-feature blocks. The generated blocks above forbid access to other features' internals. They allow the feature's own internals, because the feature's own name is excluded from others.
Adding a feature means adding its name to the features array. If you forget, the new feature is protected by the global rule but not by a per-feature block. That is still safe, because the global rule is the stricter default here. The downside is that the new feature then cannot import its own files by alias, so it must use relative imports. This is a good reason to keep intra-feature imports relative.
Enforcing layer direction
In the layering from earlier chapters, dependencies point one way: pages may import features, features may import shared code, and shared code imports nothing from features. The reverse direction is what causes tangled code. A shared Button that imports from features/cart makes the whole shared layer depend on one feature.
You can express this with the same rule, applied to the shared folder:
// eslint.config.js (additional block)
export default [
{
files: ["src/shared/**/*.{ts,tsx}"],
rules: {
"no-restricted-imports": [
"error",
{
patterns: [
{
group: ["@/features/*", "@/app/*"],
message: "Shared code must not depend on features or app wiring.",
},
],
},
],
},
},
];Here the group @/features/* matches even the public entry point, because shared code should not import from a feature at all. In a real configuration this block goes in the same array as the others, after the global block.
The direction table below summarizes what to forbid.
| Importing file in | May import from | Must not import from |
|---|---|---|
| `app/` | `features/`, `shared/` | nothing special |
| `features/x/` | its own files, `shared/`, other features' index files | other features' internals, `app/` |
| `shared/` | `shared/` only | `features/`, `app/` |
Features that depend on each other
If cart imports from orders and orders imports from cart, you have a circular dependency. It might work at runtime today, but it often causes undefined imports during module loading and makes both features impossible to move or test alone. The no-restricted-imports rule cannot detect cycles. The import/no-cycle rule from eslint-plugin-import can:
// eslint.config.js
import importPlugin from "eslint-plugin-import";
export default [
{
files: ["src/**/*.{ts,tsx}"],
plugins: { import: importPlugin },
settings: {
"import/resolver": {
typescript: { project: "./tsconfig.json" },
},
},
rules: {
"import/no-cycle": "error",
},
},
];The typescript resolver (from eslint-import-resolver-typescript) lets the plugin understand your @/ alias. Without it, the plugin cannot resolve aliased paths and silently finds no cycles through them. This is a common reason a cycle rule seems to pass on code that clearly has a cycle.
When you find a cycle between two features, there are three usual fixes:
- Move the shared piece into
shared/. - Pass the needed data or callback in as a prop from a page, so the features never import each other.
- Merge the two features if they are really one.
Rolling out rules on an existing codebase
Turning on a boundary rule in a codebase with hundreds of violations produces a wall of errors that nobody fixes. Two approaches work better.
- Start with warnings. Set the rule to
"warn", track the count, and switch to"error"when it reaches zero. A warning does not fail CI, so the count may drift upward unless someone watches it. - Scope by folder. Enable the strict rule only for features that are already migrated, using the per-feature blocks. Add each feature to the list as you clean it up. New code in migrated features is protected right away, and old code is left alone.
Run the linter in CI as a required check. A rule that only runs in editors is a suggestion.
// package.json scripts, shown as a JavaScript object for clarity
const scripts = {
lint: "eslint .",
"lint:ci": "eslint . --max-warnings 0",
};
console.log(scripts);The --max-warnings 0 flag makes any warning fail the run, which lets you use "warn" locally while keeping CI strict once the count hits zero.
Verifying a rule works
After writing a rule, prove it fires. Add a deliberately bad import to a scratch file, run npx eslint src, and confirm that you get the expected error message. Then delete the file. A rule that never fires looks identical to a rule that is misconfigured, so this check is the only way to tell them apart.
Exercise
Your orders feature contains import { formatPrice } from "@/features/cart/utils/formatPrice". The global rule with group: ["@/features/*/*"] already reports it. Name two ways to resolve the violation without disabling the rule, and say which is better if formatPrice is also needed by a third feature.
Show answer
First, export formatPrice from @/features/cart/index.ts and import it from @/features/cart. Second, move formatPrice into shared/lib and import it from there. When a third feature also needs it, moving it to shared/lib is better, because otherwise several features depend on the cart feature for an unrelated utility, which invites cycles and couples features that have no real relationship.
Exercise
You enable import/no-cycle but it reports nothing, even though features/a and features/b import each other through @/ paths. What is the most likely cause, and how do you fix it?
Show answer
The plugin cannot resolve the @/ alias, so it ignores those imports. Install eslint-import-resolver-typescript and set settings["import/resolver"].typescript to point at your tsconfig.json. Then verify with a deliberate cycle that the rule now reports it.