refactor(vite): enable strict type checking (#6616)

This commit is contained in:
Anthony Fu 2022-08-15 21:40:06 +08:00 committed by GitHub
parent 385fa6037a
commit d2094ea37a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 75 additions and 55 deletions

View File

@ -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",

View File

@ -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
}
}
}

View File

@ -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
},
@ -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
}
}
}
@ -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]}`)
}
}
@ -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)

View File

@ -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",

View File

@ -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]')),
@ -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,
@ -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 })
@ -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)
})

View File

@ -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: []
}

View File

@ -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 {
@ -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
@ -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 => `
@ -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)

View File

@ -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, ''))
}
}
}

View File

@ -17,7 +17,6 @@ export function analyzePlugin (ctx: ViteBuildContext): Plugin[] {
}))
bundle.modules = Object.fromEntries(minifiedEntries)
}
return null
}
},
// @ts-ignore

View File

@ -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
}
}

View File

@ -8,8 +8,8 @@ import type { CallExpression } from 'estree'
import { parseURL } from 'ufo'
export interface ComposableKeysOptions {
sourcemap?: boolean
rootDir?: string
sourcemap: boolean
rootDir: string
}
const keyedFunctions = [
@ -17,7 +17,7 @@ const keyedFunctions = [
]
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',
@ -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,
@ -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
}
}
}

View File

@ -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) {

View File

@ -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)
}
}
},
@ -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)
}

View File

@ -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: {

View File

@ -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) {

View File

@ -4,4 +4,4 @@ import fse from 'fs-extra'
export const wpfs = {
...fse,
join
} as any
} as typeof fse & { join: typeof join }

View File

@ -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)
@ -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({
@ -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)
}
@ -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: [
@ -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 })
}
@ -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)

View File

@ -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: {
@ -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)

View File

@ -0,0 +1,11 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"strict": true,
"noImplicitAny": true
},
"include": [
"./src/**/*.ts",
"./test/**/*.ts"
]
}

View File

@ -45,7 +45,7 @@
"style-resources-loader": "^1.5.0",
"time-fix-plugin": "^2.0.7",
"ufo": "^0.8.5",
"unplugin": "^0.9.0",
"unplugin": "^0.9.2",
"url-loader": "^4.1.1",
"vue-bundle-renderer": "^0.4.2",
"vue-loader": "^17.0.0",

View File

@ -1806,7 +1806,7 @@ __metadata:
rollup-plugin-visualizer: ^5.7.1
ufo: ^0.8.5
unbuild: latest
unplugin: ^0.9.0
unplugin: ^0.9.2
vite: ~3.0.7
vite-node: ^0.21.1
vite-plugin-checker: ^0.4.9
@ -1857,7 +1857,7 @@ __metadata:
time-fix-plugin: ^2.0.7
ufo: ^0.8.5
unbuild: latest
unplugin: ^0.9.0
unplugin: ^0.9.2
url-loader: ^4.1.1
vue: 3.2.37
vue-bundle-renderer: ^0.4.2
@ -9959,7 +9959,7 @@ __metadata:
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
@ -13105,7 +13105,7 @@ __metadata:
languageName: node
linkType: hard
"unplugin@npm:^0.9.0":
"unplugin@npm:^0.9.0, unplugin@npm:^0.9.2":
version: 0.9.2
resolution: "unplugin@npm:0.9.2"
dependencies: