Skip to content

Commit ea802f8

Browse files
authored
refactor: fix logic errors found by no-unnecessary-condition rule (#18891)
1 parent 690a36f commit ea802f8

35 files changed

+172
-205
lines changed

Diff for: packages/create-vite/src/index.ts

+6-5
Original file line numberDiff line numberDiff line change
@@ -289,9 +289,10 @@ const FRAMEWORKS: Framework[] = [
289289
},
290290
]
291291

292-
const TEMPLATES = FRAMEWORKS.map(
293-
(f) => (f.variants && f.variants.map((v) => v.name)) || [f.name],
294-
).reduce((a, b) => a.concat(b), [])
292+
const TEMPLATES = FRAMEWORKS.map((f) => f.variants.map((v) => v.name)).reduce(
293+
(a, b) => a.concat(b),
294+
[],
295+
)
295296

296297
const renameFiles: Record<string, string | undefined> = {
297298
_gitignore: '.gitignore',
@@ -394,8 +395,8 @@ async function init() {
394395
}),
395396
},
396397
{
397-
type: (framework: Framework) =>
398-
framework && framework.variants ? 'select' : null,
398+
type: (framework: Framework | /* package name */ string) =>
399+
typeof framework === 'object' ? 'select' : null,
399400
name: 'variant',
400401
message: reset('Select a variant:'),
401402
choices: (framework: Framework) =>

Diff for: packages/vite/src/client/overlay.ts

+14-16
Original file line numberDiff line numberDiff line change
@@ -264,23 +264,21 @@ export class ErrorOverlay extends HTMLElement {
264264
fileRE.lastIndex = 0
265265
while ((match = fileRE.exec(text))) {
266266
const { 0: file, index } = match
267-
if (index != null) {
268-
const frag = text.slice(curIndex, index)
269-
el.appendChild(document.createTextNode(frag))
270-
const link = document.createElement('a')
271-
link.textContent = file
272-
link.className = 'file-link'
273-
link.onclick = () => {
274-
fetch(
275-
new URL(
276-
`${base}__open-in-editor?file=${encodeURIComponent(file)}`,
277-
import.meta.url,
278-
),
279-
)
280-
}
281-
el.appendChild(link)
282-
curIndex += frag.length + file.length
267+
const frag = text.slice(curIndex, index)
268+
el.appendChild(document.createTextNode(frag))
269+
const link = document.createElement('a')
270+
link.textContent = file
271+
link.className = 'file-link'
272+
link.onclick = () => {
273+
fetch(
274+
new URL(
275+
`${base}__open-in-editor?file=${encodeURIComponent(file)}`,
276+
import.meta.url,
277+
),
278+
)
283279
}
280+
el.appendChild(link)
281+
curIndex += frag.length + file.length
284282
}
285283
}
286284
}

Diff for: packages/vite/src/module-runner/hmrHandler.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -151,11 +151,11 @@ function getModulesEntrypoints(
151151
if (!module) {
152152
continue
153153
}
154-
if (module.importers && !module.importers.size) {
154+
if (!module.importers.size) {
155155
entrypoints.add(module.url)
156156
continue
157157
}
158-
for (const importer of module.importers || []) {
158+
for (const importer of module.importers) {
159159
getModulesEntrypoints(runner, [importer], visited, entrypoints)
160160
}
161161
}
@@ -167,7 +167,7 @@ function findAllEntrypoints(
167167
entrypoints = new Set<string>(),
168168
): Set<string> {
169169
for (const mod of runner.evaluatedModules.idToModuleMap.values()) {
170-
if (mod.importers && !mod.importers.size) {
170+
if (!mod.importers.size) {
171171
entrypoints.add(mod.url)
172172
}
173173
}

Diff for: packages/vite/src/module-runner/sourcemap/interceptor.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ function mapSourcePosition(position: OriginalMapping) {
210210
}
211211

212212
// Resolve the source URL relative to the URL of the source map
213-
if (sourceMap && sourceMap.map && sourceMap.url) {
213+
if (sourceMap.map && sourceMap.url) {
214214
const originalPosition = getOriginalPosition(sourceMap.map, position)
215215

216216
// Only return the original position if a matching line was found. If no

Diff for: packages/vite/src/node/build.ts

+8-8
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ export function resolveBuildEnvironmentOptions(
391391
logger: Logger,
392392
consumer: 'client' | 'server' | undefined,
393393
): ResolvedBuildEnvironmentOptions {
394-
const deprecatedPolyfillModulePreload = raw?.polyfillModulePreload
394+
const deprecatedPolyfillModulePreload = raw.polyfillModulePreload
395395
const { polyfillModulePreload, ...rest } = raw
396396
raw = rest
397397
if (deprecatedPolyfillModulePreload !== undefined) {
@@ -543,7 +543,7 @@ async function buildEnvironment(
543543

544544
const resolve = (p: string) => path.resolve(root, p)
545545
const input = libOptions
546-
? options.rollupOptions?.input ||
546+
? options.rollupOptions.input ||
547547
(typeof libOptions.entry === 'string'
548548
? resolve(libOptions.entry)
549549
: Array.isArray(libOptions.entry)
@@ -556,7 +556,7 @@ async function buildEnvironment(
556556
))
557557
: typeof options.ssr === 'string'
558558
? resolve(options.ssr)
559-
: options.rollupOptions?.input || resolve('index.html')
559+
: options.rollupOptions.input || resolve('index.html')
560560

561561
if (ssr && typeof input === 'string' && input.endsWith('.html')) {
562562
throw new Error(
@@ -596,7 +596,7 @@ async function buildEnvironment(
596596
output: options.rollupOptions.output,
597597
input,
598598
plugins,
599-
external: options.rollupOptions?.external,
599+
external: options.rollupOptions.external,
600600
onwarn(warning, warn) {
601601
onRollupWarning(warning, warn, environment)
602602
},
@@ -743,7 +743,7 @@ async function buildEnvironment(
743743

744744
// resolve lib mode outputs
745745
const outputs = resolveBuildOutputs(
746-
options.rollupOptions?.output,
746+
options.rollupOptions.output,
747747
libOptions,
748748
logger,
749749
)
@@ -760,7 +760,7 @@ async function buildEnvironment(
760760
const resolvedOutDirs = getResolvedOutDirs(
761761
root,
762762
options.outDir,
763-
options.rollupOptions?.output,
763+
options.rollupOptions.output,
764764
)
765765
const emptyOutDir = resolveEmptyOutDir(
766766
options.emptyOutDir,
@@ -1058,7 +1058,7 @@ export function onRollupWarning(
10581058
}
10591059

10601060
clearLine()
1061-
const userOnWarn = environment.config.build.rollupOptions?.onwarn
1061+
const userOnWarn = environment.config.build.rollupOptions.onwarn
10621062
if (userOnWarn) {
10631063
userOnWarn(warning, viteWarn)
10641064
} else {
@@ -1441,7 +1441,7 @@ export class BuildEnvironment extends BaseEnvironment {
14411441
if (setup?.options) {
14421442
options = mergeConfig(
14431443
options,
1444-
setup?.options,
1444+
setup.options,
14451445
) as ResolvedEnvironmentOptions
14461446
}
14471447
super(name, config, options)

Diff for: packages/vite/src/node/config.ts

+23-30
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import {
2525
FS_PREFIX,
2626
} from './constants'
2727
import type {
28+
FalsyPlugin,
2829
HookHandler,
2930
Plugin,
3031
PluginOption,
@@ -1002,7 +1003,7 @@ export async function resolveConfig(
10021003
mode = inlineConfig.mode || config.mode || mode
10031004
configEnv.mode = mode
10041005

1005-
const filterPlugin = (p: Plugin) => {
1006+
const filterPlugin = (p: Plugin | FalsyPlugin): p is Plugin => {
10061007
if (!p) {
10071008
return false
10081009
} else if (!p.apply) {
@@ -1015,9 +1016,9 @@ export async function resolveConfig(
10151016
}
10161017

10171018
// resolve plugins
1018-
const rawPlugins = (
1019-
(await asyncFlatten(config.plugins || [])) as Plugin[]
1020-
).filter(filterPlugin)
1019+
const rawPlugins = (await asyncFlatten(config.plugins || [])).filter(
1020+
filterPlugin,
1021+
)
10211022

10221023
const [prePlugins, normalPlugins, postPlugins] = sortUserPlugins(rawPlugins)
10231024

@@ -1068,12 +1069,12 @@ export async function resolveConfig(
10681069
// Backward compatibility: server.warmup.clientFiles/ssrFiles -> environment.dev.warmup
10691070
const warmupOptions = config.server?.warmup
10701071
if (warmupOptions?.clientFiles) {
1071-
configEnvironmentsClient.dev.warmup = warmupOptions?.clientFiles
1072+
configEnvironmentsClient.dev.warmup = warmupOptions.clientFiles
10721073
}
10731074
if (warmupOptions?.ssrFiles) {
10741075
configEnvironmentsSsr ??= {}
10751076
configEnvironmentsSsr.dev ??= {}
1076-
configEnvironmentsSsr.dev.warmup = warmupOptions?.ssrFiles
1077+
configEnvironmentsSsr.dev.warmup = warmupOptions.ssrFiles
10771078
}
10781079

10791080
// Backward compatibility: merge ssr into environments.ssr.config as defaults
@@ -1102,11 +1103,7 @@ export async function resolveConfig(
11021103
}
11031104

11041105
// The client and ssr environment configs can't be removed by the user in the config hook
1105-
if (
1106-
!config.environments ||
1107-
!config.environments.client ||
1108-
(!config.environments.ssr && !isBuild)
1109-
) {
1106+
if (!config.environments.client || (!config.environments.ssr && !isBuild)) {
11101107
throw new Error(
11111108
'Required environments configuration were stripped out in the config hook',
11121109
)
@@ -1244,7 +1241,7 @@ export async function resolveConfig(
12441241
? !isBuild || config.build?.ssr
12451242
? '/'
12461243
: './'
1247-
: (resolveBaseUrl(config.base, isBuild, logger) ?? configDefaults.base)
1244+
: resolveBaseUrl(config.base, isBuild, logger)
12481245

12491246
// resolve cache directory
12501247
const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir
@@ -1301,7 +1298,7 @@ export async function resolveConfig(
13011298
// And Plugins may also have cached that could be corrupted by being used in these extra rollup calls.
13021299
// So we need to separate the worker plugin from the plugin that vite needs to run.
13031300
const rawWorkerUserPlugins = (
1304-
(await asyncFlatten(createUserWorkerPlugins?.() || [])) as Plugin[]
1301+
await asyncFlatten(createUserWorkerPlugins?.() || [])
13051302
).filter(filterPlugin)
13061303

13071304
// resolve worker
@@ -1577,7 +1574,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter
15771574
* electron or expects to deploy
15781575
*/
15791576
export function resolveBaseUrl(
1580-
base: UserConfig['base'] = '/',
1577+
base: UserConfig['base'] = configDefaults.base,
15811578
isBuild: boolean,
15821579
logger: Logger,
15831580
): string {
@@ -1846,7 +1843,7 @@ async function bundleConfigFile(
18461843
const { text } = result.outputFiles[0]
18471844
return {
18481845
code: text,
1849-
dependencies: result.metafile ? Object.keys(result.metafile.inputs) : [],
1846+
dependencies: Object.keys(result.metafile.inputs),
18501847
}
18511848
}
18521849

@@ -1934,11 +1931,9 @@ async function runConfigHook(
19341931
for (const p of getSortedPluginsByHook('config', plugins)) {
19351932
const hook = p.config
19361933
const handler = getHookHandler(hook)
1937-
if (handler) {
1938-
const res = await handler(conf, configEnv)
1939-
if (res && res !== conf) {
1940-
conf = mergeConfig(conf, res)
1941-
}
1934+
const res = await handler(conf, configEnv)
1935+
if (res && res !== conf) {
1936+
conf = mergeConfig(conf, res)
19421937
}
19431938
}
19441939

@@ -1955,15 +1950,13 @@ async function runConfigEnvironmentHook(
19551950
for (const p of getSortedPluginsByHook('configEnvironment', plugins)) {
19561951
const hook = p.configEnvironment
19571952
const handler = getHookHandler(hook)
1958-
if (handler) {
1959-
for (const name of environmentNames) {
1960-
const res = await handler(name, environments[name], {
1961-
...configEnv,
1962-
isSsrTargetWebworker: isSsrTargetWebworkerSet && name === 'ssr',
1963-
})
1964-
if (res) {
1965-
environments[name] = mergeConfig(environments[name], res)
1966-
}
1953+
for (const name of environmentNames) {
1954+
const res = await handler(name, environments[name], {
1955+
...configEnv,
1956+
isSsrTargetWebworker: isSsrTargetWebworkerSet && name === 'ssr',
1957+
})
1958+
if (res) {
1959+
environments[name] = mergeConfig(environments[name], res)
19671960
}
19681961
}
19691962
}
@@ -1977,7 +1970,7 @@ function optimizeDepsDisabledBackwardCompatibility(
19771970
const optimizeDepsDisabled = optimizeDeps.disabled
19781971
if (optimizeDepsDisabled !== undefined) {
19791972
if (optimizeDepsDisabled === true || optimizeDepsDisabled === 'dev') {
1980-
const commonjsOptionsInclude = resolved.build?.commonjsOptions?.include
1973+
const commonjsOptionsInclude = resolved.build.commonjsOptions.include
19811974
const commonjsPluginDisabled =
19821975
Array.isArray(commonjsOptionsInclude) &&
19831976
commonjsOptionsInclude.length === 0

Diff for: packages/vite/src/node/external.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export function createIsConfiguredAsExternal(
6161
!(Array.isArray(noExternal) && noExternal.length === 0) &&
6262
createFilter(undefined, noExternal, { resolve: false })
6363

64-
const targetConditions = resolve.externalConditions || []
64+
const targetConditions = resolve.externalConditions
6565

6666
const resolveOptions: InternalResolveOptions = {
6767
...resolve,

Diff for: packages/vite/src/node/optimizer/esbuildDepPlugin.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ export function esbuildDepPlugin(
5757

5858
// remove optimizable extensions from `externalTypes` list
5959
const allExternalTypes = extensions
60-
? externalTypes.filter((type) => !extensions?.includes('.' + type))
60+
? externalTypes.filter((type) => !extensions.includes('.' + type))
6161
: externalTypes
6262

6363
// use separate package cache for optimizer as it caches paths around node_modules

0 commit comments

Comments
 (0)