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-comment #11326

Merged
merged 2 commits into from Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 11 additions & 1 deletion .eslintrc.cjs
Expand Up @@ -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',
Shinigami92 marked this conversation as resolved.
Show resolved Hide resolved
'@typescript-eslint/ban-types': 'off', // TODO: we should turn this on in a new PR
'@typescript-eslint/explicit-module-boundary-types': [
'error',
Expand Down Expand Up @@ -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: {
Expand Down
19 changes: 10 additions & 9 deletions packages/plugin-legacy/src/index.ts
Expand Up @@ -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'

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -752,12 +754,11 @@ function isLegacyBundle(
function recordAndRemovePolyfillBabelPlugin(
polyfills: Set<string>,
): 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)) {
Copy link
Member

Choose a reason for hiding this comment

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

What is the reason for this change?

Copy link
Member Author

Choose a reason for hiding this comment

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

t.isImportDeclaration only expects Node to be passed to the argument. p is NodePath and p.node is Node.
The previous code also works because NodePath and Node both has type property.
https://github.com/babel/babel/blob/df733b18ae88f370caddecc30c6d96844007c411/packages/babel-types/src/validators/generated/index.ts#L1062-L1078
But given that t.isImportDeclaration narrows the argument to ImportDeclaration instead of NodePath<ImportDeclaration>, passing p.node is more correct.

We could use p.isImportDeclaration() instead of t.isImportDeclaration(p.node), too.

Copy link
Member

Choose a reason for hiding this comment

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

Thanks for the explanation, it looks good as is!

polyfills.add(p.node.source.value)
p.remove()
}
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/__tests__/plugins/css.spec.ts
Expand Up @@ -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
Expand All @@ -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() {
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/build.ts
Expand Up @@ -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. ` +
Expand Down
5 changes: 1 addition & 4 deletions 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'
Expand Down Expand Up @@ -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 = (
Expand Down Expand Up @@ -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(
Expand Down
11 changes: 3 additions & 8 deletions packages/vite/src/node/config.ts
Expand Up @@ -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'] = {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/optimizer/optimizer.ts
Expand Up @@ -466,7 +466,7 @@ async function createDepsOptimizer(
}

currentlyProcessing = false
// @ts-ignore
// @ts-expect-error `enqueuedRerun` could exist because `debouncedProcessing` may run while awaited
enqueuedRerun?.()
}

Expand Down
14 changes: 7 additions & 7 deletions packages/vite/src/node/plugins/css.ts
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/esbuild.ts
Expand Up @@ -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]
}
}
Expand Down Expand Up @@ -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
}
Expand Down
12 changes: 3 additions & 9 deletions packages/vite/src/node/plugins/importAnalysisBuild.ts
Expand Up @@ -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<string, boolean>
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()
}
Expand All @@ -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"]' : ''
Expand All @@ -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) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/terser.ts
Expand Up @@ -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
Expand Down
6 changes: 0 additions & 6 deletions packages/vite/src/node/plugins/wasm.ts
Expand Up @@ -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++) {
Expand All @@ -23,27 +22,22 @@ 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
// 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
2 changes: 1 addition & 1 deletion packages/vite/src/node/plugins/worker.ts
Expand Up @@ -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
}
Expand Down
Expand Up @@ -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)
Expand Down
15 changes: 4 additions & 11 deletions packages/vite/src/node/server/index.ts
Expand Up @@ -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
Expand All @@ -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,
Expand Down
3 changes: 1 addition & 2 deletions 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
Expand Down Expand Up @@ -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'),
Expand Down
3 changes: 1 addition & 2 deletions packages/vite/src/node/server/middlewares/time.ts
Expand Up @@ -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()
Expand Down