From e9a2746ca77473b1814fd05db3d299c074135fe5 Mon Sep 17 00:00:00 2001 From: Bjorn Lu Date: Thu, 12 Sep 2024 17:28:36 +0800 Subject: [PATCH] chore: enable some eslint rules (#18084) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: 翠 / green --- eslint.config.js | 28 +++++++++++++------ packages/create-vite/build.config.ts | 2 +- packages/plugin-legacy/src/index.ts | 15 ++++++---- packages/plugin-legacy/src/types.ts | 2 +- packages/vite/bin/vite.js | 2 +- packages/vite/src/client/env.ts | 1 - .../vite/src/module-runner/moduleCache.ts | 4 ++- packages/vite/src/module-runner/runner.ts | 4 +-- .../module-runner/sourcemap/interceptor.ts | 2 +- .../src/node/__tests__/plugins/css.spec.ts | 2 +- packages/vite/src/node/external.ts | 2 +- packages/vite/src/node/optimizer/index.ts | 8 +++--- packages/vite/src/node/plugin.ts | 2 +- .../src/node/plugins/completeSystemWrap.ts | 2 +- packages/vite/src/node/plugins/css.ts | 15 ++++++---- .../src/node/plugins/dynamicImportVars.ts | 2 +- packages/vite/src/node/plugins/esbuild.ts | 8 +++--- packages/vite/src/node/plugins/html.ts | 7 ++--- .../src/node/plugins/importAnalysisBuild.ts | 2 +- .../vite/src/node/plugins/importMetaGlob.ts | 2 +- packages/vite/src/node/plugins/index.ts | 4 +-- .../vite/src/node/plugins/loadFallback.ts | 2 +- packages/vite/src/node/plugins/manifest.ts | 2 +- .../vite/src/node/plugins/optimizedDeps.ts | 6 ++-- packages/vite/src/node/plugins/resolve.ts | 20 ++----------- packages/vite/src/node/plugins/wasm.ts | 3 +- packages/vite/src/node/plugins/worker.ts | 2 +- .../server/__tests__/pluginContainer.spec.ts | 4 +-- .../node/server/middlewares/htmlFallback.ts | 2 +- .../src/node/server/middlewares/indexHtml.ts | 2 +- .../vite/src/node/server/middlewares/proxy.ts | 6 ++-- .../src/node/server/middlewares/static.ts | 2 +- .../src/node/server/middlewares/transform.ts | 2 +- .../vite/src/node/server/mixedModuleGraph.ts | 4 +-- packages/vite/src/node/server/moduleGraph.ts | 2 +- packages/vite/src/node/server/openBrowser.ts | 4 +-- .../vite/src/node/server/pluginContainer.ts | 2 +- packages/vite/src/node/typeUtils.ts | 2 +- playground/vitestSetup.ts | 2 +- 39 files changed, 93 insertions(+), 92 deletions(-) diff --git a/eslint.config.js b/eslint.config.js index 5db3208a2e2a4c..0c936aa7986ff1 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -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 }, @@ -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', @@ -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', @@ -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', }, }, diff --git a/packages/create-vite/build.config.ts b/packages/create-vite/build.config.ts index 03907ba7e0d809..079834cb73822b 100644 --- a/packages/create-vite/build.config.ts +++ b/packages/create-vite/build.config.ts @@ -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 diff --git a/packages/plugin-legacy/src/index.ts b/packages/plugin-legacy/src/index.ts index 974e07d13d83e3..4bd497f1af8de8 100644 --- a/packages/plugin-legacy/src/index.ts +++ b/packages/plugin-legacy/src/index.ts @@ -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, @@ -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, @@ -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, @@ -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 @@ -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: diff --git a/packages/plugin-legacy/src/types.ts b/packages/plugin-legacy/src/types.ts index bd2d239c0aab8d..f8a5a95268dcae 100644 --- a/packages/plugin-legacy/src/types.ts +++ b/packages/plugin-legacy/src/types.ts @@ -2,7 +2,7 @@ export interface Options { /** * default: 'defaults' */ - targets?: string | string[] | { [key: string]: string } + targets?: string | string[] | Record /** * default: 'edge>=79, firefox>=67, chrome>=64, safari>=12, chromeAndroid>=64, iOS>=12' */ diff --git a/packages/vite/bin/vite.js b/packages/vite/bin/vite.js index a9bbb9c3a54716..0054bd2773d44d 100755 --- a/packages/vite/bin/vite.js +++ b/packages/vite/bin/vite.js @@ -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() diff --git a/packages/vite/src/client/env.ts b/packages/vite/src/client/env.ts index e6d51d98f9a5bf..158ce43f7bf36f 100644 --- a/packages/vite/src/client/env.ts +++ b/packages/vite/src/client/env.ts @@ -1,4 +1,3 @@ -declare const __MODE__: string declare const __DEFINES__: Record const context = (() => { diff --git a/packages/vite/src/module-runner/moduleCache.ts b/packages/vite/src/module-runner/moduleCache.ts index f575f915e6a7f1..9c5c188e3da8cc 100644 --- a/packages/vite/src/module-runner/moduleCache.ts +++ b/packages/vite/src/module-runner/moduleCache.ts @@ -114,7 +114,9 @@ export class ModuleCacheMap extends Map { 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 diff --git a/packages/vite/src/module-runner/runner.ts b/packages/vite/src/module-runner/runner.ts index 49ab24c6177b5a..4c132ec4117072 100644 --- a/packages/vite/src/module-runner/runner.ts +++ b/packages/vite/src/module-runner/runner.ts @@ -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.', ) @@ -437,7 +437,7 @@ function exportAll(exports: any, sourceModule: any) { configurable: true, get: () => sourceModule[key], }) - } catch (_err) {} + } catch {} } } } diff --git a/packages/vite/src/module-runner/sourcemap/interceptor.ts b/packages/vite/src/module-runner/sourcemap/interceptor.ts index d9787d81df22f8..1041e6b7276459 100644 --- a/packages/vite/src/module-runner/sourcemap/interceptor.ts +++ b/packages/vite/src/module-runner/sourcemap/interceptor.ts @@ -21,7 +21,7 @@ export interface InterceptorOptions { const sourceMapCache: Record = {} const fileContentsCache: Record = {} -const moduleGraphs: Set = new Set() +const moduleGraphs = new Set() const retrieveFileHandlers = new Set() const retrieveSourceMapHandlers = new Set() diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 7076bb915c386c..891690e58b6f51 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -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] ?? '')) }) diff --git a/packages/vite/src/node/external.ts b/packages/vite/src/node/external.ts index 6e386dcccac736..1fef5113a2612f 100644 --- a/packages/vite/src/node/external.ts +++ b/packages/vite/src/node/external.ts @@ -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.`, ) diff --git a/packages/vite/src/node/optimizer/index.ts b/packages/vite/src/node/optimizer/index.ts index fbbf73ee627060..e038affeeca355 100644 --- a/packages/vite/src/node/optimizer/index.ts +++ b/packages/vite/src/node/optimizer/index.ts @@ -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)) { @@ -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 } } @@ -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 @@ -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) }) diff --git a/packages/vite/src/node/plugin.ts b/packages/vite/src/node/plugin.ts index c181ff9f9e9c84..2f85520ac34f51 100644 --- a/packages/vite/src/node/plugin.ts +++ b/packages/vite/src/node/plugin.ts @@ -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' diff --git a/packages/vite/src/node/plugins/completeSystemWrap.ts b/packages/vite/src/node/plugins/completeSystemWrap.ts index 8244fe80c046a0..e4e5565fabff2d 100644 --- a/packages/vite/src/node/plugins/completeSystemWrap.ts +++ b/packages/vite/src/node/plugins/completeSystemWrap.ts @@ -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) => diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 217805c335a3a9..390804543ce9e3 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -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', } @@ -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) || @@ -2056,7 +2057,7 @@ function loadSassPackage(root: string): { try { const path = loadPreprocessorPath(PreprocessLang.sass, root) return { name: 'sass', path } - } catch (e2) { + } catch { throw e1 } } @@ -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'> = { @@ -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)) { diff --git a/packages/vite/src/node/plugins/dynamicImportVars.ts b/packages/vite/src/node/plugins/dynamicImportVars.ts index 145f6130a55708..ac1fc2d90edc23 100644 --- a/packages/vite/src/node/plugins/dynamicImportVars.ts +++ b/packages/vite/src/node/plugins/dynamicImportVars.ts @@ -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 } diff --git a/packages/vite/src/node/plugins/esbuild.ts b/packages/vite/src/node/plugins/esbuild.ts index f810b55c89c33a..c4d86432d5f320 100644 --- a/packages/vite/src/node/plugins/esbuild.ts +++ b/packages/vite/src/node/plugins/esbuild.ts @@ -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 = { diff --git a/packages/vite/src/node/plugins/html.ts b/packages/vite/src/node/plugins/html.ts index 8b7908a0d288bc..7d70b5a2938c7e 100644 --- a/packages/vite/src/node/plugins/html.ts +++ b/packages/vite/src/node/plugins/html.ts @@ -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), @@ -694,7 +693,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { }, async generateBundle(options, bundle) { - const analyzedChunk: Map = new Map() + const analyzedChunk = new Map() const inlineEntryChunk = new Set() const getImportedChunks = ( chunk: OutputChunk, @@ -797,7 +796,7 @@ export function buildHtmlPlugin(config: ResolvedConfig): Plugin { relativeUrlPath, 'html', config, - (filename: string, importer: string) => assetsBase + filename, + (filename) => assetsBase + filename, ) } } diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index 12d35997c92271..12aee275740150 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -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 = new Set() + const deps = new Set() let hasRemovedPureCssChunk = false let normalizedFile: string | undefined = undefined diff --git a/packages/vite/src/node/plugins/importMetaGlob.ts b/packages/vite/src/node/plugins/importMetaGlob.ts index f010f093446c03..991393f5aa6b54 100644 --- a/packages/vite/src/node/plugins/importMetaGlob.ts +++ b/packages/vite/src/node/plugins/importMetaGlob.ts @@ -220,7 +220,7 @@ export async function parseImportGlob( let cleanCode: string try { cleanCode = stripLiteral(code) - } catch (e) { + } catch { // skip invalid js code return [] } diff --git a/packages/vite/src/node/plugins/index.ts b/packages/vite/src/node/plugins/index.ts index af0215d415871e..7d4efd6a024b61 100644 --- a/packages/vite/src/node/plugins/index.ts +++ b/packages/vite/src/node/plugins/index.ts @@ -44,7 +44,7 @@ export async function resolvePlugins( ) return [ - depOptimizationEnabled ? optimizedDepsPlugin(config) : null, + depOptimizationEnabled ? optimizedDepsPlugin() : null, isBuild ? metadataPlugin() : null, !isWorker ? watchPackageDataPlugin(config.packageCache) : null, preAliasPlugin(config), @@ -81,7 +81,7 @@ export async function resolvePlugins( }, isBuild, ), - wasmHelperPlugin(config), + wasmHelperPlugin(), webWorkerPlugin(config), assetPlugin(config), diff --git a/packages/vite/src/node/plugins/loadFallback.ts b/packages/vite/src/node/plugins/loadFallback.ts index b774b042fc5626..f221ce56bdd2fb 100644 --- a/packages/vite/src/node/plugins/loadFallback.ts +++ b/packages/vite/src/node/plugins/loadFallback.ts @@ -14,7 +14,7 @@ export function buildLoadFallbackPlugin(): Plugin { const content = await fsp.readFile(cleanedId, 'utf-8') this.addWatchFile(cleanedId) return content - } catch (e) { + } catch { const content = await fsp.readFile(id, 'utf-8') this.addWatchFile(id) return content diff --git a/packages/vite/src/node/plugins/manifest.ts b/packages/vite/src/node/plugins/manifest.ts index 12acfd4c81f732..5ea9779633df37 100644 --- a/packages/vite/src/node/plugins/manifest.ts +++ b/packages/vite/src/node/plugins/manifest.ts @@ -134,7 +134,7 @@ export function manifestPlugin(): Plugin { try { const fileName = this.getFileName(id) entryCssAssetFileNames.add(fileName) - } catch (error: unknown) { + } catch { // The asset was generated as part of a different output option. // It was already handled during the previous run of this plugin. assets.delete(id) diff --git a/packages/vite/src/node/plugins/optimizedDeps.ts b/packages/vite/src/node/plugins/optimizedDeps.ts index f3cdd039c213e8..e1c4dcc049426a 100644 --- a/packages/vite/src/node/plugins/optimizedDeps.ts +++ b/packages/vite/src/node/plugins/optimizedDeps.ts @@ -1,6 +1,6 @@ import fsp from 'node:fs/promises' import colors from 'picocolors' -import type { DevEnvironment, ResolvedConfig } from '..' +import type { DevEnvironment } from '..' import type { Plugin } from '../plugin' import { DEP_VERSION_RE } from '../constants' import { createDebugger } from '../utils' @@ -15,7 +15,7 @@ export const ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR = const debug = createDebugger('vite:optimize-deps') -export function optimizedDepsPlugin(config: ResolvedConfig): Plugin { +export function optimizedDepsPlugin(): Plugin { return { name: 'vite:optimized-deps', @@ -70,7 +70,7 @@ export function optimizedDepsPlugin(config: ResolvedConfig): Plugin { // we are sure that the file has been properly save to disk try { return await fsp.readFile(file, 'utf-8') - } catch (e) { + } catch { const newMetadata = depsOptimizer.metadata if (optimizedDepInfoFromFile(newMetadata, file)) { // Outdated non-entry points (CHUNK), loaded after a rerun diff --git a/packages/vite/src/node/plugins/resolve.ts b/packages/vite/src/node/plugins/resolve.ts index 2abacbf9d2caea..c0b5314d867a18 100644 --- a/packages/vite/src/node/plugins/resolve.ts +++ b/packages/vite/src/node/plugins/resolve.ts @@ -598,7 +598,6 @@ export function tryFsResolve( fsPath: string, options: InternalResolveOptions, tryIndex = true, - targetWeb = true, skipPackageJson = false, ): string | undefined { // Dependencies like es5-ext use `#` in their paths. We don't support `#` in user @@ -610,25 +609,13 @@ export function tryFsResolve( // We only need to check foo#bar?baz and foo#bar, ignore foo?bar#baz if (queryIndex < 0 || queryIndex > hashIndex) { const file = queryIndex > hashIndex ? fsPath.slice(0, queryIndex) : fsPath - const res = tryCleanFsResolve( - file, - options, - tryIndex, - targetWeb, - skipPackageJson, - ) + const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson) if (res) return res + fsPath.slice(file.length) } } const { file, postfix } = splitFileAndPostfix(fsPath) - const res = tryCleanFsResolve( - file, - options, - tryIndex, - targetWeb, - skipPackageJson, - ) + const res = tryCleanFsResolve(file, options, tryIndex, skipPackageJson) if (res) return res + postfix } @@ -639,7 +626,6 @@ function tryCleanFsResolve( file: string, options: InternalResolveOptions, tryIndex = true, - targetWeb = true, skipPackageJson = false, ): string | undefined { const { tryPrefix, extensions, preserveSymlinks } = options @@ -1104,7 +1090,6 @@ export function resolvePackageEntry( entryPointPath, options, true, - true, skipPackageJson, ) if (resolvedEntryPoint) { @@ -1228,7 +1213,6 @@ function resolveDeepImport( path.join(dir, relativeId), options, !exportsField, // try index only if no exports field - !!options.webCompatible, ) if (resolved) { debug?.( diff --git a/packages/vite/src/node/plugins/wasm.ts b/packages/vite/src/node/plugins/wasm.ts index d3e9c272c89b50..0fbb2b90d65205 100644 --- a/packages/vite/src/node/plugins/wasm.ts +++ b/packages/vite/src/node/plugins/wasm.ts @@ -1,4 +1,3 @@ -import type { ResolvedConfig } from '../config' import type { Plugin } from '../plugin' import { fileToUrl } from './asset' @@ -47,7 +46,7 @@ const wasmHelper = async (opts = {}, url: string) => { const wasmHelperCode = wasmHelper.toString() -export const wasmHelperPlugin = (config: ResolvedConfig): Plugin => { +export const wasmHelperPlugin = (): Plugin => { return { name: 'vite:wasm-helper', diff --git a/packages/vite/src/node/plugins/worker.ts b/packages/vite/src/node/plugins/worker.ts index 4625a82eab2657..dd6cb9b8a3e0a4 100644 --- a/packages/vite/src/node/plugins/worker.ts +++ b/packages/vite/src/node/plugins/worker.ts @@ -244,7 +244,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin { } }, - async transform(raw, id, options) { + async transform(raw, id) { const workerFileMatch = workerFileRE.exec(id) if (workerFileMatch) { // if import worker by worker constructor will have query.type diff --git a/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts b/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts index 5dce96bd36384f..6cd19a7d6e8674 100644 --- a/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts +++ b/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts @@ -29,7 +29,7 @@ describe('plugin container', () => { return { code: 'export {}', meta: { x: 2 } } } }, - transform(code, id) { + transform(_code, id) { if (id === entryUrl) { const { meta } = this.getModuleInfo(entryUrl) ?? {} metaArray.push(meta) @@ -191,7 +191,7 @@ describe('plugin container', () => { if (id === entryUrl) return { code: '1' } else if (id === otherUrl) return { code: '2', meta: { code: '2' } } }, - async transform(code, id) { + async transform(_code, id) { if (id === entryUrl) { // NOTE: ModuleInfo.code not implemented, used `.meta.code` for now return (await this.load({ id: otherUrl }))?.meta.code diff --git a/packages/vite/src/node/server/middlewares/htmlFallback.ts b/packages/vite/src/node/server/middlewares/htmlFallback.ts index 0814b697f95d9a..a7f9d826a2c738 100644 --- a/packages/vite/src/node/server/middlewares/htmlFallback.ts +++ b/packages/vite/src/node/server/middlewares/htmlFallback.ts @@ -13,7 +13,7 @@ export function htmlFallbackMiddleware( fsUtils: FsUtils = commonFsUtils, ): Connect.NextHandleFunction { // Keep the named function. The name is visible in debug logs via `DEBUG=connect:dispatcher ...` - return function viteHtmlFallbackMiddleware(req, res, next) { + return function viteHtmlFallbackMiddleware(req, _res, next) { if ( // Only accept GET or HEAD (req.method !== 'GET' && req.method !== 'HEAD') || diff --git a/packages/vite/src/node/server/middlewares/indexHtml.ts b/packages/vite/src/node/server/middlewares/indexHtml.ts index 2da4efee960a58..e55cf8505138cc 100644 --- a/packages/vite/src/node/server/middlewares/indexHtml.ts +++ b/packages/vite/src/node/server/middlewares/indexHtml.ts @@ -169,7 +169,7 @@ const processNodeUrl = ( if (preTransformUrl) { try { preTransformUrl = decodeURI(preTransformUrl) - } catch (err) { + } catch { // Malformed uri. Skip pre-transform. return url } diff --git a/packages/vite/src/node/server/middlewares/proxy.ts b/packages/vite/src/node/server/middlewares/proxy.ts index 17f6d7a235d583..6a546260941cd5 100644 --- a/packages/vite/src/node/server/middlewares/proxy.ts +++ b/packages/vite/src/node/server/middlewares/proxy.ts @@ -89,7 +89,7 @@ export function proxyMiddleware( opts.configure(proxy, opts) } - proxy.on('error', (err, req, originalRes) => { + proxy.on('error', (err, _req, originalRes) => { // When it is ws proxy, res is net.Socket // originalRes can be falsy if the proxy itself errored const res = originalRes as http.ServerResponse | net.Socket | undefined @@ -127,7 +127,7 @@ export function proxyMiddleware( } }) - proxy.on('proxyReqWs', (proxyReq, req, socket, options, head) => { + proxy.on('proxyReqWs', (proxyReq, _req, socket, options) => { rewriteOriginHeader(proxyReq, options, config) socket.on('error', (err) => { @@ -143,7 +143,7 @@ export function proxyMiddleware( // https://github.com/http-party/node-http-proxy/issues/1520#issue-877626125 // https://github.com/chimurai/http-proxy-middleware/blob/cd58f962aec22c925b7df5140502978da8f87d5f/src/plugins/default/debug-proxy-errors-plugin.ts#L25-L37 - proxy.on('proxyRes', (proxyRes, req, res) => { + proxy.on('proxyRes', (proxyRes, _req, res) => { res.on('close', () => { if (!res.writableEnded) { debug?.('destroying proxyRes in proxyRes close event') diff --git a/packages/vite/src/node/server/middlewares/static.ts b/packages/vite/src/node/server/middlewares/static.ts index 33e0bd161e977d..8b41781ce33fb8 100644 --- a/packages/vite/src/node/server/middlewares/static.ts +++ b/packages/vite/src/node/server/middlewares/static.ts @@ -73,7 +73,7 @@ export function servePublicMiddleware( if (filePath.indexOf('%') !== -1) { try { filePath = decodeURI(filePath) - } catch (err) { + } catch { /* malform uri */ } } diff --git a/packages/vite/src/node/server/middlewares/transform.ts b/packages/vite/src/node/server/middlewares/transform.ts index 8f2e76848f2bfc..c5e65ac2d9a557 100644 --- a/packages/vite/src/node/server/middlewares/transform.ts +++ b/packages/vite/src/node/server/middlewares/transform.ts @@ -128,7 +128,7 @@ export function transformMiddleware( return send(req, res, JSON.stringify(map), 'json', { headers: server.config.server.headers, }) - } catch (e) { + } catch { // Outdated source map request for optimized deps, this isn't an error // but part of the normal flow when re-optimizing after missing deps // Send back an empty source map so the browser doesn't issue warnings diff --git a/packages/vite/src/node/server/mixedModuleGraph.ts b/packages/vite/src/node/server/mixedModuleGraph.ts index b943331d47a9a3..74000cce46e245 100644 --- a/packages/vite/src/node/server/mixedModuleGraph.ts +++ b/packages/vite/src/node/server/mixedModuleGraph.ts @@ -271,7 +271,7 @@ export class ModuleGraph { async getModuleByUrl( url: string, - ssr?: boolean, + _ssr?: boolean, ): Promise { // In the mixed graph, the ssr flag was used to resolve the id. const [clientModule, ssrModule] = await Promise.all([ @@ -333,7 +333,7 @@ export class ModuleGraph { invalidateModule( mod: ModuleNode, - seen: Set = new Set(), + seen = new Set(), timestamp: number = Date.now(), isHmr: boolean = false, /** @internal */ diff --git a/packages/vite/src/node/server/moduleGraph.ts b/packages/vite/src/node/server/moduleGraph.ts index d55807b9668d7d..e932285bd91d93 100644 --- a/packages/vite/src/node/server/moduleGraph.ts +++ b/packages/vite/src/node/server/moduleGraph.ts @@ -164,7 +164,7 @@ export class EnvironmentModuleGraph { invalidateModule( mod: EnvironmentModuleNode, - seen: Set = new Set(), + seen = new Set(), timestamp: number = Date.now(), isHmr: boolean = false, /** @internal */ diff --git a/packages/vite/src/node/server/openBrowser.ts b/packages/vite/src/node/server/openBrowser.ts index 740df255c70c4a..ec99a6a475e409 100644 --- a/packages/vite/src/node/server/openBrowser.ts +++ b/packages/vite/src/node/server/openBrowser.ts @@ -104,7 +104,7 @@ async function startBrowserProcess( ) return true } - } catch (err) { + } catch { // Ignore errors } } @@ -135,7 +135,7 @@ async function startBrowserProcess( }) return true - } catch (err) { + } catch { return false } } diff --git a/packages/vite/src/node/server/pluginContainer.ts b/packages/vite/src/node/server/pluginContainer.ts index bca2df727008b3..18c7c2c82aad0e 100644 --- a/packages/vite/src/node/server/pluginContainer.ts +++ b/packages/vite/src/node/server/pluginContainer.ts @@ -633,7 +633,7 @@ class PluginContext implements Omit { return [...this._container.watchFiles] } - emitFile(assetOrFile: EmittedFile): string { + emitFile(_assetOrFile: EmittedFile): string { this._warnIncompatibleMethod(`emitFile`) return '' } diff --git a/packages/vite/src/node/typeUtils.ts b/packages/vite/src/node/typeUtils.ts index 83acb5f5089357..88667bbe965397 100644 --- a/packages/vite/src/node/typeUtils.ts +++ b/packages/vite/src/node/typeUtils.ts @@ -9,7 +9,7 @@ export type NonNeverKeys = { }[keyof T] export type GetHookContextMap = { - [K in keyof Plugin]-?: Plugin[K] extends ObjectHook + [K in keyof Plugin]-?: Plugin[K] extends ObjectHook ? T extends (this: infer This, ...args: any[]) => any ? This extends RollupPluginContext ? This diff --git a/playground/vitestSetup.ts b/playground/vitestSetup.ts index fcf8c7b01903d0..b316bb6924bb18 100644 --- a/playground/vitestSetup.ts +++ b/playground/vitestSetup.ts @@ -351,7 +351,7 @@ export function createInMemoryLogger(logs: string[]): Logger { function setupConsoleWarnCollector(logs: string[]) { const warn = console.warn console.warn = (...args) => { - serverLogs.push(args.join(' ')) + logs.push(args.join(' ')) return warn.call(console, ...args) } }