sherif icon indicating copy to clipboard operation
sherif copied to clipboard

explicit-imports rule

Open kayandra opened this issue 8 months ago • 4 comments

Hello @QuiiBz I would like to suggest a new rule called explicit-imports this will ensure that packages imported in package that are not standard packages should be defined in package.json

kayandra avatar Mar 24 '25 05:03 kayandra

Could you explain a bit more what you mean by standard packages?

QuiiBz avatar Jun 19 '25 16:06 QuiiBz

@QuiiBz sorry for the confusion. What I really meant is that in a monorepo every package should only be able to import modules it has explicitly declared in its own dependencies. If you hoist a dependency in one package, it shouldn’t become magically available in all the others.

For example, imagine this setup:

// packages/package-a/package.json
{
  "name": "package-a",
  "dependencies": {
    "lodash": "^4.17.21"
  }
}
// packages/package-b/package.json
{
  "name": "package-b",
  "dependencies": {
    // lodash is NOT listed here
  }
}

Even though Bun/Yarn/Nx/Pnpm might hoist lodash into the repo root, sherif should raise an error that package-b needs an explicit dependency.

// packages/package-b/src/index.ts
import _ from 'lodash';  // ❌ Sherif should compaling that lodash isn’t declared in package-b’s package.json

If package-b really needs lodash, it should add it to its own deps:

cd packages/package-b
bun add lodash

This way, every package’s imports remain explicit and self-contained.

kayandra avatar Jun 20 '25 18:06 kayandra

Thanks for the explanation, that makes sense. It's a rule that I've been wanting to add for a while, but it requires quite a bit of work. Sherif only reads package.json files and no source code today, and only parses JSON.

Rought overview of how that could work:

  • for each package in the monorepo
  • walk the directories recursively, ignore node_modules, dist, build, and any other .gitignore'ed folder
  • read the .ts, .tsx, js, jsx, cjs, mjs, cts, mts files
  • parse into an AST using OXC / SWC
  • get all the import statements (also the dynamic ones), filter out relative/absolute paths
  • push the filtered imports into a Set for this package
  • diff the imports set with the package dependencies

QuiiBz avatar Jun 21 '25 06:06 QuiiBz

Yes, this sounds like a good plan. I believe OXC would also be great for this.

Quick question, at what point do think that Sherif will start getting into biome/eslint territory?

kayandra avatar Jun 21 '25 09:06 kayandra