chore: 🦄 Add eslint-plugin-unicorn (#22883)

* 🦄 Add eslint-plugin-unicorn

* fix eslint errors

* fix eslint errors

* fix lint demo

* fix lint demo
This commit is contained in:
偏右 2020-04-03 15:02:11 +08:00 committed by GitHub
parent 1e5c527146
commit b369717181
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 54 additions and 56 deletions

View File

@ -19,7 +19,7 @@ function finalizeCompile() {
`{ version: '${packageInfo.version}' }`,
),
);
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log('Wrote version into lib/version/index.js');
// Build package.json version to lib/version/index.d.ts
@ -29,7 +29,7 @@ function finalizeCompile() {
versionDefPath,
`declare var _default: "${packageInfo.version}";\nexport default _default;\n`,
);
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log('Wrote version into lib/version/index.d.ts');
// Build a entry less file to dist/antd.less
@ -57,7 +57,7 @@ function buildThemeFile(theme, vars) {
`@import "../lib/style/${theme}.less";\n@import "../lib/style/components.less";`,
);
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log(`Built a entry less file to dist/antd.${theme}.less`);
// Build ${theme}.js: dist/${theme}-theme.js, for less-loader
@ -67,7 +67,7 @@ function buildThemeFile(theme, vars) {
`module.exports = ${JSON.stringify(vars, null, 2)};`,
);
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log(`Built a ${theme} theme js file to dist/${theme}-theme.js`);
}
@ -78,7 +78,7 @@ function finalizeDist() {
path.join(process.cwd(), 'dist', 'antd.less'),
'@import "../lib/style/index.less";\n@import "../lib/style/components.less";',
);
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log('Built a entry less file to dist/antd.less');
buildThemeFile('dark', darkVars);
buildThemeFile('compact', compactVars);

View File

@ -20,7 +20,7 @@ const eslintrc = {
},
},
parser: '@typescript-eslint/parser',
plugins: ['markdown', 'react', 'babel', 'jest', '@typescript-eslint', 'react-hooks'],
plugins: ['markdown', 'react', 'babel', 'jest', '@typescript-eslint', 'react-hooks', 'unicorn'],
// https://github.com/typescript-eslint/typescript-eslint/issues/46#issuecomment-470486034
overrides: [
{
@ -91,6 +91,10 @@ const eslintrc = {
'jest/no-test-callback': 0,
'jest/expect-expect': 0,
'react-hooks/rules-of-hooks': 2, // Checks rules of Hooks
"unicorn/better-regex": 2,
"unicorn/prefer-trim-start-end": 2,
"unicorn/expiring-todo-comments": 2,
"unicorn/no-abusive-eslint-disable": 2,
},
globals: {
gtag: true,

View File

@ -16,7 +16,7 @@ function isHidden(element: HTMLElement) {
function isNotGrey(color: string) {
// eslint-disable-next-line no-useless-escape
const match = (color || '').match(/rgba?\((\d*), (\d*), (\d*)(, [\.\d]*)?\)/);
const match = (color || '').match(/rgba?\((\d*), (\d*), (\d*)(, [\d.]*)?\)/);
if (match && match[1] && match[2] && match[3]) {
return !(match[1] === match[2] && match[2] === match[3]);
}
@ -76,7 +76,7 @@ export default class Wave extends React.Component<{ insertExtraNode?: boolean }>
waveColor !== '#ffffff' &&
waveColor !== 'rgb(255, 255, 255)' &&
isNotGrey(waveColor) &&
!/rgba\(\d*, \d*, \d*, 0\)/.test(waveColor) && // any transparent rgba color
!/rgba\((?:\d*, ){3}0\)/.test(waveColor) && // any transparent rgba color
waveColor !== 'transparent'
) {
// Add nonce if CSP exist

View File

@ -60,7 +60,8 @@ describe('Alert', () => {
const testIt = process.env.REACT === '15' ? it.skip : it;
testIt('ErrorBoundary', () => {
const ThrowError = () => <NotExisted />; // eslint-disable-line
// eslint-disable-next-line react/jsx-no-undef
const ThrowError = () => <NotExisted />;
const wrapper = mount(
<ErrorBoundary>
<ThrowError />

View File

@ -107,7 +107,6 @@ describe('Button', () => {
it('have static property for type detecting', () => {
const wrapper = mount(<Button>Button Text</Button>);
// eslint-disable-next-line
expect(wrapper.type().__ANT_BUTTON).toBe(true);
});
@ -136,7 +135,6 @@ describe('Button', () => {
});
it('should change loading state with delay', () => {
// eslint-disable-next-line
class DefaultButton extends Component {
state = {
loading: false,

View File

@ -156,7 +156,7 @@ describe('Calendar', () => {
it('Calendar should support locale', () => {
MockDate.set(Moment('2018-10-19'));
// eslint-disable-next-line
// eslint-disable-next-line global-require
const zhCN = require('../locale/zh_CN').default;
const wrapper = mount(<Calendar locale={zhCN} />);
expect(wrapper.render()).toMatchSnapshot();

View File

@ -40,7 +40,7 @@ describe('DropdownButton', () => {
const dropdownProps = wrapper.find(Dropdown).props();
Object.keys(props).forEach(key => {
expect(dropdownProps[key]).toBe(props[key]); // eslint-disable-line
expect(dropdownProps[key]).toBe(props[key]);
});
});

View File

@ -48,7 +48,7 @@ const FormItemLabel: React.FC<FormItemLabelProps & { required?: boolean; prefixC
const haveColon = computedColon && !vertical;
// Remove duplicated user input colon
if (haveColon && typeof label === 'string' && (label as string).trim() !== '') {
labelChildren = (label as string).replace(/[|:]\s*$/, '');
labelChildren = (label as string).replace(/[:|]\s*$/, '');
}
const labelClassName = classNames({

View File

@ -522,7 +522,7 @@ describe('Form', () => {
// https://github.com/ant-design/ant-design/issues/21415
it('Component.props.onChange is null', () => {
// eslint-disable-next-line
// eslint-disable-next-line react/prefer-stateless-function
class CustomComponent extends Component {
static defaultProps = {
onChange: null,

View File

@ -35,7 +35,7 @@ function formatNumber(value) {
class NumericInput extends React.Component {
onChange = e => {
const { value } = e.target;
const reg = /^-?[0-9]*(\.[0-9]*)?$/;
const reg = /^-?\d*(\.\d*)?$/;
if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
this.props.onChange(value);
}

View File

@ -98,7 +98,6 @@ describe('message', () => {
// https://github.com/ant-design/ant-design/issues/8201
it('should destroy messages correctly', () => {
// eslint-disable-next-line
class Test extends React.Component {
componentDidMount() {
message.loading('Action in progress1..', 0);

View File

@ -36,7 +36,7 @@ const timeUnits: [string, number][] = [
export function formatTimeStr(duration: number, format: string) {
let leftDuration: number = duration;
const escapeRegex = /\[[^\]]*\]/g;
const escapeRegex = /\[[^\]]*]/g;
const keepList: string[] = (format.match(escapeRegex) || []).map(str => str.slice(1, -1));
const templateText = format.replace(escapeRegex, '[]');

View File

@ -115,7 +115,7 @@ class Transfer extends React.Component<TransferProps, any> {
};
}
// eslint-disable-next-line
// eslint-disable-next-line class-methods-use-this
getSelectedKeysName(direction: TransferDirection) {
return direction === 'left' ? 'sourceSelectedKeys' : 'targetSelectedKeys';
}

View File

@ -55,7 +55,7 @@ class Editable extends React.Component<EditableProps, EditableState> {
}
onChange: React.ChangeEventHandler<HTMLTextAreaElement> = ({ target: { value } }) => {
this.setState({ current: value.replace(/[\r\n]/g, '') });
this.setState({ current: value.replace(/[\n\r]/g, '') });
};
onCompositionStart = () => {

View File

@ -276,7 +276,7 @@ describe('Typography', () => {
wrapper.find('TextArea').simulate('keyUp', { keyCode: KeyCode.ESC });
},
onChange => {
// eslint-disable-next-line
// eslint-disable-next-line jest/no-standalone-expect
expect(onChange).not.toHaveBeenCalled();
},
);

View File

@ -165,7 +165,7 @@ class Upload extends React.Component<UploadProps, UploadState> {
const removedFileList = removeFileItem(file, fileList);
if (removedFileList) {
file.status = 'removed'; // eslint-disable-line
file.status = 'removed';
if (this.upload) {
this.upload.abort(file);

View File

@ -199,7 +199,6 @@ describe('Upload', () => {
// https://github.com/ant-design/ant-design/issues/14298
it('should not have id if upload children is null, avoid being triggered by label', () => {
// eslint-disable-next-line
const Demo = ({ children }) => (
<Form>
<Form.Item name="upload" label="Upload" valuePropName="fileList">
@ -221,7 +220,6 @@ describe('Upload', () => {
// https://github.com/ant-design/ant-design/issues/16478
it('should not have id if upload is disabled, avoid being triggered by label', () => {
// eslint-disable-next-line
const Demo = ({ disabled }) => (
<Form>
<Form.Item name="upload" label="Upload" valuePropName="fileList">

View File

@ -190,6 +190,7 @@
"eslint-plugin-markdown": "^1.0.0",
"eslint-plugin-react": "^7.14.2",
"eslint-plugin-react-hooks": "^3.0.0",
"eslint-plugin-unicorn": "^18.0.1",
"eslint-tinker": "^0.5.0",
"fetch-jsonp": "^1.1.3",
"full-icu": "^1.3.0",

View File

@ -16,7 +16,7 @@ const components = uniq(
cwd: join(process.cwd()),
dot: false,
})
.map(path => path.replace(/(\/index)?((\.zh-CN)|(\.en-US))?\.md$/i, '')),
.map(path => path.replace(/(\/index)?((\.zh-cn)|(\.en-us))?\.md$/i, '')),
);
describe('site test', () => {

View File

@ -14,7 +14,6 @@ function alertBabelConfig(rules) {
if (rule.options.plugins.indexOf(replaceLib) === -1) {
rule.options.plugins.push(replaceLib);
}
// eslint-disable-next-line
rule.options.plugins = rule.options.plugins.filter(
plugin => !plugin.indexOf || plugin.indexOf('babel-plugin-add-module-exports') === -1,
);
@ -106,7 +105,6 @@ module.exports = {
javascriptEnabled: true,
},
webpackConfig(config) {
// eslint-disable-next-line
config.resolve.alias = {
'antd/lib': path.join(process.cwd(), 'components'),
'antd/es': path.join(process.cwd(), 'components'),
@ -116,23 +114,21 @@ module.exports = {
'react-intl': 'react-intl/dist',
};
// eslint-disable-next-line
config.externals = {
'react-router-dom': 'ReactRouterDOM',
};
if (usePreact) {
// eslint-disable-next-line
config.resolve.alias = Object.assign({}, config.resolve.alias, {
config.resolve.alias = {
...config.resolve.alias,
react: 'preact-compat',
'react-dom': 'preact-compat',
'create-react-class': 'preact-compat/lib/create-react-class',
'react-router': 'react-router',
});
};
}
if (isDev) {
// eslint-disable-next-line
config.devtool = 'source-map';
// Resolve use react hook fail when yarn link or npm link

View File

@ -6,7 +6,6 @@ import ColorPatterns from './ColorPatterns';
const primaryMinSaturation = 70; //
const primaryMinBrightness = 70; //
// eslint-disable-next-line
export default class ColorPaletteTool extends Component {
state = {
primaryColor: '#1890ff',

View File

@ -7,7 +7,6 @@ import ColorPatterns from './ColorPatterns';
const primaryMinSaturation = 70; //
const primaryMinBrightness = 70; //
// eslint-disable-next-line
export default class ColorPaletteTool extends Component {
state = {
primaryColor: '#1890ff',

View File

@ -109,7 +109,6 @@ class Article extends React.Component<ArticleProps> {
const metaDesc = helmetDesc || contentChild;
return (
/* eslint-disable-next-line */
<article className="markdown" onClick={this.onResourceClick}>
<Helmet encodeSpecialCharacters={false}>
{helmetTitle && <title>{helmetTitle}</title>}

View File

@ -92,7 +92,7 @@ class Demo extends React.Component {
});
};
// eslint-disable-next-line
// eslint-disable-next-line class-methods-use-this
track({ type, demo }) {
if (!window.gtag) {
return;
@ -180,18 +180,18 @@ class Demo extends React.Component {
title: `${localizedTitle} - Ant Design Demo`,
html,
js: sourceCode
.replace(/import\s+\{(\s+[^}]*\s+)\}\s+from\s+'antd';/, 'const { $1 } = antd;')
.replace(/import\s+{(\s+[^}]*\s+)}\s+from\s+'antd';/, 'const { $1 } = antd;')
.replace(
/import\s+\{(\s+[^}]*\s+)\}\s+from\s+'@ant-design\/icons';/,
/import\s+{(\s+[^}]*\s+)}\s+from\s+'@ant-design\/icons';/,
'const { $1 } = icons;',
)
.replace("import moment from 'moment';", '')
.replace(/import\s+\{\s+(.*)\s+\}\s+from\s+'react-router';/, 'const { $1 } = ReactRouter;')
.replace(/import\s+{\s+(.*)\s+}\s+from\s+'react-router';/, 'const { $1 } = ReactRouter;')
.replace(
/import\s+\{\s+(.*)\s+\}\s+from\s+'react-router-dom';/,
/import\s+{\s+(.*)\s+}\s+from\s+'react-router-dom';/,
'const { $1 } = ReactRouterDOM;',
)
.replace(/([a-zA-Z]*)\s+as\s+([a-zA-Z]*)/, '$1:$2'),
.replace(/([A-Za-z]*)\s+as\s+([A-Za-z]*)/, '$1:$2'),
css: prefillStyle,
editors: '001',
// eslint-disable-next-line no-undef
@ -300,7 +300,7 @@ ${parsedSourceCode.replace('mountNode', "document.getElementById('container')")}
<section className="code-box-demo">
<ErrorBoundary>{this.liveDemo}</ErrorBoundary>
{style ? (
<style dangerouslySetInnerHTML={{ __html: style }} /> // eslint-disable-line
<style dangerouslySetInnerHTML={{ __html: style }} />
) : null}
</section>
<section className="code-box-meta markdown">

View File

@ -43,7 +43,7 @@ function getModuleData(props) {
}
function fileNameToPath(filename) {
const snippets = filename.replace(/(\/index)?((\.zh-CN)|(\.en-US))?\.md$/i, '').split('/');
const snippets = filename.replace(/(\/index)?((\.zh-cn)|(\.en-us))?\.md$/i, '').split('/');
return snippets[snippets.length - 1];
}
@ -195,8 +195,10 @@ class MainContent extends Component {
if (!document.querySelector('.markdown > h2, .code-box')) {
return;
}
require('intersection-observer'); // eslint-disable-line
const scrollama = require('scrollama'); // eslint-disable-line
// eslint-disable-next-line global-require
require('intersection-observer');
// eslint-disable-next-line global-require
const scrollama = require('scrollama');
this.scroller = scrollama();
this.scroller
.setup({
@ -205,7 +207,7 @@ class MainContent extends Component {
})
.onStepEnter(({ element }) => {
[].forEach.call(document.querySelectorAll('.toc-affix li a'), node => {
node.className = ''; // eslint-disable-line
node.className = '';
});
const currentNode = document.querySelectorAll(`.toc-affix li a[href="#${element.id}"]`)[0];
if (currentNode) {
@ -232,7 +234,7 @@ class MainContent extends Component {
</span>,
];
const { disabled } = item;
const url = item.filename.replace(/(\/index)?((\.zh-CN)|(\.en-US))?\.md$/i, '').toLowerCase();
const url = item.filename.replace(/(\/index)?((\.zh-cn)|(\.en-us))?\.md$/i, '').toLowerCase();
const child = !item.link ? (
<Link
to={utils.getLocalizedPathname(

View File

@ -48,7 +48,7 @@ export default function Home() {
return (
<div className="home-container">
<style dangerouslySetInnerHTML={{ __html: getStyle() }} /> {/* eslint-disable-line */}
<style dangerouslySetInnerHTML={{ __html: getStyle() }} />
<Banner />
<div style={{ maxWidth: 1256, margin: '0 auto' }}>
<BlockContent title={<FormattedMessage id="app.home.recommend" />}>

View File

@ -23,7 +23,8 @@ const { Option } = Select;
let docsearch: any;
if (typeof window !== 'undefined') {
docsearch = require('docsearch.js'); // eslint-disable-line
// eslint-disable-next-line global-require
docsearch = require('docsearch.js');
}
function initDocSearch(locale: string) {
@ -38,8 +39,8 @@ function initDocSearch(locale: string) {
algoliaOptions: { facetFilters: [`tags:${lang}`] },
transformData(hits: { url: string }[]) {
hits.forEach(hit => {
hit.url = hit.url.replace('ant.design', window.location.host); // eslint-disable-line
hit.url = hit.url.replace('https:', window.location.protocol); // eslint-disable-line
hit.url = hit.url.replace('ant.design', window.location.host);
hit.url = hit.url.replace('https:', window.location.protocol)
});
return hits;
},

View File

@ -144,7 +144,6 @@ export function getLocalizedPathname(
}
export function ping(callback: (status: string) => void) {
// eslint-disable-next-line
const url =
'https://private-a' +
'lipay' +

View File

@ -16,5 +16,5 @@ $('dist')
.hasFile('antd.compact.css')
.hasFile('dark-theme.js');
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log(chalk.green('✨ `dist` directory is valid.'));

View File

@ -56,5 +56,5 @@ function compare(originFiles, targetFiles, targetPath) {
compare(localeFiles, localeProviderFiles, '/locale-provider');
compare(localeProviderFiles, localeFiles, '/locale');
// eslint-disable-next-line
// eslint-disable-next-line no-console
console.log(chalk.green('✨ `lib` directory is valid.'));

View File

@ -6,7 +6,8 @@ describe('antd dist files', () => {
// https://github.com/ant-design/ant-design/issues/1638
// https://github.com/ant-design/ant-design/issues/1968
it('exports modules correctly', () => {
const antd = testDist ? require('../dist/antd') : require('../components'); // eslint-disable-line
// eslint-disable-next-line global-require,import/no-unresolved
const antd = testDist ? require('../dist/antd') : require('../components');
expect(Object.keys(antd)).toMatchSnapshot();
});
@ -14,7 +15,8 @@ describe('antd dist files', () => {
// https://github.com/ant-design/ant-design/issues/1804
if (testDist) {
it('should have antd.version', () => {
const antd = require('../dist/antd'); // eslint-disable-line
// eslint-disable-next-line global-require,import/no-unresolved
const antd = require('../dist/antd');
expect(antd.version).toBe(pkg.version);
});
}