Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(arui-scripts): refactoring linter rules #169

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/arui-scripts/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,15 @@ module.exports = {
'import/no-named-as-default': 'warn',
// чтобы могли использовать for и генераторы
'no-restricted-syntax': 'off',
'class-methods-use-this': ['error', { exceptMethods: ['generate'] }],
// чтобы можно было игнорировать неиспользуемые аргументы и переменные, которые начинаются с _
'@typescript-eslint/no-unused-vars': [
'warn',
{
argsIgnorePattern: '^_',
varsIgnorePattern: '^_',
caughtErrorsIgnorePattern: '^_',
},
],
},
};
2 changes: 1 addition & 1 deletion packages/arui-scripts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@
"@types/webpack-manifest-plugin": "3.0.5",
"@types/webpack-node-externals": "^3.0.0",
"eslint": "^8.20.0",
"eslint-config-custom": "workspace:*",
"eslint-config-custom": "file:../eslint-config-custom",
"prettier": "^2.7.1",
"semantic-release": "^21.0.7",
"stylelint": "^14.9.1",
Expand Down
3 changes: 1 addition & 2 deletions packages/arui-scripts/release.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// TODO: remove eslint-disable-next-line
const betaChannelName = process.env.NPM_CHANNEL || 'next';

if (betaChannelName === 'latest') {
Expand All @@ -19,7 +18,7 @@ module.exports = {
{
name: '*/*',
channel: betaChannelName,
// eslint-disable-next-line no-template-curly-in-string
// eslint-disable-next-line no-template-curly-in-string
prerelease: '${name.replace(/[^0-9A-Za-z-]/g, "-")}',
},
],
Expand Down
1 change: 0 additions & 1 deletion packages/arui-scripts/src/commands/changelog/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ const changelogHeaderRegExp = /^###? \[\d+\.\d+\.\d+]\([^)]+\) \(\d{4}-\d{2}-\d{
ws.write(getVersionDescription({ features, bugFixes, breakingChanges }));
};

// eslint-disable-next-line no-restricted-syntax
for await (const line of rl) {
switch (modifyingStatus) {
// Копируем всё как есть до первого заголовка.
Expand Down
14 changes: 3 additions & 11 deletions packages/arui-scripts/src/commands/util/client-assets-sizes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// TODO: remove eslint-disable-next-line
import fs from 'fs';
import path from 'path';

Expand All @@ -7,15 +6,7 @@ import filesize from 'filesize';
import { sync as gzipSize } from 'gzip-size';
import stripAnsi from 'strip-ansi';
import { Stats } from 'webpack';

let brotliSize: (content: Buffer) => number = () => NaN;

try {
// eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
brotliSize = require('brotli-size').sync;
} catch (error) {
// empty error
}
import * as brotliSize from 'brotli-size';

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

здесь лучше сделать import { sync } from 'brotli-size'; если такое возможно, тк есть мнение что так tree shaking лучше сработает

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tree shaking в консольной утилите не то чтоб сильно актуален. Я за то чтоб оставить либо текущую запись, либо переделать на такую же, как и у gzip-size, потому что что такое функция sync - понять совсем не реально, а что такое brotlySize.sync - вполне

function canReadAsset(asset: string) {
return (
Expand Down Expand Up @@ -64,7 +55,7 @@ export function calculateAssetsSizes(webpackStats: Stats, rootDir = ''): ClientA
.map((asset) => {
const fileContents = fs.readFileSync(path.join(rootDir, asset.name));
const size = gzipSize(fileContents);
const brSize = brotliSize(fileContents);
const brSize = brotliSize.sync(fileContents);
const filename = path.basename(asset.name);

return {
Expand All @@ -78,6 +69,7 @@ export function calculateAssetsSizes(webpackStats: Stats, rootDir = ''): ClientA
brotliLabel: brSize ? filesize(brSize) : '-',
};
});

const totalSizes: Partial<TotalSizes> = (assets || []).reduce(
(file, total) => ({
size: total.size + file.size,
Expand Down
5 changes: 2 additions & 3 deletions packages/arui-scripts/src/commands/util/exec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
// TODO: remove eslint-disable-next-line
import shell from 'shelljs';

function exec(command: string) {
return new Promise((resolve, reject) => {
console.log(`Executing command: ${command}`);
// eslint-disable-next-line consistent-return

shell.exec(command, (code) => {
if (code === 0) {
return resolve(code);
resolve(code);
}
reject(code);
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// TODO: remove eslint-disable and eslint-disable-next-line
/* eslint-disable no-param-reassign */
/**
* Copyright (c) 2015-present, Facebook, Inc.
Expand All @@ -14,8 +13,7 @@
// This is quite hacky and hopefully won't be needed when Webpack fixes this.
// https://github.com/webpack/webpack/issues/2878

// eslint-disable-next-line @typescript-eslint/no-var-requires
const chalk = require('chalk');
import chalk from 'chalk';

const friendlySyntaxErrorLabel = 'Syntax error:';

Expand All @@ -24,7 +22,6 @@ function isLikelyASyntaxError(message: string) {
}

// Cleans up webpack error messages.
// eslint-disable-next-line no-unused-vars
function formatMessage(message: string | { message: string }) {
if (typeof message !== 'string') {
message = message.message;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ describe('update-with-presets', () => {
overridesPath: ['package-overrides-path.js'],
} as AppContext;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const updatedConfig = updateWithPresets(baseConfig, context);
updateWithPresets(baseConfig, context);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а куда переменная updatedConfig делась? Или она не использовалась?


expect(context.overridesPath).toEqual([
'presets/arui-scripts.overrides',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// TODO: remove eslint-disable-next-line
import fs from 'fs';
import path from 'path';
import { version as innerBabelRuntimeVersion } from '@babel/runtime/package.json';

import { getPolyfills } from '../util/get-polyfills';
import { resolveNodeModuleRelativeTo } from '../util/resolve';
Expand Down Expand Up @@ -38,8 +38,7 @@ export function calculateDependentContext(config: AppConfigs, context: AppContex
fs.readFileSync(pathToProjectBabelRuntime, 'utf8'),
).version;
} catch (e) {
// eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
babelRuntimeVersion = require('@babel/runtime/package.json').version;
babelRuntimeVersion = innerBabelRuntimeVersion;
}

return {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,39 +1,38 @@
// TODO: remove eslint-disable-next-line
import merge from 'lodash.merge';

import { tryResolve } from '../util/resolve';

import { AppConfigs, AppContext } from './types';
import { validateSettingsKeys } from './validate-settings-keys';

const ES_MODULE = '__esModule';

export function updateWithPresets(config: AppConfigs, context: AppContext) {
if (!config.presets) {
return config;
}
if (!config.presets) return config;

const presetsConfigPath = tryResolve(`${config.presets}/arui-scripts.config`, {
let appConfig = config;
const presetsConfigPath = tryResolve(`${appConfig.presets}/arui-scripts.config`, {
paths: [context.cwd],
});
const presetsOverridesPath = tryResolve(`${config.presets}/arui-scripts.overrides`, {
const presetsOverridesPath = tryResolve(`${appConfig.presets}/arui-scripts.overrides`, {
paths: [context.cwd],
});

if (presetsConfigPath) {
// eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-var-requires, global-require
let presetsSettings = require(presetsConfigPath);

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

require тут можно динамическим импортом заменить, тогда eslint комменты можно будет снести

// eslint-disable-next-line no-underscore-dangle
if (presetsSettings.__esModule) {
if (ES_MODULE in presetsSettings) {
// ts-node импортирует esModules, из них надо вытягивать default именно так
presetsSettings = presetsSettings.default;
}
validateSettingsKeys(config, presetsSettings, presetsConfigPath);
// eslint-disable-next-line no-param-reassign
config = merge(config, presetsSettings);
validateSettingsKeys(appConfig, presetsSettings, presetsConfigPath);

appConfig = merge(appConfig, presetsSettings);
}
if (presetsOverridesPath) {
context.overridesPath.unshift(presetsOverridesPath);
}

return config;
}
return appConfig;
}
37 changes: 16 additions & 21 deletions packages/arui-scripts/src/configs/util/apply-overrides.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// TODO: remove eslint-disable-next-line
import type { Configuration as WebpackConfiguration, WebpackOptionsNormalized } from 'webpack';
import type { Configuration as WebpackDevServerConfiguration } from 'webpack-dev-server';

Expand Down Expand Up @@ -44,7 +43,7 @@ type BoundCreateSingleClientWebpackConfig = OmitFirstArg<typeof createSingleClie
type ClientWebpackAdditionalArgs = {
createSingleClientWebpackConfig: BoundCreateSingleClientWebpackConfig;
findLoader: typeof findLoader;
findPlugin: ReturnType<typeof findPlugin<'client'>>
findPlugin: ReturnType<typeof findPlugin<'client'>>;
};

type ServerWebpackAdditionalArgs = {
Expand Down Expand Up @@ -75,7 +74,7 @@ type OverrideFunction<
> = (
config: Overrides[K],
appConfig: AppContextWithConfigs,
additionalArgs: AdditionalArgs,
additionalArgs: AdditionalArgs | unknown,
) => Overrides[K];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не надо тут unknown. Обсуждали в чате - этот тип выставляется пользователям. Сейчас он точно говорит что за тип ожидать при использовании оверрайда.

Пример использования на проекте

const override: OverrideFile = {
    webpackClient: (config, appConfig, { createSingleClientWebpackConfig }) => {
        return createSingleClientWebpackConfig('src/index', 'something');
    }
};

С типами без unknown - все работает. Если добавить unknown - ts будет ругаться. Нужно чтобы не ругался.

Если при этом никак не обойтись без использования например any в коде библиотеки - это ок, правильность и удобство типов для потребителей важнее чем прохождение правил линтера в библиотеке.


export type OverrideFile = {
Expand All @@ -89,8 +88,7 @@ overrides = appConfigs.overridesPath.map((path) => {
// eslint-disable-next-line import/no-dynamic-require, global-require, @typescript-eslint/no-var-requires
const requireResult = require(path);

// eslint-disable-next-line no-underscore-dangle
if (requireResult.__esModule) {
if ('__esModule' in requireResult) {
// ts-node импортирует esModules, из них надо вытягивать default именно так
return requireResult.default;
}
Expand All @@ -111,32 +109,29 @@ overrides = appConfigs.overridesPath.map((path) => {
* @param args Дополнительные аргументы, которые будут переданы в функцию оверрайда
* @returns {*}
*/
function applyOverrides<
T extends Overrides[Key],
Key extends keyof Overrides,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
Args = Key extends keyof OverridesAdditionalArgs ? OverridesAdditionalArgs[Key] : undefined,
>(overridesKey: Key | Key[], config: T, args?: any): T {
if (typeof overridesKey === 'string') {
// eslint-disable-next-line no-param-reassign
overridesKey = [overridesKey];
}
overridesKey.forEach((key) => {
function applyOverrides<T extends Overrides[Key], Key extends keyof Overrides>(
overridesKey: Key | Key[],
config: T,
args?: unknown,
): T {
let tempConfig = config;
const overrideKeys = typeof overridesKey === 'string' ? [overridesKey] : overridesKey;

overrideKeys.forEach((key) => {
overrides.forEach((override) => {
// eslint-disable-next-line no-prototype-builtins
if (override.hasOwnProperty(key)) {
if (key in override) {
const overrideFn = override[key];

if (typeof overrideFn !== 'function') {
throw new TypeError(`Override ${key} must be a function`);
}
// eslint-disable-next-line no-param-reassign
config = overrideFn(config, appConfigs, args);

tempConfig = overrideFn(tempConfig, appConfigs, args);
}
});
});

return config;
return tempConfig;
}

export default applyOverrides;
2 changes: 1 addition & 1 deletion packages/arui-scripts/src/configs/util/find-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@ export function findLoader(
}

return undefined;
}
}
8 changes: 4 additions & 4 deletions packages/arui-scripts/src/configs/webpack.client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,18 +281,18 @@ export const createSingleClientWebpackConfig = (
{
loader: require.resolve('babel-loader'),
options: {
...babelConf,
cacheDirectory: mode === 'dev',
cacheCompression: false,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
plugins:
plugins: [
mode === 'dev'
? [
require.resolve('react-refresh/babel'),
{ skipEnvCheck: true },
]
: undefined,
...babelConf,
...babelConf.plugins,
].filter(Boolean),
},
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ export class RuntimeModule extends webpack.RuntimeModule {
super('AruiRuntimeModule', webpack.RuntimeModule.STAGE_BASIC);
}

// eslint-disable-next-line class-methods-use-this
generate() {
return webpack.Template.asString([
"if (typeof __webpack_modules__ !== 'undefined') {", // По какой-то причине вебпак пытается выполнить этот код не только в браузере, но и при сборке.
Expand Down
9 changes: 8 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -6817,7 +6817,7 @@ __metadata:
css-loader: 6.8.1
css-minimizer-webpack-plugin: 3.4.1
eslint: ^8.20.0
eslint-config-custom: "workspace:*"
eslint-config-custom: "file:../eslint-config-custom"
expose-loader: 3.1.0
filesize: ^6.4.0
fork-ts-checker-webpack-plugin: 6.5.3
Expand Down Expand Up @@ -10093,6 +10093,13 @@ __metadata:
languageName: node
linkType: hard

"eslint-config-custom@file:../eslint-config-custom::locator=arui-scripts%40workspace%3Apackages%2Farui-scripts":
version: 0.0.0
resolution: "eslint-config-custom@file:../eslint-config-custom#../eslint-config-custom::hash=566b4e&locator=arui-scripts%40workspace%3Apackages%2Farui-scripts"
checksum: 424ecde95a6583b13ebdc939f5de19e8ff282659e775a691f5dc5a3cb0dd6c901c6c6c3db1bf5e435fb1707b419a01540320114a3a0ea953b377eb2de22467e7
languageName: node
linkType: hard

"eslint-config-custom@workspace:*, eslint-config-custom@workspace:packages/eslint-config-custom":
version: 0.0.0-use.local
resolution: "eslint-config-custom@workspace:packages/eslint-config-custom"
Expand Down
Loading