molindo / eslint-config-molindo Goto Github PK
View Code? Open in Web Editor NEWESLint config that implements the Molindo styleguide and helps to catch errors
License: MIT License
ESLint config that implements the Molindo styleguide and helps to catch errors
License: MIT License
I was a bit unsure which of these patterns is preferable for a longer time:
function LinkButton({href, ...rest}) {
const Component = useMemo(() =>
function Link(props) {
return <a href={href} {...props} />
},
[href]
);
return <Button as={Component} {...rest} />
}
function LinkButton({href, ...rest}) {
return <Button as="a" href={href} {...rest} />
}
… the second one has the advantage that the component remains mounted for the lifetime of the component. I was concerned however about handling an unknown prop like href
within Button
.
After discovering react-polymorphic-types
I'm now largely in favour of the second approach. I'm not sure yet if it's worth linting for, but we could consider it.
I'd set allowAsProps
to true
in any case to not be too restrictive.
eslint-plugin-import now has support for alphabetical sorting: https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md#alphabetize-order-ascdescignore
This can be tricky: A variable defined with const
can be compiled via Babel to a regular var
and therefore a violation of this rule might not throw in a browser. However if this code isn't compiled and run directly with modern tools where const
is natively supported, a ReferenceError
will be thrown.
With the introduction of React Hooks I began to think about what the most readable React component looks like.
With classes we had different syntax for properties and methods:
class Button {
property = 'foo';
getProperty() {
return this.property;
}
}
If we write React components as functions I think it becomes a bit harder to see at a glance what are functions and what are properties, if you'd declare both of them with expressions.
const property = 'foo'
const getProperty = () => property;
In a reduced example this is usually not an issue, but a larger component might make this less obvious.
React components themself are also closely related to functions, therefore I think the function
keyword makes more sense for them. Also you can use the export
statement on the same line as the declaration, which isn't the case with expressions. Furthermore I think function
is semantically more correct to const
(is it a constant?).
Therefore I'd go for this in the future:
function Button(props) {
const property = 'foo';
function getProperty() {
return property;
}
// …
}
Arrow functions are only allowed for callbacks, potentially handling the topic of this
correctly there.
I propose these two new rules here:
"func-style": ["error", "declaration", {"allowArrowFunctions": false}],
"prefer-arrow-callback": "error",
Valid:
function declaration(foo) {
return foo;
}
useEffect(() => {
document.title = 'foo';
});
Invalid:
const expressionWithArrowFunction = foo => foo;
const expressionWithAnonymousFunction = function(foo) {
return foo;
};
useEffect(function () {
document.title = 'foo';
});
useEffect(function setDocumentTitle() {
document.title = 'foo';
});
Other advantages (from discussion below):
Note that prefer-arrow-callback
is auto-fixable, but func-style
can be codemodded.
The current resolver config needs a webpack config file which might not be available in every project. The only feature that we use from webpack is to provide src
as an additional module directory.
We could achieve this by using node as well:
"import/resolver": {
"node": {
"paths": [
"node_modules",
"src"
]
}
}
That would work in projects without webpack as well.
It often has false positives like:
t('questions.description', {
contact: (children) => (
<Link href="/contact">
<a>{children}</a>
</Link>
)
})
With the patterns we use to define React components this should usually not be an issue.
… and replace it with import/order
since eslint-plugin-import-order-autofix isn't maintained well.
The alternative doesn't have an auto fix option, but since all dependants already have the autofix applied, this shouldn't be a big deal.
This creates false positives when there are overloads.
E.g.:
import useQueryParamString from './useQueryParamString';
export default function useQueryParamNumber(
name: string,
required: true
): number;
export default function useQueryParamNumber(
name: string,
required?: false
): number | undefined;
export default function useQueryParamNumber(name: string, required?: any) {
const value = useQueryParamString(name, required);
return value ? parseFloat(value) : undefined;
}
In a subdirectory
src/utils/tests/subdir/something-test.js
I get this error:
import sinon from „sinon"
'sinon' should be listed in the project's dependencies, not devDependencies.
In the root level it works without problems:
src/utils/tests/semething-test.js
import sinon from „sinon“
This is because of:
'import/no-extraneous-dependencies': [
ERROR,
{
devDependencies: [
'webpack.config.js',
'**/__testUtils__/**/*.js',
'**/__tests__/*-test.js'
]
}
],
https://www.npmjs.com/package/eslint-plugin-sort-destructure-keys
This is the last puzzle piece for sorting props in React components. It also has autofix.
Very useful when refactoring from a class to a function component.
https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-this-in-sfc.md
Configure https://eslint.org/docs/rules/no-restricted-globals with https://www.npmjs.com/package/confusing-browser-globals.
Check if it works to have confusing-browser-globals
as a dependency. Otherwise copy-paste the list into the repo.
It seems like there's a way to get importing from dependencies to work by using require.resolve
: https://github.com/kripod/eslint-config/blob/master/packages/eslint-config-base/index.js
There are valid cases for this, especially with async/await. I think the lint rule doesn't help here anymore, as we're quite familiar with different iteration methods and this only creates noise.
No longer needed for the latest JSX transform in React 17
https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-useless-fragment.md
… with the option allowExpressions
for the mentioned TypeScript workaround.
… since import React from 'react';
is no longer necessary with the new JSX transform (available both in React 16 as well as React 17).
cy
Cypress
We already only permit function
declarations for components. With this rule, we could get auto fixing at least for React components.
Could be interesting to mirror the setting from react/jsx-sort-props
. However this isn't helpful as long as issues reported by the rule can't be fixed automatically.
Would be useful in order to support someRef = React.createRef()
.
E.g.:
*.config.js
(e.g. next.config.js
).*rc.js
(e.g. .eslintrc.js
)cypress/**/*.*
src/setupTests.js
*.spec.js
https://eslint.org/docs/rules/func-names
as-needed
looks good, but make sure that it allows for anonymous arrow function callbacks.
TypeScript has this special syntax:
/// <reference types="jest" />
We should configure spaced-comment
to allow this:
'spaced-comment': [
'error',
'always',
{
line: {
markers: ['/'],
exceptions: ['/']
}
}
]
… with:
{
"namedComponents": "function-declaration"
}
This provides auto fixing for a pattern we're already enforcing with func-style
.
The background is that react/sort-prop-types
currently doesn't work for TypeScript prop types.
If .tsx
files are exclusively used for React components, a workaround could be to be more strict in those files and apply typescript/member-ordering
there.
Note that this will have some false positives, but it might be a pragmatic solution.
I'm not sure if this is a good idea though. A lot of codebases use .tsx
for all TypeScript files, regardless if they contain JSX or not. When in doubt, we should maybe leave this turned off.
See the discussion in import-js/eslint-plugin-import#662 and filenames/match-exported
of https://www.npmjs.com/package/eslint-plugin-filenames.
However with the current story with peer dependencies it's a bit painful to add new plugins.
Related, it would be nice to ensure that imports match filenames.
This should be blocked by eslint/eslint#3458, however I just found this option on the CLI:
--resolve-plugins-relative-to path::String A folder where plugins should be
resolved from, CWD by default
Maybe with that we could work around the issue.
This is currently discussed in eslint-plugin-import issue #877 and could be helpful.
I think it's usually a good idea to favour iteration based on array methods (map
, filter
, …) but for/of can be handy if you need async/await or break
.
With e.g. https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/no-focused-tests.md
It would be great if this would also consider Cypress tests (i.e. it.only
). Since it's the same syntax, this might work OOTB.
The extension .e2e.{js,jsx,ts,tsx}
would be helpful. Cypress also introduced .cy.{js,jsx,ts,tsx}
recently with component tests.
… and use single quotes wherever possible.
Backticks should only be used where necessary. We could also consider prefer-template
for those cases.
I think there are valid cases where the code is easier to read if you have a lonely if/else.
E.g.
if (conditionA) {
...
} else {
if (conditionB) {
...
} else {
...
}
}
Code like this can be confusing:
const isValidEnterSubmit = isEnter && searchResults.length;
If there are results and you console.log(isValidEnterSubmit)
you might see a number like 12
as the last value in the condition is assigned to the variable. Explicit length checks like searchResults.length > 0
avoid this issue and is therefore preferred.
Also in JSX this is problematic:
<div>{searchResults.length && searchResults[0].title}</div>
This will render 0
if there are no results, as numbers are emitted to the DOM, but booleans are not.
Theres a rule for this in an external plugin, but I'd like to avoid adding yet another plugin – at least as long as consumers of this package have to install plugins separately.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.