ESLint是否存在仅允许从指定模块导入特定命名导出的规则?
Restricting @prisma/client imports to only Prisma and PrismaClient
Great question! You're right that no-restricted-imports feels like it's built for "allow all except X" scenarios, but you can repurpose it to enforce a "deny all except X" pattern using regex magic. Here's how to set it up:
Step 1: Update your ESLint config
Add this rule to your .eslintrc.json (or equivalent config file):
{ "rules": { "no-restricted-imports": [ "error", { "paths": [ { "name": "@prisma/client", "importNames": ["/^(?!Prisma$|PrismaClient$).+/"], "message": "Only Prisma and PrismaClient may be imported from @prisma/client." } ] } ] } }
How this works
The regex /^(?!Prisma$|PrismaClient$).+/ uses a negative lookahead to match any import name that is not exactly Prisma or PrismaClient. Here's the breakdown:
^and$ensure we match the entire import name (no partial matches)(?!Prisma$|PrismaClient$)excludes the two allowed names.+matches any other non-empty string
Example behavior
- ✅ Valid:
import { Prisma, PrismaClient } from '@prisma/client';(no error) - ❌ Invalid:
import { Airline, Airport } from '@prisma/client';(triggers error) - ❌ Invalid:
import { User } from '@prisma/client';(triggers error) - ❌ Invalid:
import { Prisma, User } from '@prisma/client';(triggers error becauseUseris restricted)
Notes
- This works in ESLint v6 and above, which supports regex patterns in
importNames. - If you need to allow additional imports later, just add them to the regex's negative lookahead. For example, to allow
PrismaPromise:/^(?!Prisma$|PrismaClient$|PrismaPromise$).+/
内容的提问来源于stack exchange,提问作者JamesJGoodwin
相关产品推荐
相关产品推荐

