Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

refactor(vite): enable strict type checking #6616

Merged
merged 4 commits into from
Aug 15, 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
"unctx": "^2.0.1",
"unenv": "^0.5.4",
"unimport": "^0.6.7",
"unplugin": "^0.9.0",
"unplugin": "^0.9.2",
"untyped": "^0.4.5",
"vue": "^3.2.37",
"vue-bundle-renderer": "^0.4.2",
Expand Down
4 changes: 3 additions & 1 deletion packages/nuxt/src/core/plugins/unctx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ export const UnctxTransformPlugin = (nuxt: Nuxt) => {
if (result) {
return {
code: result.code,
map: options.sourcemap && result.magicString.generateMap({ source: id, includeContent: true })
map: options.sourcemap
? result.magicString.generateMap({ source: id, includeContent: true })
: undefined
}
}
}
Expand Down
15 changes: 10 additions & 5 deletions packages/nuxt/src/pages/macros.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const TransformMacroPlugin = createUnplugin((options: TransformMacroPlugi
name: 'nuxt:pages-macros-transform',
enforce: 'post',
transformInclude (id) {
if (!id || id.startsWith('\x00')) { return }
if (!id || id.startsWith('\x00')) { return false }
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
return pathname.endsWith('.vue') || !!parseQuery(search).macro
},
Expand All @@ -26,7 +26,12 @@ export const TransformMacroPlugin = createUnplugin((options: TransformMacroPlugi

function result () {
if (s.hasChanged()) {
return { code: s.toString(), map: options.sourcemap && s.generateMap({ source: id, includeContent: true }) }
return {
code: s.toString(),
map: options.sourcemap
? s.generateMap({ source: id, includeContent: true })
: undefined
}
}
}

Expand All @@ -35,7 +40,7 @@ export const TransformMacroPlugin = createUnplugin((options: TransformMacroPlugi
for (const macro in options.macros) {
const match = code.match(new RegExp(`\\b${macro}\\s*\\(\\s*`))
if (match?.[0]) {
s.overwrite(match.index, match.index + match[0].length, `/*#__PURE__*/ false && ${match[0]}`)
s.overwrite(match.index!, match.index! + match[0].length, `/*#__PURE__*/ false && ${match[0]}`)
}
}

Expand Down Expand Up @@ -113,13 +118,13 @@ function extractObject (code: string) {
// Strip comments
code = code.replace(/^\s*\/\/.*$/gm, '')

const stack = []
const stack: string[] = []
let result = ''
do {
if (stack[0] === code[0] && result.slice(-1) !== '\\') {
stack.shift()
} else if (code[0] in starts && !QUOTE_RE.test(stack[0])) {
stack.unshift(starts[code[0]])
stack.unshift(starts[code[0] as keyof typeof starts])
}
result += code[0]
code = code.slice(1)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"rollup": "^2.78.0",
"rollup-plugin-visualizer": "^5.7.1",
"ufo": "^0.8.5",
"unplugin": "^0.9.0",
"unplugin": "^0.9.2",
"vite": "~3.0.7",
"vite-node": "^0.21.1",
"vite-plugin-checker": "^0.4.9",
Expand Down
14 changes: 7 additions & 7 deletions packages/vite/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,11 @@ export async function buildClient (ctx: ViteBuildContext) {
// In build mode we explicitly override any vite options that vite is relying on
// to detect whether to inject production or development code (such as HMR code)
if (!ctx.nuxt.options.dev) {
clientConfig.server.hmr = false
clientConfig.server!.hmr = false
}

// We want to respect users' own rollup output options
ctx.config.build.rollupOptions = defu(ctx.config.build.rollupOptions, {
ctx.config.build!.rollupOptions = defu(ctx.config.build!.rollupOptions!, {
output: {
// https://github.com/vitejs/vite/tree/main/packages/vite/src/node/build.ts#L464-L478
assetFileNames: ctx.nuxt.options.dev ? undefined : withoutLeadingSlash(join(ctx.nuxt.options.app.buildAssetsDir, '[name].[hash].[ext]')),
Expand All @@ -84,7 +84,7 @@ export async function buildClient (ctx: ViteBuildContext) {
}
})

if (clientConfig.server.hmr !== false) {
if (clientConfig.server && clientConfig.server.hmr !== false) {
const hmrPortDefault = 24678 // Vite's default HMR port
const hmrPort = await getPort({
port: hmrPortDefault,
Expand All @@ -99,7 +99,7 @@ export async function buildClient (ctx: ViteBuildContext) {

// Add analyze plugin if needed
if (ctx.nuxt.options.build.analyze) {
clientConfig.plugins.push(...await import('./plugins/analyze').then(r => r.analyzePlugin(ctx)))
clientConfig.plugins!.push(...await import('./plugins/analyze').then(r => r.analyzePlugin(ctx)))
}

await ctx.nuxt.callHook('vite:extendConfig', clientConfig, { isClient: true, isServer: false })
Expand All @@ -113,9 +113,9 @@ export async function buildClient (ctx: ViteBuildContext) {
const BASE_RE = new RegExp(`^${escapeRE(withTrailingSlash(withLeadingSlash(baseURL)))}`)
const viteMiddleware: Connect.NextHandleFunction = (req, res, next) => {
// Workaround: vite devmiddleware modifies req.url
const originalURL = req.url
req.url = req.url.replace(BASE_RE, '/')
viteServer.middlewares.handle(req, res, (err) => {
const originalURL = req.url!
req.url = originalURL.replace(BASE_RE, '/')
viteServer.middlewares.handle(req, res, (err: unknown) => {
req.url = originalURL
next(err)
})
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { ViteOptions } from './vite'
import { distDir } from './dirs'

export function resolveCSSOptions (nuxt: Nuxt): ViteOptions['css'] {
const css: ViteOptions['css'] & { postcss: Exclude<ViteOptions['css']['postcss'], string> } = {
const css: ViteOptions['css'] & { postcss: NonNullable<Exclude<NonNullable<ViteOptions['css']>['postcss'], string>> } = {
postcss: {
plugins: []
}
Expand Down
8 changes: 4 additions & 4 deletions packages/vite/src/dev-bundler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ async function transformRequest (opts: TransformOptions, id: string) {
const externalId = id.replace(/\?v=\w+$|^\/@fs/, '')

if (await opts.isExternal(externalId)) {
const path = builtinModules.includes(externalId.split('node:').pop())
const path = builtinModules.includes(externalId.split('node:').pop()!)
? externalId
: isAbsolute(externalId) ? pathToFileURL(externalId).href : externalId
return {
Expand Down Expand Up @@ -90,7 +90,7 @@ ${res.code || '/* empty */'};
return { code, deps: res.deps || [], dynamicDeps: res.dynamicDeps || [] }
}

async function transformRequestRecursive (opts: TransformOptions, id, parent = '<entry>', chunks: Record<string, TransformChunk> = {}) {
async function transformRequestRecursive (opts: TransformOptions, id: string, parent = '<entry>', chunks: Record<string, TransformChunk> = {}) {
if (chunks[id]) {
chunks[id].parents.push(parent)
return
Expand All @@ -111,7 +111,7 @@ async function transformRequestRecursive (opts: TransformOptions, id, parent = '
}

export async function bundleRequest (opts: TransformOptions, entryURL: string) {
const chunks = await transformRequestRecursive(opts, entryURL)
const chunks = (await transformRequestRecursive(opts, entryURL))!

const listIds = (ids: string[]) => ids.map(id => `// - ${id} (${hashId(id)})`).join('\n')
const chunksCode = chunks.map(chunk => `
Expand Down Expand Up @@ -227,7 +227,7 @@ async function __instantiateModule__(url, urlStack) {
}

export async function initViteDevBundler (ctx: ViteBuildContext, onBuild: () => Promise<any>) {
const viteServer = ctx.ssrServer
const viteServer = ctx.ssrServer!
const options: TransformOptions = {
viteServer,
isExternal: createIsExternal(viteServer, ctx.nuxt.options.rootDir)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/manifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ export async function writeManifest (ctx: ViteBuildContext, css: string[] = [])
}
for (const item of ['css', 'assets']) {
if (clientManifest[key][item]) {
clientManifest[key][item] = clientManifest[key][item].map(i => i.replace(BASE_RE, ''))
clientManifest[key][item] = clientManifest[key][item].map((i: string) => i.replace(BASE_RE, ''))
}
}
}
Expand Down
1 change: 0 additions & 1 deletion packages/vite/src/plugins/analyze.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export function analyzePlugin (ctx: ViteBuildContext): Plugin[] {
}))
bundle.modules = Object.fromEntries(minifiedEntries)
}
return null
}
},
// @ts-ignore
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/plugins/cache-dir.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function cacheDirPlugin (rootDir: string, name: string) {
return <Plugin> {
name: 'nuxt:cache-dir',
configResolved (resolvedConfig) {
// @ts-ignore
// @ts-expect-error
resolvedConfig.optimizeCacheDir = optimizeCacheDir
}
}
Expand Down
17 changes: 10 additions & 7 deletions packages/vite/src/plugins/composable-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@ import type { CallExpression } from 'estree'
import { parseURL } from 'ufo'

export interface ComposableKeysOptions {
sourcemap?: boolean
rootDir?: string
sourcemap: boolean
rootDir: string
}

const keyedFunctions = [
'useState', 'useFetch', 'useAsyncData', 'useLazyAsyncData', 'useLazyFetch'
]
const KEYED_FUNCTIONS_RE = new RegExp(`(${keyedFunctions.join('|')})`)

export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptions = {}) => {
export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptions) => {
return {
name: 'nuxt:composable-keys',
enforce: 'post',
Expand All @@ -34,9 +34,10 @@ export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptio
sourceType: 'module',
ecmaVersion: 'latest'
}), {
enter (node: CallExpression) {
if (node.type !== 'CallExpression' || node.callee.type !== 'Identifier') { return }
if (keyedFunctions.includes(node.callee.name) && node.arguments.length < 4) {
enter (_node) {
if (_node.type !== 'CallExpression' || (_node as CallExpression).callee.type !== 'Identifier') { return }
const node: CallExpression = _node as CallExpression
if (keyedFunctions.includes((node.callee as any).name) && node.arguments.length < 4) {
const end = (node as any).end
s.appendLeft(
codeIndex + end - 1,
Expand All @@ -48,7 +49,9 @@ export const composableKeysPlugin = createUnplugin((options: ComposableKeysOptio
if (s.hasChanged()) {
return {
code: s.toString(),
map: options.sourcemap && s.generateMap({ source: id, includeContent: true })
map: options.sourcemap
? s.generateMap({ source: id, includeContent: true })
: undefined
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/plugins/virtual.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const PREFIX = 'virtual:nuxt:'

export default function virtual (vfs: Record<string, string>): Plugin {
const extensions = ['', '.ts', '.vue', '.mjs', '.cjs', '.js', '.json']
const resolveWithExt = (id) => {
const resolveWithExt = (id: string) => {
for (const ext of extensions) {
const rId = id + ext
if (rId in vfs) {
Expand Down
7 changes: 4 additions & 3 deletions packages/vite/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,10 @@ export async function buildServer (ctx: ViteBuildContext) {
format: 'module'
},
onwarn (warning, rollupWarn) {
if (!['UNUSED_EXTERNAL_IMPORT'].includes(warning.code)) {
rollupWarn(warning)
if (warning.code && ['UNUSED_EXTERNAL_IMPORT'].includes(warning.code)) {
return
}
rollupWarn(warning)
}
}
},
Expand All @@ -113,7 +114,7 @@ export async function buildServer (ctx: ViteBuildContext) {
// Add type-checking
if (ctx.nuxt.options.typescript.typeCheck === true || (ctx.nuxt.options.typescript.typeCheck === 'build' && !ctx.nuxt.options.dev)) {
const checker = await import('vite-plugin-checker').then(r => r.default)
serverConfig.plugins.push(checker({
serverConfig.plugins!.push(checker({
vueTsc: {
tsconfigPath: await resolveTSConfig(ctx.nuxt.options.rootDir)
}
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/utils/external.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ export function createIsExternal (viteServer: ViteDevServer, rootDir: string) {
inline: [
/virtual:/,
/\.ts$/,
...ExternalsDefaults.inline,
...ExternalsDefaults.inline || [],
...viteServer.config.ssr.noExternal as string[]
],
external: [
...viteServer.config.ssr.external,
...viteServer.config.ssr.external || [],
/node_modules/
],
resolve: {
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ export function hashId (id: string) {
return '$id_' + hash(id)
}

export function readDirRecursively (dir: string) {
export function readDirRecursively (dir: string): string[] {
return readdirSync(dir).reduce((files, file) => {
const name = join(dir, file)
const isDirectory = statSync(name).isDirectory()
return isDirectory ? [...files, ...readDirRecursively(name)] : [...files, name]
}, [])
}, [] as string[])
}

export async function isDirectory (path: string) {
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/utils/wpfs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ import fse from 'fs-extra'
export const wpfs = {
...fse,
join
} as any
} as typeof fse & { join: typeof join }
15 changes: 7 additions & 8 deletions packages/vite/src/vite-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ export function viteNodePlugin (ctx: ViteBuildContext): VitePlugin {
},
handleHotUpdate ({ file, server }) {
function markInvalidate (mod: ModuleNode) {
if (invalidates.has(mod.id)) {
return
}
if (!mod.id) { return }
if (invalidates.has(mod.id)) { return }
invalidates.add(mod.id)
for (const importer of mod.importers) {
markInvalidate(importer)
Expand All @@ -49,7 +48,7 @@ export function registerViteNodeMiddleware (ctx: ViteBuildContext) {
}

function getManifest (ctx: ViteBuildContext) {
const css = Array.from(ctx.ssrServer.moduleGraph.urlToModuleMap.keys())
const css = Array.from(ctx.ssrServer!.moduleGraph.urlToModuleMap.keys())
.filter(i => isCSS(i))

const manifest = normalizeViteManifest({
Expand Down Expand Up @@ -81,7 +80,7 @@ function createViteNodeMiddleware (ctx: ViteBuildContext, invalidates: Set<strin
app.use('/invalidates', defineEventHandler(() => {
// When a file has been invalidated, we also invalidate the entry module
if (invalidates.size) {
for (const key of ctx.ssrServer.moduleGraph.fileToModulesMap.keys()) {
for (const key of ctx.ssrServer!.moduleGraph.fileToModulesMap.keys()) {
if (key.startsWith(ctx.nuxt.options.appDir + '/entry')) {
invalidates.add(key)
}
Expand All @@ -93,7 +92,7 @@ function createViteNodeMiddleware (ctx: ViteBuildContext, invalidates: Set<strin
}))

app.use('/module', defineLazyEventHandler(() => {
const viteServer = ctx.ssrServer
const viteServer = ctx.ssrServer!
const node: ViteNodeServer = new ViteNodeServer(viteServer, {
deps: {
inline: [
Expand All @@ -117,7 +116,7 @@ function createViteNodeMiddleware (ctx: ViteBuildContext, invalidates: Set<strin
}

return async (event) => {
const moduleId = decodeURI(event.req.url).substring(1)
const moduleId = decodeURI(event.req.url!).substring(1)
if (moduleId === '/') {
throw createError({ statusCode: 400 })
}
Expand All @@ -144,7 +143,7 @@ export async function initViteNodeServer (ctx: ViteBuildContext) {
baseURL: `${protocol}://${host}:${port}/__nuxt_vite_node__`,
root: ctx.nuxt.options.srcDir,
entryPath,
base: ctx.ssrServer.config.base || '/_nuxt/'
base: ctx.ssrServer!.config.base || '/_nuxt/'
}
process.env.NUXT_VITE_NODE_OPTIONS = JSON.stringify(viteNodeServerOptions)

Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export interface ViteBuildContext {
export async function bundle (nuxt: Nuxt) {
const ctx: ViteBuildContext = {
nuxt,
entry: null,
entry: null!,
config: vite.mergeConfig(
{
resolve: {
Expand Down Expand Up @@ -85,8 +85,8 @@ export async function bundle (nuxt: Nuxt) {
// In build mode we explicitly override any vite options that vite is relying on
// to detect whether to inject production or development code (such as HMR code)
if (!nuxt.options.dev) {
ctx.config.server.watch = undefined
ctx.config.build.watch = undefined
ctx.config.server!.watch = undefined
ctx.config.build!.watch = undefined
}

await nuxt.callHook('vite:extend', ctx)
Expand Down
11 changes: 11 additions & 0 deletions packages/vite/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"strict": true,
"noImplicitAny": true
},
"include": [
"./src/**/*.ts",
"./test/**/*.ts"
]
}
Loading