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

chore: enable some eslint rules #18084

Merged
merged 7 commits into from
Sep 12, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
28 changes: 19 additions & 9 deletions eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export default tseslint.config(
],

'@typescript-eslint/ban-ts-comment': 'error',
'@typescript-eslint/no-unsafe-function-type': 'off', // TODO: we should turn this on in a new PR
'@typescript-eslint/no-unsafe-function-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': [
'error',
{ allowArgumentsExplicitlyTypedAsAny: true },
Expand All @@ -107,26 +107,33 @@ export default tseslint.config(
],
'@typescript-eslint/no-empty-object-type': [
'error',
{ allowInterfaces: 'with-single-extends' }, // maybe we should turn this on in a new PR
{ allowInterfaces: 'with-single-extends' },
],
'@typescript-eslint/no-empty-interface': 'off',
'@typescript-eslint/no-explicit-any': 'off', // maybe we should turn this on in a new PR
'@typescript-eslint/no-explicit-any': 'off',
'no-extra-semi': 'off',
'@typescript-eslint/no-extra-semi': 'off', // conflicts with prettier
'@typescript-eslint/no-inferrable-types': 'off',
'@typescript-eslint/no-unused-expressions': 'off', // maybe we should turn this on in a new PR
'@typescript-eslint/no-unused-vars': 'off', // maybe we should turn this on in a new PR
'@typescript-eslint/no-unused-vars': [
'error',
{
args: 'all',
argsIgnorePattern: '^_',
caughtErrors: 'all',
caughtErrorsIgnorePattern: '^_',
destructuredArrayIgnorePattern: '^_',
varsIgnorePattern: '^_',
ignoreRestSiblings: true,
},
],
'@typescript-eslint/no-require-imports': 'off',
'@typescript-eslint/consistent-type-imports': [
'error',
{ prefer: 'type-imports', disallowTypeAnnotations: false },
],
// disable rules set in @typescript-eslint/stylistic which conflict with current code
// maybe we should turn them on in a new PR
// we should discuss if we want to enable these as they encourage consistent code
'@typescript-eslint/array-type': 'off',
'@typescript-eslint/ban-tslint-comment': 'off',
'@typescript-eslint/consistent-generic-constructors': 'off',
'@typescript-eslint/consistent-indexed-object-style': 'off',
'@typescript-eslint/consistent-type-definitions': 'off',
'@typescript-eslint/prefer-for-of': 'off',
'@typescript-eslint/prefer-function-type': 'off',
Expand Down Expand Up @@ -270,6 +277,8 @@ export default tseslint.config(
'n/no-unsupported-features/es-builtins': 'off',
'n/no-unsupported-features/node-builtins': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-unused-expressions': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'no-undef': 'off',
'no-empty': 'off',
'no-constant-condition': 'off',
Expand Down Expand Up @@ -298,6 +307,7 @@ export default tseslint.config(
name: 'disables/dts',
files: ['**/*.d.ts'],
rules: {
'@typescript-eslint/consistent-indexed-object-style': 'off',
'@typescript-eslint/triple-slash-reference': 'off',
},
},
Expand Down
2 changes: 1 addition & 1 deletion packages/create-vite/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default defineBuildConfig({
prompts: 'prompts/lib/index.js',
},
hooks: {
'rollup:options'(ctx, options) {
'rollup:options'(_ctx, options) {
options.plugins = [
options.plugins,
// @ts-expect-error TODO: unbuild uses rollup v3 and Vite uses rollup v4
Expand Down
15 changes: 10 additions & 5 deletions packages/plugin-legacy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ function toAssetPathFromHtml(
config: ResolvedConfig,
): string {
const relativeUrlPath = normalizePath(path.relative(config.root, htmlPath))
const toRelative = (filename: string, hostId: string) =>
const toRelative = (filename: string, _hostId: string) =>
getBaseInHTML(relativeUrlPath, config) + filename
return toOutputFilePathInHtml(
filename,
Expand Down Expand Up @@ -296,11 +296,12 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] {
if (!modernPolyfills.size) {
return
}
isDebug &&
if (isDebug) {
console.log(
`[@vitejs/plugin-legacy] modern polyfills:`,
modernPolyfills,
)
}
const polyfillChunk = await buildPolyfillChunk(
config.mode,
modernPolyfills,
Expand Down Expand Up @@ -338,11 +339,12 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] {
}

if (legacyPolyfills.size || !options.externalSystemJS) {
isDebug &&
if (isDebug) {
console.log(
`[@vitejs/plugin-legacy] legacy polyfills:`,
legacyPolyfills,
)
}

await buildPolyfillChunk(
config.mode,
Expand Down Expand Up @@ -377,8 +379,9 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] {
config = _config

modernTargets = options.modernTargets || modernTargetsBabel
isDebug &&
if (isDebug) {
console.log(`[@vitejs/plugin-legacy] modernTargets:`, modernTargets)
}

if (!genLegacy || config.build.ssr) {
return
Expand All @@ -388,7 +391,9 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] {
options.targets ||
browserslistLoadConfig({ path: config.root }) ||
'last 2 versions and not dead, > 0.3%, Firefox ESR'
isDebug && console.log(`[@vitejs/plugin-legacy] targets:`, targets)
if (isDebug) {
console.log(`[@vitejs/plugin-legacy] targets:`, targets)
}

const getLegacyOutputFileName = (
fileNames:
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-legacy/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ export interface Options {
/**
* default: 'defaults'
*/
targets?: string | string[] | { [key: string]: string }
targets?: string | string[] | Record<string, string>
/**
* default: 'edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12'
*/
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/bin/vite.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ if (!import.meta.url.includes('node_modules')) {
try {
// only available as dev dependency
await import('source-map-support').then((r) => r.default.install())
} catch (e) {}
} catch {}
}

global.__vite_start_time = performance.now()
Expand Down
1 change: 0 additions & 1 deletion packages/vite/src/client/env.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
declare const __MODE__: string
declare const __DEFINES__: Record<string, any>

const context = (() => {
Expand Down
4 changes: 3 additions & 1 deletion packages/vite/src/module-runner/moduleCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ export class ModuleCacheMap extends Map<string, ModuleCache> {
const subIds = Array.from(super.entries())
.filter(([, mod]) => mod.importers?.has(id))
.map(([key]) => key)
subIds.length && this.invalidateSubDepTree(subIds, invalidated)
if (subIds.length) {
this.invalidateSubDepTree(subIds, invalidated)
}
super.delete(id)
}
return invalidated
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/module-runner/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ export class ModuleRunner {
dirname: isWindows ? toWindowsPath(dirname) : dirname,
url: href,
env: this.envProxy,
resolve(id, parent) {
resolve(_id, _parent) {
throw new Error(
'[module runner] "import.meta.resolve" is not supported.',
)
Expand Down Expand Up @@ -437,7 +437,7 @@ function exportAll(exports: any, sourceModule: any) {
configurable: true,
get: () => sourceModule[key],
})
} catch (_err) {}
} catch {}
}
}
}
2 changes: 1 addition & 1 deletion packages/vite/src/module-runner/sourcemap/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export interface InterceptorOptions {
const sourceMapCache: Record<string, CachedMapEntry> = {}
const fileContentsCache: Record<string, string> = {}

const moduleGraphs: Set<ModuleCacheMap> = new Set()
const moduleGraphs = new Set<ModuleCacheMap>()
const retrieveFileHandlers = new Set<RetrieveFileHandler>()
const retrieveSourceMapHandlers = new Set<RetrieveSourceMapHandler>()

Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/__tests__/plugins/css.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ async function createCssPluginTransform(
const mockFs = vi
.spyOn(fs, 'readFile')
// @ts-expect-error vi.spyOn not recognize override `fs.readFile` definition.
.mockImplementationOnce((p, encoding, callback) => {
.mockImplementationOnce((p, _encoding, callback) => {
callback(null, Buffer.from(files?.[p] ?? ''))
})

Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/external.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export function createIsConfiguredAsExternal(
// configured as external
!!configuredAsExternal,
)?.external
} catch (e) {
} catch {
debug?.(
`Failed to node resolve "${id}". Skipping externalizing it by default.`,
)
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/optimizer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ export async function loadCachedDepOptimizationMetadata(
await fsp.readFile(cachedMetadataPath, 'utf-8'),
depsCacheDir,
)
} catch (e) {}
} catch {}
// hash is consistent, no need to re-bundle
if (cachedMetadata) {
if (cachedMetadata.lockfileHash !== getLockfileHash(environment)) {
Expand Down Expand Up @@ -508,7 +508,7 @@ export function runOptimizeDeps(
try {
// When exiting the process, `fsp.rm` may not take effect, so we use `fs.rmSync`
fs.rmSync(processingCacheDir, { recursive: true, force: true })
} catch (error) {
} catch {
// Ignore errors
}
}
Expand Down Expand Up @@ -1286,7 +1286,7 @@ export async function cleanupDepsCacheStaleDirs(
for (const dirent of dirents) {
if (dirent.isDirectory() && dirent.name.includes('_temp_')) {
const tempDirPath = path.resolve(config.cacheDir, dirent.name)
const stats = await fsp.stat(tempDirPath).catch((_) => null)
const stats = await fsp.stat(tempDirPath).catch(() => null)
if (
stats?.mtime &&
Date.now() - stats.mtime.getTime() > MAX_TEMP_DIR_AGE_MS
Expand Down Expand Up @@ -1331,7 +1331,7 @@ const safeRename = promisify(function gracefulRename(
Date.now() - start < GRACEFUL_RENAME_TIMEOUT
) {
setTimeout(function () {
fs.stat(to, function (stater, st) {
fs.stat(to, function (stater, _st) {
if (stater && stater.code === 'ENOENT') fs.rename(from, to, CB)
else CB(er)
})
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import type {
ResolvedConfig,
UserConfig,
} from './config'
import type { ServerHook, ViteDevServer } from './server'
import type { ServerHook } from './server'
import type { IndexHtmlTransform } from './plugins/html'
import type { EnvironmentModuleNode } from './server/moduleGraph'
import type { ModuleNode } from './server/mixedModuleGraph'
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/completeSystemWrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export function completeSystemWrapPlugin(): Plugin {
return {
name: 'vite:force-systemjs-wrap-complete',

renderChunk(code, chunk, opts) {
renderChunk(code, _chunk, opts) {
if (opts.format === 'system') {
return {
code: code.replace(SystemJSWrapRE, (s, s1) =>
Expand Down
15 changes: 9 additions & 6 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ const enum PreprocessLang {
styl = 'styl',
stylus = 'stylus',
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- bug in typescript-eslint
const enum PureCssLang {
css = 'css',
}
Expand Down Expand Up @@ -964,7 +965,7 @@ export function cssAnalysisPlugin(config: ResolvedConfig): Plugin {
return {
name: 'vite:css-analysis',

async transform(_, id, options) {
async transform(_, id) {
if (
!isCSSRequest(id) ||
commonjsProxyRE.test(id) ||
Expand Down Expand Up @@ -2056,7 +2057,7 @@ function loadSassPackage(root: string): {
try {
const path = loadPreprocessorPath(PreprocessLang.sass, root)
return { name: 'sass', path }
} catch (e2) {
} catch (_e2) {
bluwy marked this conversation as resolved.
Show resolved Hide resolved
throw e1
}
}
Expand Down Expand Up @@ -2173,9 +2174,11 @@ const makeScssWorker = (
}
const importer = [_internalImporter]
if (options.importer) {
Array.isArray(options.importer)
? importer.unshift(...options.importer)
: importer.unshift(options.importer)
if (Array.isArray(options.importer)) {
importer.unshift(...options.importer)
} else {
importer.unshift(options.importer)
}
}

const finalOptions: Sass.LegacyOptions<'async'> = {
Expand Down Expand Up @@ -2847,7 +2850,7 @@ const stylProcessor = (
worker.stop()
}
},
async process(environment, source, root, options, resolvers) {
async process(_environment, source, root, options, _resolvers) {
const stylusPath = loadPreprocessorPath(PreprocessLang.stylus, root)

if (!workerMap.has(options.alias)) {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/dynamicImportVars.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export function dynamicImportVarsPlugin(config: ResolvedConfig): Plugin {
let imports: readonly ImportSpecifier[] = []
try {
imports = parseImports(source)[0]
} catch (e: any) {
} catch {
// ignore as it might not be a JS file, the subsequent plugins will catch the error
return null
}
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,10 @@ export async function transformWithEsbuild(
// esbuild uses tsconfig fields when both the normal options and tsconfig was set
// but we want to prioritize the normal options
if (options) {
options.jsx && (compilerOptions.jsx = undefined)
options.jsxFactory && (compilerOptions.jsxFactory = undefined)
options.jsxFragment && (compilerOptions.jsxFragmentFactory = undefined)
options.jsxImportSource && (compilerOptions.jsxImportSource = undefined)
if (options.jsx) compilerOptions.jsx = undefined
if (options.jsxFactory) compilerOptions.jsxFactory = undefined
if (options.jsxFragment) compilerOptions.jsxFragmentFactory = undefined
if (options.jsxImportSource) compilerOptions.jsxImportSource = undefined
}

tsconfigRaw = {
Expand Down
7 changes: 3 additions & 4 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,8 +338,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
const publicPath = `/${relativeUrlPath}`
const publicBase = getBaseInHTML(relativeUrlPath, config)

const publicToRelative = (filename: string, importer: string) =>
publicBase + filename
const publicToRelative = (filename: string) => publicBase + filename
const toOutputPublicFilePath = (url: string) =>
toOutputFilePathInHtml(
url.slice(1),
Expand Down Expand Up @@ -694,7 +693,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
},

async generateBundle(options, bundle) {
const analyzedChunk: Map<OutputChunk, number> = new Map()
const analyzedChunk = new Map<OutputChunk, number>()
const inlineEntryChunk = new Set<string>()
const getImportedChunks = (
chunk: OutputChunk,
Expand Down Expand Up @@ -797,7 +796,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin {
relativeUrlPath,
'html',
config,
(filename: string, importer: string) => assetsBase + filename,
(filename) => assetsBase + filename,
)
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ export function buildImportAnalysisPlugin(config: ResolvedConfig): Plugin {
if (rawUrl[0] === `"` && rawUrl[rawUrl.length - 1] === `"`)
url = rawUrl.slice(1, -1)
}
const deps: Set<string> = new Set()
const deps = new Set<string>()
let hasRemovedPureCssChunk = false

let normalizedFile: string | undefined = undefined
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/importMetaGlob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export async function parseImportGlob(
let cleanCode: string
try {
cleanCode = stripLiteral(code)
} catch (e) {
} catch {
// skip invalid js code
return []
}
Expand Down
Loading
Loading