From e58a4f00e201e9c0d43ddda51ccac7b612d58650 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BF=A0=20/=20green?= Date: Mon, 12 Dec 2022 19:59:02 +0900 Subject: [PATCH] chore: enable `@typescript-eslint/ban-ts-comment` (#11326) --- .eslintrc.cjs | 12 +++++++++++- packages/plugin-legacy/src/index.ts | 19 ++++++++++--------- .../src/node/__tests__/plugins/css.spec.ts | 4 ++-- packages/vite/src/node/build.ts | 3 +-- packages/vite/src/node/cli.ts | 5 +---- packages/vite/src/node/config.ts | 11 +++-------- packages/vite/src/node/optimizer/optimizer.ts | 2 +- packages/vite/src/node/plugins/css.ts | 14 +++++++------- packages/vite/src/node/plugins/esbuild.ts | 4 ++-- .../src/node/plugins/importAnalysisBuild.ts | 12 +++--------- packages/vite/src/node/plugins/terser.ts | 2 +- packages/vite/src/node/plugins/wasm.ts | 6 ------ packages/vite/src/node/plugins/worker.ts | 2 +- .../server/__tests__/pluginContainer.spec.ts | 2 +- packages/vite/src/node/server/index.ts | 15 ++++----------- .../node/server/middlewares/compression.ts | 3 +-- .../vite/src/node/server/middlewares/time.ts | 3 +-- .../vite/src/node/server/pluginContainer.ts | 2 +- packages/vite/src/node/ssr/ssrModuleLoader.ts | 2 +- packages/vite/src/node/utils.ts | 6 ++---- packages/vite/src/types/shims.d.ts | 5 +++++ playground/hmr/hmr.ts | 1 - playground/hmr/modules.d.ts | 3 +++ playground/legacy/vite.config.js | 1 - playground/ssr-noexternal/server.js | 1 - playground/vitestSetup.ts | 13 +++++++++++-- playground/worker/my-shared-worker.ts | 2 +- 27 files changed, 74 insertions(+), 81 deletions(-) create mode 100644 playground/hmr/modules.d.ts diff --git a/.eslintrc.cjs b/.eslintrc.cjs index bfdcd3d4f71cb8..f60f3280712ed6 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -61,7 +61,7 @@ module.exports = defineConfig({ 'node/no-unpublished-require': 'off', 'node/no-unsupported-features/es-syntax': 'off', - '@typescript-eslint/ban-ts-comment': 'off', // TODO: we should turn this on in a new PR + '@typescript-eslint/ban-ts-comment': 'error', '@typescript-eslint/ban-types': 'off', // TODO: we should turn this on in a new PR '@typescript-eslint/explicit-module-boundary-types': [ 'error', @@ -185,6 +185,16 @@ module.exports = defineConfig({ '@typescript-eslint/no-empty-function': 'off', }, }, + { + files: [ + 'playground/tsconfig-json/**', + 'playground/tsconfig-json-load-error/**', + ], + excludedFiles: '**/__tests__/**', + rules: { + '@typescript-eslint/ban-ts-comment': 'off', + }, + }, { files: ['*.js', '*.mjs', '*.cjs'], rules: { diff --git a/packages/plugin-legacy/src/index.ts b/packages/plugin-legacy/src/index.ts index 41f76470d0b13a..3e8b86eee48888 100644 --- a/packages/plugin-legacy/src/index.ts +++ b/packages/plugin-legacy/src/index.ts @@ -18,7 +18,10 @@ import type { PreRenderedChunk, RenderedChunk, } from 'rollup' -import type { PluginItem as BabelPlugin } from '@babel/core' +import type { + PluginItem as BabelPlugin, + types as BabelTypes, +} from '@babel/core' import colors from 'picocolors' import type { Options } from './types' @@ -387,23 +390,22 @@ function viteLegacyPlugin(options: Options = {}): Plugin[] { return null } - // @ts-ignore avoid esbuild transform on legacy chunks since it produces + // @ts-expect-error avoid esbuild transform on legacy chunks since it produces // legacy-unsafe code - e.g. rewriting object properties into shorthands opts.__vite_skip_esbuild__ = true - // @ts-ignore force terser for legacy chunks. This only takes effect if + // @ts-expect-error force terser for legacy chunks. This only takes effect if // minification isn't disabled, because that leaves out the terser plugin // entirely. opts.__vite_force_terser__ = true - // @ts-ignore - // In the `generateBundle` hook, + // @ts-expect-error In the `generateBundle` hook, // we'll delete the assets from the legacy bundle to avoid emitting duplicate assets. // But that's still a waste of computing resource. // So we add this flag to avoid emitting the asset in the first place whenever possible. opts.__vite_skip_asset_emit__ = true - // @ts-ignore avoid emitting assets for legacy bundle + // avoid emitting assets for legacy bundle const needPolyfills = options.polyfills !== false && !Array.isArray(options.polyfills) @@ -752,12 +754,11 @@ function isLegacyBundle( function recordAndRemovePolyfillBabelPlugin( polyfills: Set, ): BabelPlugin { - return ({ types: t }): BabelPlugin => ({ + return ({ types: t }: { types: typeof BabelTypes }): BabelPlugin => ({ name: 'vite-remove-polyfill-import', post({ path }) { path.get('body').forEach((p) => { - if (t.isImportDeclaration(p)) { - // @ts-expect-error + if (t.isImportDeclaration(p.node)) { polyfills.add(p.node.source.value) p.remove() } diff --git a/packages/vite/src/node/__tests__/plugins/css.spec.ts b/packages/vite/src/node/__tests__/plugins/css.spec.ts index 9fca203593d310..fcf42f91667865 100644 --- a/packages/vite/src/node/__tests__/plugins/css.spec.ts +++ b/packages/vite/src/node/__tests__/plugins/css.spec.ts @@ -209,7 +209,7 @@ async function createCssPluginTransform( const config = await resolveConfig(inlineConfig, 'serve') const { transform, buildStart } = cssPlugin(config) - // @ts-expect-error + // @ts-expect-error buildStart is function await buildStart.call({}) const mockFs = vi @@ -221,7 +221,7 @@ async function createCssPluginTransform( return { async transform(code: string, id: string) { - // @ts-expect-error + // @ts-expect-error transform is function return await transform.call( { addWatchFile() { diff --git a/packages/vite/src/node/build.ts b/packages/vite/src/node/build.ts index 4245e61251caab..1e8a9d3739793a 100644 --- a/packages/vite/src/node/build.ts +++ b/packages/vite/src/node/build.ts @@ -546,8 +546,7 @@ async function doBuild( try { const buildOutputOptions = (output: OutputOptions = {}): OutputOptions => { - // See https://github.com/vitejs/vite/issues/5812#issuecomment-984345618 - // @ts-ignore + // @ts-expect-error See https://github.com/vitejs/vite/issues/5812#issuecomment-984345618 if (output.output) { config.logger.warn( `You've set "rollupOptions.output.output" in your config. ` + diff --git a/packages/vite/src/node/cli.ts b/packages/vite/src/node/cli.ts index 8863fd3cd42167..cd9abd75348a83 100644 --- a/packages/vite/src/node/cli.ts +++ b/packages/vite/src/node/cli.ts @@ -1,7 +1,6 @@ import path from 'node:path' import fs from 'node:fs' import { performance } from 'node:perf_hooks' -import type { Session } from 'node:inspector' import { cac } from 'cac' import colors from 'picocolors' import type { BuildOptions } from './build' @@ -32,8 +31,7 @@ interface GlobalCLIOptions { force?: boolean } -// @ts-ignore -let profileSession: Session | undefined = global.__vite_profile_session +let profileSession = global.__vite_profile_session let profileCount = 0 export const stopProfiler = ( @@ -141,7 +139,6 @@ cli const info = server.config.logger.info - // @ts-ignore const viteStartTime = global.__vite_start_time ?? false const startupDurationString = viteStartTime ? colors.dim( diff --git a/packages/vite/src/node/config.ts b/packages/vite/src/node/config.ts index b8a72d1ac13c90..a78079b0b57386 100644 --- a/packages/vite/src/node/config.ts +++ b/packages/vite/src/node/config.ts @@ -462,18 +462,13 @@ export async function resolveConfig( ) const clientAlias = [ - { find: /^\/?@vite\/env/, replacement: () => ENV_ENTRY }, - { find: /^\/?@vite\/client/, replacement: () => CLIENT_ENTRY }, + { find: /^\/?@vite\/env/, replacement: ENV_ENTRY }, + { find: /^\/?@vite\/client/, replacement: CLIENT_ENTRY }, ] // resolve alias with internal client alias const resolvedAlias = normalizeAlias( - mergeAlias( - // @ts-ignore because @rollup/plugin-alias' type doesn't allow function - // replacement, but its implementation does work with function values. - clientAlias, - config.resolve?.alias || [], - ), + mergeAlias(clientAlias, config.resolve?.alias || []), ) const resolveOptions: ResolvedConfig['resolve'] = { diff --git a/packages/vite/src/node/optimizer/optimizer.ts b/packages/vite/src/node/optimizer/optimizer.ts index 2dcb84a3e8f1b9..cbf4e6667e18a9 100644 --- a/packages/vite/src/node/optimizer/optimizer.ts +++ b/packages/vite/src/node/optimizer/optimizer.ts @@ -466,7 +466,7 @@ async function createDepsOptimizer( } currentlyProcessing = false - // @ts-ignore + // @ts-expect-error `enqueuedRerun` could exist because `debouncedProcessing` may run while awaited enqueuedRerun?.() } diff --git a/packages/vite/src/node/plugins/css.ts b/packages/vite/src/node/plugins/css.ts index 9fab5281602e1f..9834858bf1a878 100644 --- a/packages/vite/src/node/plugins/css.ts +++ b/packages/vite/src/node/plugins/css.ts @@ -623,7 +623,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin { }, async generateBundle(opts, bundle) { - // @ts-ignore asset emits are skipped in legacy bundle + // @ts-expect-error asset emits are skipped in legacy bundle if (opts.__vite_skip_asset_emit__) { return } @@ -1149,7 +1149,6 @@ async function resolvePostcssConfig( const searchPath = typeof inlineOptions === 'string' ? inlineOptions : config.root try { - // @ts-ignore result = await postcssrc({}, searchPath) } catch (e) { if (!/No PostCSS Config found/.test(e.message)) { @@ -1508,6 +1507,9 @@ function loadPreprocessor( } } +declare const window: unknown | undefined +declare const location: { href: string } | undefined + // in unix, scss might append `location.href` in environments that shim `location` // see https://github.com/sass/dart-sass/issues/710 function cleanScssBugUrl(url: string) { @@ -1533,12 +1535,10 @@ function fixScssBugImportValue( typeof window !== 'undefined' && typeof location !== 'undefined' && data && - // @ts-expect-error - data.file && - // @ts-expect-error - data.contents == null + 'file' in data && + (!('contents' in data) || data.contents == null) ) { - // @ts-expect-error + // @ts-expect-error we need to preserve file property for HMR data.contents = fs.readFileSync(data.file, 'utf-8') } return data diff --git a/packages/vite/src/node/plugins/esbuild.ts b/packages/vite/src/node/plugins/esbuild.ts index 89e2dab2e54316..1e6e4927e87718 100644 --- a/packages/vite/src/node/plugins/esbuild.ts +++ b/packages/vite/src/node/plugins/esbuild.ts @@ -112,7 +112,7 @@ export async function transformWithEsbuild( for (const field of meaningfulFields) { if (field in loadedCompilerOptions) { - // @ts-ignore TypeScript can't tell they are of the same type + // @ts-expect-error TypeScript can't tell they are of the same type compilerOptionsForFile[field] = loadedCompilerOptions[field] } } @@ -297,7 +297,7 @@ export const buildEsbuildPlugin = (config: ResolvedConfig): Plugin => { await initTSConfck(config) }, async renderChunk(code, chunk, opts) { - // @ts-ignore injected by @vitejs/plugin-legacy + // @ts-expect-error injected by @vitejs/plugin-legacy if (opts.__vite_skip_esbuild__) { return null } diff --git a/packages/vite/src/node/plugins/importAnalysisBuild.ts b/packages/vite/src/node/plugins/importAnalysisBuild.ts index 3a9fe89dd00ac3..0ae2001b91b886 100644 --- a/packages/vite/src/node/plugins/importAnalysisBuild.ts +++ b/packages/vite/src/node/plugins/importAnalysisBuild.ts @@ -52,21 +52,20 @@ function toRelativePath(filename: string, importer: string) { */ function detectScriptRel() { - // @ts-ignore const relList = document.createElement('link').relList - // @ts-ignore return relList && relList.supports && relList.supports('modulepreload') ? 'modulepreload' : 'preload' } declare const scriptRel: string +declare const seen: Record function preload( baseModule: () => Promise<{}>, deps?: string[], importerUrl?: string, ) { - // @ts-ignore + // @ts-expect-error __VITE_IS_MODERN__ will be replaced with boolean later if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) { return baseModule() } @@ -75,11 +74,9 @@ function preload( return Promise.all( deps.map((dep) => { - // @ts-ignore + // @ts-expect-error assetsURL is declared before preload.toString() dep = assetsURL(dep, importerUrl) - // @ts-ignore if (dep in seen) return - // @ts-ignore seen[dep] = true const isCss = dep.endsWith('.css') const cssSelector = isCss ? '[rel="stylesheet"]' : '' @@ -101,16 +98,13 @@ function preload( return } - // @ts-ignore const link = document.createElement('link') - // @ts-ignore link.rel = isCss ? 'stylesheet' : scriptRel if (!isCss) { link.as = 'script' link.crossOrigin = '' } link.href = dep - // @ts-ignore document.head.appendChild(link) if (isCss) { return new Promise((res, rej) => { diff --git a/packages/vite/src/node/plugins/terser.ts b/packages/vite/src/node/plugins/terser.ts index 2d0874231a1cc4..40f28cb9daccaf 100644 --- a/packages/vite/src/node/plugins/terser.ts +++ b/packages/vite/src/node/plugins/terser.ts @@ -49,7 +49,7 @@ export function terserPlugin(config: ResolvedConfig): Plugin { // can use terser. if ( config.build.minify !== 'terser' && - // @ts-ignore injected by @vitejs/plugin-legacy + // @ts-expect-error injected by @vitejs/plugin-legacy !outputOptions.__vite_force_terser__ ) { return null diff --git a/packages/vite/src/node/plugins/wasm.ts b/packages/vite/src/node/plugins/wasm.ts index 866c1b6ae7565d..2dac0aa9259697 100644 --- a/packages/vite/src/node/plugins/wasm.ts +++ b/packages/vite/src/node/plugins/wasm.ts @@ -12,7 +12,6 @@ const wasmHelper = async (opts = {}, url: string) => { if (typeof Buffer === 'function' && typeof Buffer.from === 'function') { bytes = Buffer.from(urlContent, 'base64') } else if (typeof atob === 'function') { - // @ts-ignore const binaryString = atob(urlContent) bytes = new Uint8Array(binaryString.length) for (let i = 0; i < binaryString.length; i++) { @@ -23,7 +22,6 @@ const wasmHelper = async (opts = {}, url: string) => { 'Failed to decode base64-encoded data URL, Buffer and atob are not supported', ) } - // @ts-ignore result = await WebAssembly.instantiate(bytes, opts) } else { // https://github.com/mdn/webassembly-examples/issues/5 @@ -31,19 +29,15 @@ const wasmHelper = async (opts = {}, url: string) => { // correct MIME type for .wasm files, which unfortunately doesn't work for // a lot of static file servers, so we just work around it by getting the // raw buffer. - // @ts-ignore const response = await fetch(url) const contentType = response.headers.get('Content-Type') || '' if ( - // @ts-ignore 'instantiateStreaming' in WebAssembly && contentType.startsWith('application/wasm') ) { - // @ts-ignore result = await WebAssembly.instantiateStreaming(response, opts) } else { const buffer = await response.arrayBuffer() - // @ts-ignore result = await WebAssembly.instantiate(buffer, opts) } } diff --git a/packages/vite/src/node/plugins/worker.ts b/packages/vite/src/node/plugins/worker.ts index acb8c67eb1e88a..62432d0fd94579 100644 --- a/packages/vite/src/node/plugins/worker.ts +++ b/packages/vite/src/node/plugins/worker.ts @@ -387,7 +387,7 @@ export function webWorkerPlugin(config: ResolvedConfig): Plugin { }, generateBundle(opts) { - // @ts-ignore asset emits are skipped in legacy bundle + // @ts-expect-error asset emits are skipped in legacy bundle if (opts.__vite_skip_asset_emit__ || isWorker) { return } diff --git a/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts b/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts index 9b02ab09b18f03..642b1f5608ba3a 100644 --- a/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts +++ b/packages/vite/src/node/server/__tests__/pluginContainer.spec.ts @@ -157,7 +157,7 @@ async function getPluginContainer( 'serve', ) - // @ts-ignore: This plugin requires a ViteDevServer instance. + // @ts-expect-error This plugin requires a ViteDevServer instance. config.plugins = config.plugins.filter((p) => !/pre-alias/.test(p.name)) resolveId = (id) => container.resolveId(id) diff --git a/packages/vite/src/node/server/index.ts b/packages/vite/src/node/server/index.ts index d25ab50aa749e5..f9e84ea1394b20 100644 --- a/packages/vite/src/node/server/index.ts +++ b/packages/vite/src/node/server/index.ts @@ -772,7 +772,6 @@ export function resolveServerOptions( } async function restartServer(server: ViteDevServer) { - // @ts-ignore global.__vite_start_time = performance.now() const { port: prevPort, host: prevHost } = server.config.server const shortcutsOptions: BindShortcutsOptions = server._shortcutsOptions @@ -798,16 +797,10 @@ async function restartServer(server: ViteDevServer) { return } - for (const key in newServer) { - if (key === '_restartPromise') { - // prevent new server `restart` function from calling - // @ts-ignore - newServer[key] = server[key] - } else { - // @ts-ignore - server[key] = newServer[key] - } - } + // prevent new server `restart` function from calling + newServer._restartPromise = server._restartPromise + + Object.assign(server, newServer) const { logger, diff --git a/packages/vite/src/node/server/middlewares/compression.ts b/packages/vite/src/node/server/middlewares/compression.ts index e2134a224b47be..e7ecb406645c18 100644 --- a/packages/vite/src/node/server/middlewares/compression.ts +++ b/packages/vite/src/node/server/middlewares/compression.ts @@ -1,5 +1,5 @@ -//@ts-nocheck /* eslint-disable */ +//@ts-nocheck //TODO: replace this code with https://github.com/lukeed/polka/pull/148 once it's released // This is based on https://github.com/preactjs/wmr/blob/main/packages/wmr/src/lib/polkompress.js @@ -44,7 +44,6 @@ export default function compression() { function start() { started = true - // @ts-ignore size = res.getHeader('Content-Length') | 0 || size const compressible = mimes.test( String(res.getHeader('Content-Type') || 'text/plain'), diff --git a/packages/vite/src/node/server/middlewares/time.ts b/packages/vite/src/node/server/middlewares/time.ts index 7fdc7172f1ed58..1217361d84fb35 100644 --- a/packages/vite/src/node/server/middlewares/time.ts +++ b/packages/vite/src/node/server/middlewares/time.ts @@ -9,9 +9,8 @@ export function timeMiddleware(root: string): Connect.NextHandleFunction { return function viteTimeMiddleware(req, res, next) { const start = performance.now() const end = res.end - res.end = (...args: any[]) => { + res.end = (...args: readonly [any, any?, any?]) => { logTime(`${timeFrom(start)} ${prettifyUrl(req.url!, root)}`) - // @ts-ignore return end.call(res, ...args) } next() diff --git a/packages/vite/src/node/server/pluginContainer.ts b/packages/vite/src/node/server/pluginContainer.ts index 5bed7121b877e2..15ae3f6d738bf0 100644 --- a/packages/vite/src/node/server/pluginContainer.ts +++ b/packages/vite/src/node/server/pluginContainer.ts @@ -201,7 +201,7 @@ export async function createPluginContainer( for (const plugin of getSortedPlugins(hookName)) { const hook = plugin[hookName] if (!hook) continue - // @ts-expect-error + // @ts-expect-error hook is not a primitive const handler: Function = 'handler' in hook ? hook.handler : hook if ((hook as { sequential?: boolean }).sequential) { await Promise.all(parallelPromises) diff --git a/packages/vite/src/node/ssr/ssrModuleLoader.ts b/packages/vite/src/node/ssr/ssrModuleLoader.ts index 8f1b377ab70060..4952eed7645a79 100644 --- a/packages/vite/src/node/ssr/ssrModuleLoader.ts +++ b/packages/vite/src/node/ssr/ssrModuleLoader.ts @@ -234,7 +234,7 @@ async function nodeImport( importer, // Non-external modules can import ESM-only modules, but only outside // of test runs, because we use Node `require` in Jest to avoid segfault. - // @ts-expect-error + // @ts-expect-error jest only exists when running Jest typeof jest === 'undefined' ? { ...resolveOptions, tryEsmOnly: true } : resolveOptions, diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 2aeaf0691b39cb..b78d003a6001ed 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -881,10 +881,8 @@ export async function resolveServerUrls( (detail) => detail && detail.address && - // Node < v18 ((typeof detail.family === 'string' && detail.family === 'IPv4') || - // Node >= v18 - // @ts-expect-error + // @ts-expect-error Node 18.0 - 18.3 returns number (typeof detail.family === 'number' && detail.family === 4)), ) .forEach((detail) => { @@ -913,7 +911,7 @@ export const multilineCommentsRE = /\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\//g export const singlelineCommentsRE = /\/\/.*/g export const requestQuerySplitRE = /\?(?!.*[/|}])/ -// @ts-expect-error +// @ts-expect-error jest only exists when running Jest export const usingDynamicImport = typeof jest === 'undefined' /** diff --git a/packages/vite/src/types/shims.d.ts b/packages/vite/src/types/shims.d.ts index 3540828cc2a14e..4e31945d0449ae 100644 --- a/packages/vite/src/types/shims.d.ts +++ b/packages/vite/src/types/shims.d.ts @@ -39,3 +39,8 @@ declare module 'postcss-import' { // LESS' types somewhat references this which doesn't make sense in Node, // so we have to shim it declare interface HTMLLinkElement {} + +// eslint-disable-next-line no-var, @typescript-eslint/consistent-type-imports +declare var __vite_profile_session: import('node:inspector').Session | undefined +// eslint-disable-next-line no-var +declare var __vite_start_time: number | undefined diff --git a/playground/hmr/hmr.ts b/playground/hmr/hmr.ts index a9c1e332d529e3..b4b23a949da783 100644 --- a/playground/hmr/hmr.ts +++ b/playground/hmr/hmr.ts @@ -1,4 +1,3 @@ -// @ts-ignore import { virtual } from 'virtual:file' import { foo as depFoo, nestedFoo } from './hmrDep' import './importing-updated' diff --git a/playground/hmr/modules.d.ts b/playground/hmr/modules.d.ts new file mode 100644 index 00000000000000..122559a692ef20 --- /dev/null +++ b/playground/hmr/modules.d.ts @@ -0,0 +1,3 @@ +declare module 'virtual:file' { + export const virtual: string +} diff --git a/playground/legacy/vite.config.js b/playground/legacy/vite.config.js index df3df8d6f190de..7adf0f784eeeb2 100644 --- a/playground/legacy/vite.config.js +++ b/playground/legacy/vite.config.js @@ -30,7 +30,6 @@ module.exports = { }, }, - // special test only hook // for tests, remove `