Skip to content

Commit

Permalink
feat: dep optimizer entry option
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Jan 27, 2021
1 parent 7ea140c commit 64ba807
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 18 deletions.
21 changes: 17 additions & 4 deletions packages/vite/src/node/optimizer/index.ts
Expand Up @@ -15,15 +15,28 @@ import { esbuildDepPlugin } from './esbuildDepPlugin'
import { init, parse } from 'es-module-lexer'
import { scanImports } from './scan'

const debug = createDebugger('vite:optimize')
const debug = createDebugger('vite:deps')

export interface DepOptimizationOptions {
/**
* Force optimize listed dependencies (supports deep paths).
* By default, Vite will crawl your index.html to detect dependencies that
* need to be pre-bundled. If build.rollupOptions.input is specified, Vite
* will crawl those entry points instead.
*
* If neither of these fit your needs, you can specify custom entries using
* this option - the value should be a fast-glob pattern or array of patterns
* (https://github.com/mrmlnc/fast-glob#basic-syntax) that are relative from
* vite project root. This will overwrite default entries inference.
*/
entries?: string | string[]
/**
* Force optimize listed dependencies (must be resolvalble import paths,
* cannot be globs).
*/
include?: string[]
/**
* Do not optimize these dependencies.
* Do not optimize these dependencies (must be resolvable import paths,
* cannot be globs).
*/
exclude?: string[]
}
Expand Down Expand Up @@ -101,7 +114,7 @@ export async function optimizeDeps(

if (!qualifiedIds.length) {
writeFile(dataPath, JSON.stringify(data, null, 2))
log(`No listed dependency requires optimization. Skipping.\n\n\n`)
log(`No dependencies to bundle. Skipping.\n\n\n`)
return
}

Expand Down
61 changes: 47 additions & 14 deletions packages/vite/src/node/optimizer/scan.ts
Expand Up @@ -9,7 +9,8 @@ import {
emptyDir,
isDataUrl,
isExternalUrl,
normalizePath
normalizePath,
isObject
} from '../utils'
import { browserExternalId } from '../plugins/resolve'
import chalk from 'chalk'
Expand All @@ -18,29 +19,49 @@ import {
PluginContainer
} from '../server/pluginContainer'

const debug = createDebugger('vite:scan')
const debug = createDebugger('vite:deps')

export async function scanImports(
config: ResolvedConfig
): Promise<Record<string, string>> {
const s = Date.now()
const htmlEntries = await glob('**/index.html', {
cwd: config.root,
ignore: [
'**/node_modules/**',
`**/${config.build.outDir}/**`,
`**/__tests__/**`
],
absolute: true
})

const tempDir = path.join(config.optimizeCacheDir!, 'scan')
let entries: string[] = []

const explicitEntryPatterns = config.optimizeDeps?.entries
const buildInput = config.build.rollupOptions?.input

if (explicitEntryPatterns) {
entries = await globEntries(explicitEntryPatterns, config)
} else if (buildInput) {
const resolvePath = (p: string) => path.resolve(config.root, p)
if (typeof buildInput === 'string') {
entries = [resolvePath(buildInput)]
} else if (Array.isArray(buildInput)) {
entries = buildInput.map(resolvePath)
} else if (isObject(buildInput)) {
entries = Object.values(buildInput).map(resolvePath)
} else {
throw new Error('invalid rollupOptions.input value.')
}
} else {
entries = await globEntries('**/*.html', config)
}

if (!entries.length) {
debug(`No entry HTML files detected`)
return {}
} else {
debug(`Crawling dependencies using entries:\n ${entries.join('\n ')}`)
}

const tempDir = path.join(config.optimizeCacheDir!, 'temp')
const depImports: Record<string, string> = {}
const missing = new Set<string>()
const plugin = esbuildScanPlugin(config, depImports, missing)

await Promise.all(
htmlEntries.map((entry) =>
entries.map((entry) =>
build({
entryPoints: [entry],
bundle: true,
Expand All @@ -56,7 +77,7 @@ export async function scanImports(
emptyDir(tempDir)
fs.rmdirSync(tempDir)

debug(`scan completed in ${Date.now() - s}ms:`, depImports)
debug(`Scan completed in ${Date.now() - s}ms:`, depImports)

if (missing.size) {
config.logger.error(
Expand All @@ -69,6 +90,18 @@ export async function scanImports(
return depImports
}

function globEntries(pattern: string | string[], config: ResolvedConfig) {
return glob(pattern, {
cwd: config.root,
ignore: [
'**/node_modules/**',
`**/${config.build.outDir}/**`,
`**/__tests__/**`
],
absolute: true
})
}

const scriptModuleRE = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims
const scriptRE = /(<script\b[^>]*>)(.*?)<\/script>/gims
const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im
Expand Down

0 comments on commit 64ba807

Please sign in to comment.