Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: cherry pick for v4 #14520

Merged
merged 20 commits into from
Oct 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
0f7ae2f
fix(glob): trigger HMR for glob in a package (#14117)
sapphi-red Aug 16, 2023
917ff3f
fix: ws never connects after restarting server if server.hmr.server i…
sapphi-red Aug 16, 2023
65df270
fix: initWasm options should be optional (#14152)
btea Aug 18, 2023
eda46c3
fix: if host is specified check whether it is valid (#14013)
btea Aug 22, 2023
76dd2f9
fix: use string manipulation instead of regex to inject esbuild helpe…
fnlctrl Aug 25, 2023
8c35aad
fix: handle sourcemap correctly when multiple line import exists (#14…
sapphi-red Aug 29, 2023
1837415
fix(vite): precisely check if files are in dirs (#14241)
danielroe Sep 3, 2023
e6c89d7
fix: add source map to Web Workers (fix #14216) (#14217)
yume-chan Sep 3, 2023
c1db72a
fix(cli): convert special base (#14283)
btea Sep 4, 2023
be9201e
fix(css): remove pure css chunk sourcemap (#14290)
sun0day Sep 5, 2023
d8529f9
fix: include `vite/types/*` in exports field (#14296)
yuheiy Sep 6, 2023
4680cba
fix(optimizer): define crawlDeps after scanProcessing and optimizatio…
anyesu Sep 6, 2023
50d2e4a
fix(css): reset render cache on renderStart (#14326)
bluwy Sep 8, 2023
e1c365c
fix(manifest): preserve pure css chunk assets (#14297)
sun0day Sep 10, 2023
4b1c92d
feat: improve deno and bun support (#14379)
bluwy Sep 18, 2023
cf60551
fix: handle errors during `hasWorkspacePackageJSON` function (#14394)
sapphi-red Sep 18, 2023
e6213c1
fix(import-analysis): preserve importedUrls import order (#14465)
bluwy Sep 26, 2023
ae7b4cd
fix(analysis): warnings for dynamic imports that use static template …
Dunqing Sep 28, 2023
56c5f4f
fix(resolve): support submodules of optional peer deps (#14489)
decs Oct 2, 2023
1be88ab
fix: restore builtins list
bluwy Oct 3, 2023
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/vite/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ declare module '*.txt' {
// wasm?init
declare module '*.wasm?init' {
const initWasm: (
options: WebAssembly.Imports,
options?: WebAssembly.Imports,
) => Promise<WebAssembly.Instance>
export default initWasm
}
Expand Down
3 changes: 3 additions & 0 deletions packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
"types": "./client.d.ts"
},
"./dist/client/*": "./dist/client/*",
"./types/*": {
"types": "./types/*"
},
"./package.json": "./package.json"
},
"files": [
Expand Down
9 changes: 7 additions & 2 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
joinUrlSegments,
normalizePath,
requireResolveFromRootWithFallback,
withTrailingSlash,
} from './utils'
import { manifestPlugin } from './plugins/manifest'
import type { Logger } from './logger'
Expand Down Expand Up @@ -714,7 +715,7 @@ function prepareOutDir(
for (const outDir of nonDuplicateDirs) {
if (
fs.existsSync(outDir) &&
!normalizePath(outDir).startsWith(config.root + '/')
!normalizePath(outDir).startsWith(withTrailingSlash(config.root))
) {
// warn if outDir is outside of root
config.logger.warn(
Expand Down Expand Up @@ -1240,5 +1241,9 @@ export const toOutputFilePathInHtml = toOutputFilePathWithoutRuntime
function areSeparateFolders(a: string, b: string) {
const na = normalizePath(a)
const nb = normalizePath(b)
return na !== nb && !na.startsWith(nb + '/') && !nb.startsWith(na + '/')
return (
na !== nb &&
!na.startsWith(withTrailingSlash(nb)) &&
!nb.startsWith(withTrailingSlash(na))
)
}
28 changes: 25 additions & 3 deletions packages/vite/src/node/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,31 @@ function cleanOptions<Options extends GlobalCLIOptions>(
return ret
}

/**
* host may be a number (like 0), should convert to string
*/
const convertHost = (v: any) => {
if (typeof v === 'number') {
return String(v)
}
return v
}

/**
* base may be a number (like 0), should convert to empty string
*/
const convertBase = (v: any) => {
if (v === 0) {
return ''
}
return v
}

cli
.option('-c, --config <file>', `[string] use specified config file`)
.option('--base <path>', `[string] public base path (default: /)`)
.option('--base <path>', `[string] public base path (default: /)`, {
type: [convertBase],
})
.option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
.option('-d, --debug [feat]', `[string | boolean] show debug logs`)
Expand All @@ -116,7 +138,7 @@ cli
.command('[root]', 'start dev server') // default command
.alias('serve') // the command is called 'serve' in Vite's API
.alias('dev') // alias to align with the script name
.option('--host [host]', `[string] specify hostname`)
.option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
.option('--port <port>', `[number] specify port`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [path]', `[boolean | string] open browser on startup`)
Expand Down Expand Up @@ -306,7 +328,7 @@ cli
// preview
cli
.command('preview [root]', 'locally preview production build')
.option('--host [host]', `[string] specify hostname`)
.option('--host [host]', `[string] specify hostname`, { type: [convertHost] })
.option('--port <port>', `[number] specify port`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--https', `[boolean] use TLS + HTTP/2`)
Expand Down
14 changes: 9 additions & 5 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ import {
dynamicImport,
isBuiltin,
isExternalUrl,
isNodeBuiltin,
isObject,
lookupFile,
mergeAlias,
mergeConfig,
normalizeAlias,
normalizePath,
withTrailingSlash,
} from './utils'
import {
createPluginHookUtils,
Expand Down Expand Up @@ -680,7 +682,7 @@ export async function resolveConfig(
),
inlineConfig,
root: resolvedRoot,
base: resolvedBase.endsWith('/') ? resolvedBase : resolvedBase + '/',
base: withTrailingSlash(resolvedBase),
rawBase: resolvedBase,
resolve: resolveOptions,
publicDir: resolvedPublicDir,
Expand Down Expand Up @@ -856,7 +858,7 @@ assetFileNames isn't equal for every build.rollupOptions.output. A single patter
) {
resolved.logger.warn(
colors.yellow(`
(!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
(!) Experimental legacy.buildSsrCjsExternalHeuristics and ssr.format: 'cjs' are going to be removed in Vite 5.
Find more information and give feedback at https:/vitejs/vite/discussions/13816.
`),
)
Expand Down Expand Up @@ -1081,13 +1083,15 @@ async function bundleConfigFile(
if (
kind === 'entry-point' ||
path.isAbsolute(id) ||
isBuiltin(id)
isNodeBuiltin(id)
) {
return
}

// partial deno support as `npm:` does not work with esbuild
if (id.startsWith('npm:')) {
// With the `isNodeBuiltin` check above, this check captures if the builtin is a
// non-node built-in, which esbuild doesn't know how to handle. In that case, we
// externalize it so the non-node runtime handles it instead.
if (isBuiltin(id)) {
return { external: true }
}

Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/optimizer/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -619,8 +619,6 @@ async function createDepsOptimizer(
return
}

const crawlDeps = Object.keys(metadata.discovered)

// Await for the scan+optimize step running in the background
// It normally should be over by the time crawling of user code ended
await depsOptimizer.scanProcessing
Expand All @@ -630,6 +628,7 @@ async function createDepsOptimizer(
optimizationResult = undefined
currentlyProcessing = false

const crawlDeps = Object.keys(metadata.discovered)
const scanDeps = Object.keys(result.metadata.optimized)

if (scanDeps.length === 0 && crawlDeps.length === 0) {
Expand Down Expand Up @@ -680,6 +679,7 @@ async function createDepsOptimizer(
runOptimizer(result)
}
} else {
const crawlDeps = Object.keys(metadata.discovered)
currentlyProcessing = false

if (crawlDeps.length === 0) {
Expand Down
9 changes: 7 additions & 2 deletions packages/vite/src/node/plugins/asset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
joinUrlSegments,
normalizePath,
removeLeadingSlash,
withTrailingSlash,
} from '../utils'
import { FS_PREFIX } from '../constants'

Expand Down Expand Up @@ -229,7 +230,11 @@ export function checkPublicFile(
return
}
const publicFile = path.join(publicDir, cleanUrl(url))
if (!publicFile.startsWith(publicDir)) {
if (
!normalizePath(publicFile).startsWith(
withTrailingSlash(normalizePath(publicDir)),
)
) {
// can happen if URL starts with '../'
return
}
Expand Down Expand Up @@ -257,7 +262,7 @@ function fileToDevUrl(id: string, config: ResolvedConfig) {
if (checkPublicFile(id, config)) {
// in public dir, keep the url as-is
rtn = id
} else if (id.startsWith(config.root)) {
} else if (id.startsWith(withTrailingSlash(config.root))) {
// in project root, infer short public path
rtn = '/' + path.posix.relative(config.root, id)
} else {
Expand Down
11 changes: 8 additions & 3 deletions packages/vite/src/node/plugins/css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
return {
name: 'vite:css-post',

buildStart() {
renderStart() {
// Ensure new caches for every build (i.e. rebuilding in watch mode)
pureCssChunks = new Set<RenderedChunk>()
outputToExtractedCSSMap = new Map<NormalizedOutputOptions, string>()
Expand Down Expand Up @@ -769,11 +769,15 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
// chunks instead.
chunk.imports = chunk.imports.filter((file) => {
if (pureCssChunkNames.includes(file)) {
const { importedCss } = (bundle[file] as OutputChunk)
.viteMetadata!
const { importedCss, importedAssets } = (
bundle[file] as OutputChunk
).viteMetadata!
importedCss.forEach((file) =>
chunk.viteMetadata!.importedCss.add(file),
)
importedAssets.forEach((file) =>
chunk.viteMetadata!.importedAssets.add(file),
)
return false
}
return true
Expand All @@ -789,6 +793,7 @@ export function cssPostPlugin(config: ResolvedConfig): Plugin {
pureCssChunkNames.forEach((fileName) => {
removedPureCssFiles.set(fileName, bundle[fileName] as RenderedChunk)
delete bundle[fileName]
delete bundle[`${fileName}.map`]
})
}

Expand Down
39 changes: 23 additions & 16 deletions packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,9 @@ import { searchForWorkspaceRoot } from '../server/searchRoot'

const debug = createDebugger('vite:esbuild')

const INJECT_HELPERS_IIFE_RE =
/^(.*?)((?:const|var)\s+\S+\s*=\s*function\s*\([^)]*\)\s*\{\s*"use strict";)/s
const INJECT_HELPERS_UMD_RE =
/^(.*?)(\(function\([^)]*\)\s*\{.+?amd.+?function\([^)]*\)\s*\{\s*"use strict";)/s
// IIFE content looks like `var MyLib = function() {`. Spaces are removed when minified
const IIFE_BEGIN_RE =
/(const|var)\s+\S+\s*=\s*function\(\)\s*\{.*"use strict";/s

const validExtensionRE = /\.\w+$/
const jsxExtensionsRE = /\.(?:j|t)sx\b/
Expand Down Expand Up @@ -333,22 +332,30 @@ export const buildEsbuildPlugin = (config: ResolvedConfig): Plugin => {
if (config.build.lib) {
// #7188, esbuild adds helpers out of the UMD and IIFE wrappers, and the
// names are minified potentially causing collision with other globals.
// We use a regex to inject the helpers inside the wrappers.
// We inject the helpers inside the wrappers.
// e.g. turn:
// <esbuild helpers> (function(){ /*actual content/* })()
// into:
// (function(){ <esbuild helpers> /*actual content/* })()
// Not using regex because it's too hard to rule out performance issues like #8738 #8099 #10900 #14065
// Instead, using plain string index manipulation (indexOf, slice) which is simple and performant
// We don't need to create a MagicString here because both the helpers and
// the headers don't modify the sourcemap
const injectHelpers =
opts.format === 'umd'
? INJECT_HELPERS_UMD_RE
: opts.format === 'iife'
? INJECT_HELPERS_IIFE_RE
: undefined
if (injectHelpers) {
res.code = res.code.replace(
injectHelpers,
(_, helpers, header) => header + helpers,
)
const esbuildCode = res.code
const contentIndex =
opts.format === 'iife'
? esbuildCode.match(IIFE_BEGIN_RE)?.index || 0
: opts.format === 'umd'
? esbuildCode.indexOf(`(function(`) // same for minified or not
: 0
if (contentIndex > 0) {
const esbuildHelpers = esbuildCode.slice(0, contentIndex)
res.code = esbuildCode
.slice(contentIndex)
.replace(`"use strict";`, `"use strict";` + esbuildHelpers)
}
}

return res
},
}
Expand Down
Loading