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 @typescript-eslint/ban-ts-comments #8413

Closed
wants to merge 4 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
2 changes: 1 addition & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,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',
Expand Down
12 changes: 5 additions & 7 deletions packages/plugin-legacy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import type {
RenderedChunk
} from 'rollup'
import type { PluginItem as BabelPlugin } from '@babel/core'
import type { ImportDeclaration } from '@babel/types'
import type { Options } from './types'

// lazy load babel since it's not used during dev
Expand Down Expand Up @@ -283,23 +284,21 @@ 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
const needPolyfills =
options.polyfills !== false && !Array.isArray(options.polyfills)

Expand Down Expand Up @@ -661,8 +660,7 @@ function recordAndRemovePolyfillBabelPlugin(
post({ path }) {
path.get('body').forEach((p) => {
if (t.isImportDeclaration(p)) {
// @ts-expect-error
polyfills.add(p.node.source.value)
polyfills.add((p.node as ImportDeclaration).source.value)
p.remove()
}
})
Expand Down
5 changes: 3 additions & 2 deletions packages/plugin-react/src/jsx-runtime/restore-jsx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ async function getBabelRestoreJSX() {
if (!babelRestoreJSX)
babelRestoreJSX = import('./babel-restore-jsx').then((r) => {
const fn = r.default
if ('default' in fn)
// @ts-expect-error
if ('default' in fn) {
// @ts-expect-error TypeScript can't infer `fn` has `default
return fn.default
}
return fn
})
return babelRestoreJSX
Expand Down
11 changes: 7 additions & 4 deletions packages/plugin-vue-jsx/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const ssrRegisterHelperCode =
function ssrRegisterHelper(comp: ComponentOptions, filename: string) {
const setup = comp.setup
comp.setup = (props, ctx) => {
// @ts-ignore
// @ts-expect-error injected in a virtual module during SSR
const ssrContext = useSSRContext()
;(ssrContext.modules || (ssrContext.modules = new Set())).add(filename)
if (setup) {
Expand Down Expand Up @@ -88,14 +88,17 @@ function vueJsxPlugin(options: Options = {}): Plugin {
// use id for script blocks in Vue SFCs (e.g. `App.vue?vue&type=script&lang.jsx`)
// use filepath for plain jsx files (e.g. App.jsx)
if (filter(id) || filter(filepath)) {
const plugins = [importMeta, [jsx, babelPluginOptions], ...babelPlugins]
const plugins: babel.PluginItem[] = [
importMeta,
[jsx, babelPluginOptions],
...babelPlugins
]
if (id.endsWith('.tsx') || filepath.endsWith('.tsx')) {
plugins.push([
// @ts-ignore missing type
// @ts-expect-error missing type
await import('@babel/plugin-transform-typescript').then(
(r) => r.default
),
// @ts-ignore
{ isTSX: true, allowExtensions: true }
])
}
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 @@ -72,7 +72,7 @@ describe('css path resolutions', () => {

const mockFs = vi
.spyOn(fs, 'readFile')
// @ts-ignore vi.spyOn not recognize override `fs.readFile` definition.
// @ts-expect-error vi.spyOn not recognize override `fs.readFile` definition.
.mockImplementationOnce((p, encoding, callback) => {
expect(p).toBe(path.join(mockedProjectPath, mockedBarCssRelativePath))
expect(encoding).toBe('utf-8')
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,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 `OutputOptions.output.output` is deprecated
if (output.output) {
config.logger.warn(
`You've set "rollupOptions.output.output" in your config. ` +
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/certificate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

// @ts-ignore
// @ts-expect-error missing types
import forge from 'node-forge/lib/forge'
// @ts-ignore
import 'node-forge/lib/pki'

// a hexString is considered negative if it's most significant bit is 1
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ cli

const info = server.config.logger.info

// @ts-ignore
// @ts-expect-error missing types
const viteStartTime = global.__vite_start_time ?? false
const startupDurationString = viteStartTime
? colors.dim(
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ export async function resolveConfig(
// resolve alias with internal client alias
const resolvedAlias = normalizeAlias(
mergeAlias(
// @ts-ignore because @rollup/plugin-alias' type doesn't allow function
// @ts-expect-error because @rollup/plugin-alias' type doesn't allow function
// replacement, but its implementation does work with function values.
clientAlias,
config.resolve?.alias || []
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/constants.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path, { resolve } from 'path'
import { fileURLToPath } from 'url'
// @ts-expect-error
// @ts-expect-error Cannot import JSON files by default
import { version } from '../../package.json'

export const VERSION = version as string
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export async function initDepsOptimizer(
firstRunCalled = true

// Ensure that rerun is called sequentially
enqueuedRerun = undefined
enqueuedRerun = undefined as typeof enqueuedRerun

// Ensure that a rerun will not be issued for current discovered deps
if (handle) clearTimeout(handle)
Expand Down Expand Up @@ -379,7 +379,6 @@ export async function initDepsOptimizer(
}

currentlyProcessing = false
// @ts-ignore
enqueuedRerun?.()
}

Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,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
}
Expand Down Expand Up @@ -987,7 +987,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)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,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]
}
}
Expand Down Expand Up @@ -231,7 +231,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
}
Expand Down
1 change: 0 additions & 1 deletion packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,6 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
d: dynamicIndex,
// #2083 User may use escape path,
// so use imports[index].n to get the unescaped string
// @ts-ignore
n: specifier
} = imports[index]

Expand Down
14 changes: 4 additions & 10 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,49 +46,43 @@ const optimizedDepDynamicRE = /-[A-Z0-9]{8}\.js/
*/

function detectScriptRel() {
// @ts-ignore
const relList = document.createElement('link').relList
// @ts-ignore
return relList && relList.supports && relList.supports('modulepreload')
? 'modulepreload'
: 'preload'
}

declare const __VITE_IS_MODERN__: boolean
declare const scriptRel: string
declare function assetsURL(dep: string, importUrl?: string): string
declare const seen: { [dep: string]: boolean }

function preload(
baseModule: () => Promise<{}>,
deps?: string[],
importerUrl?: string
) {
// @ts-ignore
if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {
return baseModule()
}

return Promise.all(
deps.map((dep) => {
// @ts-ignore
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"]' : ''
// @ts-ignore check if the file is already preloaded by SSR markup
if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) {
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) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/terser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,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
Expand Down
6 changes: 0 additions & 6 deletions packages/vite/src/node/plugins/wasm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,27 @@ const wasmHelperId = '/__vite-wasm-helper'
const wasmHelper = async (opts = {}, url: string) => {
let result
if (url.startsWith('data:')) {
// @ts-ignore
const binaryString = atob(url.replace(/^data:.*?base64,/, ''))
const bytes = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
// @ts-ignore
result = await WebAssembly.instantiate(bytes, opts)
} else {
// https://github.com/mdn/webassembly-examples/issues/5
// WebAssembly.instantiateStreaming requires the server to provide the
// 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)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,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)
Expand Down
7 changes: 3 additions & 4 deletions packages/vite/src/node/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,7 @@ async function startServer(
logger: server.config.logger
})

// @ts-ignore
// @ts-expect-error missing types
const profileSession = global.__vite_profile_session
if (profileSession) {
profileSession.post('Profiler.stop', (err: any, { profile }: any) => {
Expand Down Expand Up @@ -690,7 +690,7 @@ export function resolveServerOptions(
}

async function restartServer(server: ViteDevServer) {
// @ts-ignore
// @ts-expect-error missing types
global.__vite_start_time = performance.now()
const { port: prevPort, host: prevHost } = server.config.server

Expand Down Expand Up @@ -718,10 +718,9 @@ async function restartServer(server: ViteDevServer) {
for (const key in newServer) {
if (key === '_restartPromise') {
// prevent new server `restart` function from calling
// @ts-ignore
newServer[key] = server[key]
} else if (key !== 'app') {
// @ts-ignore
// @ts-expect-error The type of `key` is a actually `keyof ViteDevServer`
server[key] = newServer[key]
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/compression.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/server/middlewares/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function timeMiddleware(root: string): Connect.NextHandleFunction {
const end = res.end
res.end = (...args: any[]) => {
logTime(`${timeFrom(start)} ${prettifyUrl(req.url!, root)}`)
// @ts-ignore
// @ts-expect-error TypeScript can't infer this is a safe assignment
return end.call(res, ...args)
}
next()
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/ssr/ssrModuleLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,7 @@ async function instantiateModule(
return Object.freeze(ssrModule)
}

declare const jest: any | undefined
// In node@12+ we can use dynamic import to load CJS and ESM
async function nodeImport(
id: string,
Expand Down Expand Up @@ -286,7 +287,6 @@ 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
typeof jest === 'undefined'
? { ...resolveOptions, tryEsmOnly: true }
: resolveOptions
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,7 @@ export const multilineCommentsRE = /\/\*(.|[\r\n])*?\*\//gm
export const singlelineCommentsRE = /\/\/.*/g
export const requestQuerySplitRE = /\?(?!.*[\/|\}])/

// @ts-expect-error
declare const jest: any | undefined
export const usingDynamicImport = typeof jest === 'undefined'

/**
Expand Down