This rule is useful in larger code bases to control dependencies between project modules. Rule allows to specify source file patterns and list of path patterns which should not be allowed.
For example project code has the directory layout like:
src/
client/
server/
common/
Directories client
, server
and common
represent code scopes:
client
- application UIserver
- server-side logiccommon
- shared constants and interfaces
In this setup imports between following directories should not be allowed:
client
->server
(something likeimport server from '../../server/myAPIServer'
)server
->client
(something likeimport Crux from '../../client/components/Crux'
)common
->client
common
->server
It may be implemented by adding the following rule configuration:
{
"forbidden-imports": [true, {
"client/**": ["server/**"],
"server/**": ["client/**"],
"common/**": ["client/**", "server/**"]
}]
}
yarn install -d tslint-forbidden-imports
- Add
node_modules/tslint-forbidden-imports/rules
torulesDirectory
parameter of yourtslint.json
. - Enable rule
forbidden-imports
and pass mapping"file pattern"
->["fordidden import patterns"...]
The pattern syntax may use any features supported by micromatch.
Supported import pattern types:
- Node package (i.e.
lodash
orui-*
) - GLOB file path relative to project root (i.e.
src/client/**
orplugins/*/src/ui/**
)
Library has support for placeholder replacement.
This rule will not allow imports between child directories of plugins
directory
{
'plugins/*/src/**': ['plugins/!(%0%)/**']
}
To run tests, just run yarn test
.
Project tests are based on test helper from tslint-microsoft-contrib.
- TSLint Custom Rules Development
- tslint-microsoft-contrib has a ton of well-tested rule examples