chore: prune internal unused code and exports (#21809)

This commit is contained in:
Daniel Roe 2023-06-27 10:38:40 +01:00 committed by GitHub
parent 54a0d5e8dc
commit 9c8746f2a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
32 changed files with 79 additions and 140 deletions

37
knip.json Normal file
View File

@ -0,0 +1,37 @@
{
"$schema": "https://unpkg.com/knip@2/schema.json",
"workspaces": {
".": {
"entry": [
"scripts/*"
]
},
"packages/*": {
"entry": [
"src/index.ts",
"src/runtime/**/*.ts"
]
},
"packages/test-utils": {
"entry": [
"src/experimental.ts",
"src/index.ts"
]
},
"packages/nuxi": {
"entry": [
"src/index.ts",
"src/commands/*.ts"
]
},
"packages/nuxt": {
"entry": [
"src/app/**/*.ts",
"src/app/*.ts",
"src/*/runtime/**/*.ts",
"src/core/templates.ts",
"src/index.ts"
]
}
}
}

View File

@ -13,6 +13,7 @@
"lint:fix": "eslint --ext .vue,.ts,.js,.mjs . --fix",
"lint:docs": "markdownlint ./docs && case-police 'docs/**/*.md'",
"lint:docs:fix": "markdownlint ./docs --fix && case-police 'docs/**/*.md' --fix",
"lint:knip": "pnpx knip",
"play": "nuxi dev playground",
"play:build": "nuxi build playground",
"play:preview": "nuxi preview playground",
@ -51,7 +52,6 @@
"consola": "3.1.0",
"devalue": "4.3.2",
"eslint": "8.43.0",
"eslint-import-resolver-typescript": "3.5.5",
"eslint-plugin-import": "2.27.5",
"eslint-plugin-jsdoc": "41.1.2",
"eslint-plugin-no-only-tests": "3.1.0",

View File

@ -23,13 +23,13 @@ export interface RequireModuleOptions extends ResolveModuleOptions {
}
/** @deprecated Do not use CJS utils */
export function isNodeModules (id: string) {
function isNodeModules (id: string) {
// TODO: Follow symlinks
return /[/\\]node_modules[/\\]/.test(id)
}
/** @deprecated Do not use CJS utils */
export function clearRequireCache (id: string) {
function clearRequireCache (id: string) {
if (isNodeModules(id)) {
return
}
@ -53,29 +53,7 @@ export function clearRequireCache (id: string) {
}
/** @deprecated Do not use CJS utils */
export function scanRequireTree (id: string, files = new Set<string>()) {
if (isNodeModules(id) || files.has(id)) {
return files
}
const entry = getRequireCacheItem(id)
if (!entry) {
files.add(id)
return files
}
files.add(entry.id)
for (const child of entry.children) {
scanRequireTree(child.id, files)
}
return files
}
/** @deprecated Do not use CJS utils */
export function getRequireCacheItem (id: string) {
function getRequireCacheItem (id: string) {
try {
return _require.cache[id]
} catch (e) {

View File

@ -14,11 +14,11 @@ export function getModulePaths (paths?: string | string[]): string[] {
const _require = createRequire(process.cwd())
export function resolveModule (id: string, paths?: string | string[]) {
function resolveModule (id: string, paths?: string | string[]) {
return normalize(_require.resolve(id, { paths: getModulePaths(paths) }))
}
export function requireModule (id: string, paths?: string | string[]) {
function requireModule (id: string, paths?: string | string[]) {
return _require(resolveModule(id, paths))
}

View File

@ -11,9 +11,3 @@ export async function importModule (id: string, url = import.meta.url) {
const resolvedPath = await resolvePath(id, { url })
return import(pathToFileURL(resolvedPath).href).then(interopDefault)
}
export function tryImportModule (id: string, url = import.meta.url) {
try {
return importModule(id, url).catch(() => undefined)
} catch { }
}

View File

@ -2,16 +2,6 @@ import { existsSync, promises as fsp } from 'node:fs'
import { dirname, join } from 'pathe'
import { consola } from 'consola'
// Check if a file exists
export async function exists (path: string) {
try {
await fsp.access(path)
return true
} catch {
return false
}
}
export async function clearDir (path: string, exclude?: string[]) {
if (!exclude) {
await fsp.rm(path, { recursive: true, force: true })

View File

@ -5,7 +5,7 @@ import { hash } from 'ohash'
import type { Nuxt } from '@nuxt/schema'
import { rmRecursive } from './fs'
export interface NuxtProjectManifest {
interface NuxtProjectManifest {
_hash: string | null
project: {
rootDir: string
@ -37,7 +37,7 @@ export function nuxtVersionToGitIdentifier (version: string) {
return `v${version}`
}
export function resolveNuxtManifest (nuxt: Nuxt): NuxtProjectManifest {
function resolveNuxtManifest (nuxt: Nuxt): NuxtProjectManifest {
const manifest: NuxtProjectManifest = {
_hash: null,
project: {

View File

@ -47,10 +47,9 @@ export default defineComponent({
onMounted(() => { mounted.value = true })
const ssrHTML = ref<string>(process.client ? getFragmentHTML(instance.vnode?.el ?? null).join('') ?? '<div></div>' : '<div></div>')
const slotProps = computed(() => getSlotProps(ssrHTML.value))
const uid = ref<string>(ssrHTML.value.match(SSR_UID_RE)?.[1] ?? randomUUID())
const availableSlots = computed(() => {
return [...ssrHTML.value.matchAll(SLOTNAME_RE)].map(m => m[1])
})
const availableSlots = computed(() => [...ssrHTML.value.matchAll(SLOTNAME_RE)].map(m => m[1]))
const html = computed(() => {
const currentSlots = Object.keys(slots)
@ -67,9 +66,6 @@ export default defineComponent({
}
const cHead = ref<Record<'link' | 'style', Array<Record<string, string>>>>({ link: [], style: [] })
useHead(cHead)
const slotProps = computed(() => {
return getSlotProps(ssrHTML.value)
})
async function _fetchComponent () {
const key = `${props.name}_${hashId.value}`

View File

@ -2,7 +2,7 @@ import { isAbsolute, relative } from 'pathe'
import { genDynamicImport } from 'knitwork'
import type { Component, Nuxt, NuxtApp, NuxtPluginTemplate, NuxtTemplate } from 'nuxt/schema'
export interface ComponentsTemplateContext {
interface ComponentsTemplateContext {
app: NuxtApp
nuxt: Nuxt
options: {
@ -11,7 +11,7 @@ export interface ComponentsTemplateContext {
}
}
export type ImportMagicCommentsOptions = {
type ImportMagicCommentsOptions = {
chunkName: string
prefetch?: boolean | number
preload?: boolean | number

View File

@ -58,7 +58,7 @@ export async function generateApp (nuxt: Nuxt, app: NuxtApp, options: { filter?:
await nuxt.callHook('app:templatesGenerated', app)
}
export async function resolveApp (nuxt: Nuxt, app: NuxtApp) {
async function resolveApp (nuxt: Nuxt, app: NuxtApp) {
// Resolve main (app.vue)
if (!app.mainComponent) {
app.mainComponent = await findPath(

View File

@ -1,6 +1,6 @@
import { normalizeModuleTranspilePath, useNuxt } from '@nuxt/kit'
export interface AddModuleTranspilesOptions {
interface AddModuleTranspilesOptions {
additionalModules?: string[]
}

View File

@ -10,7 +10,7 @@ import { filename } from 'pathe/utils'
import type { Nuxt, NuxtApp, NuxtTemplate } from 'nuxt/schema'
import { annotatePlugins } from './app'
export interface TemplateContext {
interface TemplateContext {
nuxt: Nuxt
app: NuxtApp
}

View File

@ -1,5 +1,5 @@
import { basename, extname } from 'pathe'
import { kebabCase, pascalCase } from 'scule'
import { kebabCase } from 'scule'
export function getNameFromPath (path: string) {
return kebabCase(basename(path).replace(extname(path), '')).replace(/["']/g, '')
@ -8,7 +8,3 @@ export function getNameFromPath (path: string) {
export function hasSuffix (path: string, suffix: string) {
return basename(path).replace(extname(path), '').endsWith(suffix)
}
export function getImportName (name: string) {
return pascalCase(name).replace(/[^\w]/g, r => '_' + r.charCodeAt(0))
}

View File

@ -5,4 +5,3 @@ let _distDir = dirname(fileURLToPath(import.meta.url))
if (_distDir.match(/(chunks|shared)$/)) { _distDir = dirname(_distDir) }
export const distDir = _distDir
export const pkgDir = resolve(distDir, '..')
export const runtimeDir = resolve(distDir, 'runtime')

View File

@ -33,6 +33,7 @@
"@unhead/schema": "1.1.28",
"@vitejs/plugin-vue": "4.2.3",
"@vitejs/plugin-vue-jsx": "3.0.1",
"@vue/compiler-core": "^3.3.4",
"esbuild-loader": "3.0.1",
"h3": "1.7.0",
"ignore": "5.2.4",
@ -44,7 +45,8 @@
"vue-bundle-renderer": "1.0.3",
"vue-loader": "17.2.2",
"vue-router": "4.2.2",
"webpack": "5.88.0"
"webpack": "5.88.0",
"webpack-dev-middleware": "^6.1.1"
},
"dependencies": {
"defu": "^6.1.2",

View File

@ -1,5 +1,4 @@
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'pathe'
import { dirname } from 'pathe'
export const distDir = dirname(fileURLToPath(import.meta.url))
export const pkgDir = resolve(distDir, '..')

View File

@ -13,21 +13,21 @@ import { createIsExternal } from './utils/external'
import { writeManifest } from './manifest'
import type { ViteBuildContext } from './vite'
export interface TransformChunk {
interface TransformChunk {
id: string,
code: string,
deps: string[],
parents: string[]
}
export interface SSRTransformResult {
interface SSRTransformResult {
code: string,
map: object,
deps: string[]
dynamicDeps: string[]
}
export interface TransformOptions {
interface TransformOptions {
viteServer: vite.ViteDevServer
isExternal(id: string): ReturnType<typeof isExternal>
}
@ -109,7 +109,7 @@ async function transformRequestRecursive (opts: TransformOptions, id: string, pa
return Object.values(chunks)
}
export async function bundleRequest (opts: TransformOptions, entryURL: string) {
async function bundleRequest (opts: TransformOptions, entryURL: string) {
const chunks = (await transformRequestRecursive(opts, entryURL))!
const listIds = (ids: string[]) => ids.map(id => `// - ${id} (${hashId(id)})`).join('\n')

View File

@ -1,7 +1,6 @@
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'pathe'
import { dirname } from 'pathe'
let _distDir = dirname(fileURLToPath(import.meta.url))
if (_distDir.match(/(chunks|shared)$/)) { _distDir = dirname(_distDir) }
export const distDir = _distDir
export const pkgDir = resolve(distDir, '..')

View File

@ -11,7 +11,7 @@ import escapeRE from 'escape-string-regexp'
import { findStaticImports, parseStaticImport } from 'mlly'
import { matchWithStringOrRegex } from '../utils'
export interface ComposableKeysOptions {
interface ComposableKeysOptions {
sourcemap: boolean
rootDir: string
composables: Array<{ name: string, source?: string | RegExp, argumentLength: number }>

View File

@ -2,7 +2,7 @@ import { joinURL } from 'ufo'
import type { Plugin } from 'vite'
import { isCSS } from '../utils'
export interface DevStyleSSRPluginOptions {
interface DevStyleSSRPluginOptions {
srcDir: string
buildAssetsURL: string
}

View File

@ -4,7 +4,7 @@ import { parseQuery, parseURL } from 'ufo'
import type { Plugin } from 'vite'
import { isCSS } from '../utils'
export interface RuntimePathsOptions {
interface RuntimePathsOptions {
sourcemap?: boolean
}

View File

@ -3,7 +3,7 @@ import { createUnplugin } from 'unplugin'
import { stripLiteral } from 'strip-literal'
import { isJS, isVue } from '../../../nuxt/src/core/utils/plugins'
export interface PureAnnotationsOptions {
interface PureAnnotationsOptions {
sourcemap: boolean
functions: string[]
}

View File

@ -1,25 +1,12 @@
import { promises as fsp, readdirSync, statSync } from 'node:fs'
import { hash } from 'ohash'
import { join } from 'pathe'
export function uniq<T> (arr: T[]): T[] {
return Array.from(new Set(arr))
}
// Copied from vue-bundle-renderer utils
const IS_JS_RE = /\.[cm]?js(\?[^.]+)?$/
const IS_MODULE_RE = /\.mjs(\?[^.]+)?$/
const HAS_EXT_RE = /[^./]+\.[^./]+$/
const IS_CSS_RE = /\.(?:css|scss|sass|postcss|less|stylus|styl)(\?[^.]+)?$/
export function isJS (file: string) {
return IS_JS_RE.test(file) || !HAS_EXT_RE.test(file)
}
export function isModule (file: string) {
return IS_MODULE_RE.test(file) || !HAS_EXT_RE.test(file)
}
export function isCSS (file: string) {
return IS_CSS_RE.test(file)
}
@ -28,22 +15,6 @@ export function hashId (id: string) {
return '$id_' + hash(id)
}
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) {
try {
return (await fsp.stat(path)).isDirectory()
} catch (_err) {
return false
}
}
export function matchWithStringOrRegex (value: string, matcher: string | RegExp) {
if (typeof matcher === 'string') {
return value === matcher

View File

@ -14,7 +14,7 @@ export const logLevelMap: Record<NuxtOptions['logLevel'], vite.UserConfig['logLe
verbose: 'info'
}
export const logLevelMapReverse: Record<NonNullable<vite.UserConfig['logLevel']>, number> = {
const logLevelMapReverse: Record<NonNullable<vite.UserConfig['logLevel']>, number> = {
silent: 0,
error: 1,
warn: 2,

View File

@ -2,7 +2,7 @@ import type { Compilation, Compiler } from 'webpack'
import webpack from 'webpack'
import { extractQueryPartJS, isJS, validate } from './util'
export interface VueSSRServerPluginOptions {
interface VueSSRServerPluginOptions {
filename: string
}

View File

@ -155,7 +155,7 @@ function baseResolve (ctx: WebpackConfigContext) {
}
}
export function baseTranspile (ctx: WebpackConfigContext) {
function baseTranspile (ctx: WebpackConfigContext) {
const { options } = ctx
const transpile = [

View File

@ -5,7 +5,7 @@ import type { Nuxt } from '@nuxt/schema'
const isPureObject = (obj: unknown): obj is Object => obj !== null && !Array.isArray(obj) && typeof obj === 'object'
export const orderPresets = {
const orderPresets = {
cssnanoLast (names: string[]) {
const nanoIndex = names.indexOf('cssnano')
if (nanoIndex !== names.length - 1) {

View File

@ -59,9 +59,6 @@ importers:
eslint:
specifier: 8.43.0
version: 8.43.0
eslint-import-resolver-typescript:
specifier: 3.5.5
version: 3.5.5(@typescript-eslint/parser@5.59.9)(eslint-plugin-import@2.27.5)(eslint@8.43.0)
eslint-plugin-import:
specifier: 2.27.5
version: 2.27.5(@typescript-eslint/parser@5.59.9)(eslint-import-resolver-typescript@3.5.5)(eslint@8.43.0)
@ -555,6 +552,9 @@ importers:
'@vitejs/plugin-vue-jsx':
specifier: 3.0.1
version: 3.0.1(vite@4.3.9)(vue@3.3.4)
'@vue/compiler-core':
specifier: ^3.3.4
version: 3.3.4
esbuild-loader:
specifier: 3.0.1
version: 3.0.1(webpack@5.88.0)
@ -591,6 +591,9 @@ importers:
webpack:
specifier: 5.88.0
version: 5.88.0
webpack-dev-middleware:
specifier: ^6.1.1
version: 6.1.1(webpack@5.88.0)
packages/test-utils:
dependencies:
@ -928,21 +931,12 @@ importers:
specifier: workspace:*
version: link:../../../packages/nuxt
devDependencies:
ofetch:
specifier: latest
version: 1.1.1
ufo:
specifier: latest
version: 1.1.2
unplugin:
specifier: latest
version: 1.3.1
vitest:
specifier: latest
version: 0.32.2(playwright@1.35.1)
vue-router:
specifier: latest
version: 4.2.2(vue@3.3.4)
test/fixtures/basic-types:
dependencies:
@ -953,9 +947,6 @@ importers:
ofetch:
specifier: latest
version: 1.1.1
unplugin:
specifier: latest
version: 1.3.1
vitest:
specifier: latest
version: 0.32.2(playwright@1.35.1)
@ -3082,7 +3073,6 @@ packages:
optional: true
dependencies:
ajv: 8.12.0
dev: false
/ajv-keywords@3.5.2(ajv@6.12.6):
resolution: {integrity: sha512-5p6WTN0DdTGVQk6VjcEju19IgaHudalcfabD7yhDGeA6bcQnmL+CpveLJq/3hvfwd1aof6L386Ougkx6RfyMIQ==}
@ -3098,7 +3088,6 @@ packages:
dependencies:
ajv: 8.12.0
fast-deep-equal: 3.1.3
dev: false
/ajv@6.12.6:
resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==}
@ -3115,7 +3104,6 @@ packages:
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
uri-js: 4.4.1
dev: false
/ansi-colors@4.1.3:
resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==}
@ -5103,7 +5091,6 @@ packages:
/fs-monkey@1.0.4:
resolution: {integrity: sha512-INM/fWAxMICjttnD0DX1rBvinKskj5G1w+oy/pnm9u/tSlnBrzFonJMcalKJ30P8RRsPzKcCG7Q8l0jx5Fh9YQ==}
dev: false
/fs.realpath@1.0.0:
resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}
@ -6008,7 +5995,6 @@ packages:
/json-schema-traverse@1.0.0:
resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}
dev: false
/json-stable-stringify-without-jsonify@1.0.1:
resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==}
@ -6288,7 +6274,6 @@ packages:
engines: {node: '>= 4.0.0'}
dependencies:
fs-monkey: 1.0.4
dev: false
/memory-fs@0.5.0:
resolution: {integrity: sha512-jA0rdU5KoQMC0e6ppoNRtpp6vjFq6+NY7r8hywnC7V+1Xj/MtHwGIbB1QaK/dunyjWteJzmkpd7ooeWg10T7GA==}
@ -7651,7 +7636,6 @@ packages:
/require-from-string@2.0.2:
resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}
engines: {node: '>=0.10.0'}
dev: false
/requires-port@1.0.0:
resolution: {integrity: sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==}
@ -7814,7 +7798,6 @@ packages:
ajv: 8.12.0
ajv-formats: 2.1.1(ajv@8.12.0)
ajv-keywords: 5.1.0(ajv@8.12.0)
dev: false
/scule@1.0.0:
resolution: {integrity: sha512-4AsO/FrViE/iDNEPaAQlb77tf0csuq27EsVpy6ett584EcRTp6pTDLoGWVxCD77y5iU5FauOvhsI4o1APwPoSQ==}
@ -9011,7 +8994,6 @@ packages:
range-parser: 1.2.1
schema-utils: 4.0.1
webpack: 5.88.0
dev: false
/webpack-hot-middleware@2.25.4:
resolution: {integrity: sha512-IRmTspuHM06aZh98OhBJtqLpeWFM8FXJS5UYpKYxCJzyFoyWj1w6VGFfomZU7OPA55dMLrQK0pRT1eQ3PACr4w==}

View File

@ -10,7 +10,6 @@
},
"devDependencies": {
"ofetch": "latest",
"unplugin": "latest",
"vitest": "latest",
"vue-router": "latest"
}

View File

@ -9,10 +9,7 @@
"nuxt": "workspace:*"
},
"devDependencies": {
"ofetch": "latest",
"ufo": "latest",
"unplugin": "latest",
"vitest": "latest",
"vue-router": "latest"
"unplugin": "latest"
}
}

View File

@ -12,7 +12,7 @@ export default defineConfig({
}
},
test: {
globalSetup: 'test/setup.ts',
globalSetup: './test/setup.ts',
testTimeout: isWindows ? 60000 : 10000,
// Excluded plugin because it should throw an error when accidentally loaded via Nuxt
exclude: [...configDefaults.exclude, '**/test.ts', '**/this-should-not-load.spec.js'],