javascript - 如何使用 ESLint 通过特定文件夹的绝对路径限制模块的导入
问题描述
我有文件夹结构:
my_project
|------ modules.private
| |------ broker_module
| |------ BrokerModule.js
|
|------ src
| |------ AppService
| |------ AppService.js
|
| |------ Components
| |------ ScreenLogin.js
|
我需要限制所有区域从 modules.private 的绝对导入,除了“./src/AppService”。
案例没有错误。Linted 文件是 './src/AppService/AppService.js':
// NO ERROR
import { BrokerModule } from 'broker_module';
有错误的情况。Linted 文件是 './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',
},
推荐阅读
- python - 除了 fig.show() 还有其他功能可以显示图形吗?
- smartcard - 尝试使用 ICAO 9303 BAC 从 National eID (T=0) 读取数据
- amazon-web-services - 使用 AWS CDK 部署后如何执行数据库架构迁移?
- javascript - 即使组件未呈现,Vue.js也会出错
- javascript - TypeError:room.map 不是函数:ReactJS
- openssl - Ubuntu WSL2 开发上的 Openssl 安装和设置
- vb.net - 在字符串中找到返回单词
- python - 在 django 中调用 Python 对象时超出了最大递归深度
- python-3.x - Python跳过输出中没有任何起始行的行
- reactjs - 如何在反应js中显示svg图标而不是鼠标光标?