eslint no-restricted-imports - prevent an import from from path ending with pattern - eslint

According to the eslint no-restricted-imports documentation
When using the object form, you can also specify an array of
gitignore-style patterns:
"no-restricted-imports": ["error", {
"paths": ["import1", "import2"],
"patterns": ["import1/private/*", "import2/*", "!import2/good"] }]
(Emphasis mine)
What I'm trying to do is restrict imports from parent index files - as this is causing issues with cyclical dependencies (I am also using the import/no-cycle rule, but it makes sense to also explicitly use this rule.)
That is, I want to ban imports like:
import foo from "../..";
import bar from "../../..";
I also want to ban imports like:
import a from "../Components";
but not like
import b from "../Components/Foo";
I have tried using this rule:
'no-restricted-imports': [
'error',
{
patterns: [
'**/..',
'**/Components'
]
},
But this causes on errors on imports of:
import b from "../Components/Foo";
Is there a way to specify 'end of string' in a gitignore style pattern?

First, make sure you don't have set import/no-relative-parent-imports, or any ../ import would fail.
Second, if this really follows .gitignore rules, you cannot have rules for folders (like **/.. or **/Components).
Because, once you ignore a folder, any other rule for elements inside that folder would be ignored.
Try:
'no-restricted-imports': [
'error',
{
patterns: [
'**/../*',
'!**/../Components',
'**/../Components/*',
'!**/../Components/Foo',
]
},

Related

How to use no-restricted-imports to prevent any import file that starts with underline (_)

I'm trying to prevent any import from "private files" that are specified by prefixing them with an underscore.
As an example, I would like to prevent importing file patters as follows:
import {foo} from '_file';
import {foo} from './_file';
import {foo} from './dialog/_file';
import {foo} from '#alias_root/src/framework/dialog/_file';
To do so, I've used the following rules:
{
'no-restricted-imports': ['error', {
patterns: [{
group: ['_*'],
message: 'Import files starting with an underline are private',
}],
}],
}
Unfortunately this does not seem to catch all the cases I would like to prevent and I'm wondering what I'm missing or how to exactly use this rule.

ESlint override rule by nested directory

I want to disable rule for all files inside nested directory. I found examples only for exact path or by file extension. But it is not what I want.
We use it for shared config and don't know where this directory will be. We have many of them.
I'm trying config like this:
{
overrides: [
{
files: [
'**/test/**/*',
],
rules: {
"import/no-extraneous-dependencies": "off"
}
},
],
}
But glob like **/test/**/* and many others didn't not work.
Can someone help to reach this goal?
The above code should work.
How were you testing this? If it's an extension like VSCode you may need to refresh things to see latest definitions loaded.
If you are using a eslint service like esprint you will also need to restart it to grab latest definitions.
Caching
Make sure that eslint is not configured to cache results to avoid having to cache bust when debugging things. eslint docs
Here's an example for a react-native app with multiple overrides
module.exports = {
...baseConfig,
overrides: [
typescriptOverrides,
e2eOverrides,
themeOverrides,
{
files: ['**/*.style.js'],
rules: {
'sort-keys': [
'error',
'asc',
{
caseSensitive: true,
natural: true,
},
],
},
},
{
files: ['**/*.test.js'],
rules: {
'arrow-body-style': 'off',
},
},
],
};
Debugging the glob matcher
Run eslint in debug mode and see all the files being run example DEBUG=eslint:cli-engine npx eslint src/**/*.test.js
You can test your glob patterns by running a ls command. Example: ls ./src/**/*.test.js will either return all the files or 'no matches found'.

Expected 'multiple' syntax before 'single' syntax

I am trying to import files like this but getting error: Expected 'multiple' syntax before 'single' syntax
import { Component, Prop, Vue } from 'vue-property-decorator';
import { getModule } from 'vuex-module-decorators';
import { ApiException, IProduct, IProductCategory } from '#/services'; // error here
import { INavs } from '#/types';
Rule config:
'sort-imports': ['error', {
'ignoreCase': false,
'ignoreDeclarationSort': false,
'ignoreMemberSort': false,
'memberSyntaxSortOrder': ['none', 'all', 'multiple', 'single']
}]
import { ApiException, IProduct, IProductCategory } from '#/services'; is importing multiple (three) exports.
Both import { getModule } from 'vuex-module-decorators'; and import { INavs } from '#/types'; are only importing a single named export.
That error will go way if you move import { ApiException, IProduct, IProductCategory } up one line so it's above the single imports.
This is configured in your settings where it says 'memberSyntaxSortOrder': ['none', 'all', 'multiple', 'single'] because 'multiple' is listed before 'single'.
You can read more about it in the eslint documentation here https://eslint.org/docs/rules/sort-imports
Ran into this too looking for a CI solution for reordering multiple imports, since ESLint --fix only supports multiple members on a single line; i.e. autofixing unsupported when spread over multiple lines - e.g. from a low Prettier printWidth of ~80.
eslint-plugin-simple-import-sort works great, fixed the errors after amending config from the docs:
Make sure not to use other sorting rules at the same time:
[sort-imports]
[import/order]
To resolve this issue I'll recommend modifying your .eslintrc.json setting
"sort-imports": ["error", {
"ignoreCase": false,
"ignoreDeclarationSort": false,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"],
"allowSeparatedGroups": false // <-- Change this to true
}],
Which prevents you from reordering local imports and third party imports that are in different groups but violate the memberSyntaxSortOrder as earlier suggested

How using Vim alphabetically sort JS es6 imports

I use vim as IDE for typescript project.
import { FlightInfo } from './FlightInfo'
import { InfoBlockProps, InfoRowProps, INavigationFlightOfferDataProps } from './interfaces'
import { getDiscountData, formatDataByServicesType, selectAdministrationFee } from './functions'
Also, I use ts-lint rule for check sorting:
...
ordered-imports": [
true,
{
"import-sources-order": "lowercase-first",
"named-imports-order": "lowercase-first"
}
],
...
And get errors:
ERROR: 11:1 ordered-imports Import sources within a group must be alphabetized.
ERROR: 11:10 ordered-imports Named imports must be alphabetized.
ERROR: 12:1 ordered-imports Import sources within a group must be alphabetized.
ERROR: 12:10 ordered-imports Named imports must be alphabetized.
I am searching for a solution or plugin for fix this sorting errors.
In this situation, for me very well works ts-lint --fix -c ./ts-congig.json my-file.ts command.

Separating app and vendor css in Brunch

My Brunch template compiles all my code into app.js and all third party dependencies into vendor.js (a pretty standard approach). I'd like to do the same with CSS and it used to work but as I moved to using Bower something stopped working and I now get the following error:
Error: couldn't load config /path-to-root/config.coffee. SyntaxError: unexpected {
at Object.exports.loadConfig (/usr/local/share/npm/lib/node_modules/brunch/lib/helpers.js:448:15)
from a configuration file (config.cofee) that looks like this:
files:
javascripts:
joinTo:
'javascripts/app.js': /^app/
'javascripts/vendor.js': /^(bower_components|vendor)/
'test/javascripts/test-vendor.js': /^test(\/|\\)(?=vendor)/
stylesheets:
joinTo:
'stylesheets/app.css': /^app/
'stylesheets/vendor.css': /^(bower_components|vendor)/
If I instead just strip out the two lines for stylesheets and put this single line in its place it works without error:
'stylesheets/vendor.css': /^(app|bower_components|vendor)/
I've been sort of living with this but this is causing more and more problems and I'd like to get it sorted. Any help would be greatly appreciated.
In case the question comes up ... the version of brunch I'm using is 1.7.6.
I am baffled but I think Paul's suggestion that maybe a special character had gotten into the file seems likely. I now have it working with a configuration that appears to be identical to what was NOT working earlier. Here's the full configuration file:
sysPath = require 'path'
exports.config =
# See http://brunch.io/#documentation for documentation.
files:
javascripts:
joinTo:
'javascripts/app.js': /^app/
'javascripts/vendor.js': /^(bower_components|vendor)/
'test/javascripts/test-vendor.js': /^test(\/|\\)(?=vendor)/
stylesheets:
joinTo:
'stylesheets/app.css': /^app/
'stylesheets/vendor.css': /^(bower_components|vendor)/
templates:
precompile: true
root: 'templates'
joinTo: 'javascripts/app.js' : /^app/
modules:
addSourceURLs: true
# allow _ prefixed templates so partials work
conventions:
ignored: (path) ->
startsWith = (string, substring) ->
string.indexOf(substring, 0) is 0
sep = sysPath.sep
if path.indexOf("app#{sep}templates#{sep}") is 0
false
else
startsWith sysPath.basename(path), '_'
It's pretty weird but I had to do the following (add / at the end) for the same case
stylesheets: {
joinTo: {
'css/vendor.css': /^(vendor|bower_components)\//,
'css/styles.css': /^app\/css\//
}
}
I had the same problem as Ken. What solved it for me is just deleting the offending lines from the config.coffeefile and simply just re-typing them again from scratch. This ensures no hidden characters are present and makes the script running again.

Resources