问题描述
我具有文件夹结构:
my_project
|------ modules.private
| |------ broker_module
| |------ brokerModule.js
|
|------ src
| |------ AppService
| |------ AppService.js
|
| |------ Components
| |------ ScreenLogin.js
|
而且我需要限制所有模块从“ modules.private”的绝对导入,除了“ ./src/AppService”。
无错误。插入的文件为“ ./src/AppService/AppService.js”:
// NO ERROR
import { brokerModule } from 'broker_module';
大小写错误。插入的文件为“ ./src/componets/ScreenLogin.js”:
// Error: can not import broker_module to restricted zone
import { brokerModule } from 'broker_module';
我已经尝试过https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-restricted-paths.md,并制定了如下规则:
// the rule is interpreted like you can not import to target zone './src/components' from 'from': 'broker_module'
'rules': {
'import/no-restricted-paths': [
'error',{
'zones': [
{ 'target': './src/components','from': 'broker_module' },],}
],},
但是它不能使用绝对路径。而且,我尝试了此ESLint规则https://eslint.org/docs/rules/no-restricted-imports的更多内容:
'no-restricted-imports': ["error",{
"paths": ["broker_module"],}]
它有效,但适用于所有区域。这意味着在我从broker_module导入实体的所有地方都会出现错误。您能告诉我如何使用eslint-plugin-import / no-restricted-paths写入绝对路径的受限区域,或者在使用ESLint / no-restricted-imports限制仅导入的情况下用于特定区域,而不是所有文件夹。
解决方法
我已经找到了如何限制特定区域的决定。它可以通过两种方式实现:
- 在您的.eslintrc.js文件中写入带有覆盖的全局模式:
'rules': {
'no-restricted-imports': ['error',{
'paths': ['vtb.broker2.api.0'],}],'import/no-restricted-paths': [
'error',{
'zones': [
{ 'target': './src/vtb','from': './src/vtb/api.1' },],}
],},'overrides': [
{
'files': ['./src/vtb/api.1/*.ts','./src/vtb/api.1/**/*.ts'],'rules': {
'no-restricted-imports': 'off',}
],
2。根据官方文档https://eslint.org/docs/user-guide/configuring#configuration-cascading-and-hierarchy可能会覆盖仅在要更改规则的文件夹目录的父目录中创建的规则,请制作一个仅适用于此文件夹的文件.eslintrc.js。例如取消规则:
'import/no-restricted-paths': [
'off',