Skip to content

Commit

Permalink
chore: merge main
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Mar 26, 2023
2 parents 5d9c2eb + edbd262 commit 115b1a3
Show file tree
Hide file tree
Showing 27 changed files with 384 additions and 437 deletions.
4 changes: 0 additions & 4 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,10 +94,6 @@ export default defineConfig({
pt: { label: 'Português', link: 'https://pt.vitejs.dev' },
},

vue: {
reactivityTransform: true,
},

themeConfig: {
logo: '/logo.svg',

Expand Down
40 changes: 40 additions & 0 deletions docs/guide/api-javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,46 @@ import { preview } from 'vite'
})()
```

## `PreviewServer`

```ts
interface PreviewServer extends PreviewServerForHook {
resolvedUrls: ResolvedServerUrls
}
```

## `PreviewServerForHook`

```ts
interface PreviewServerForHook {
/**
* The resolved vite config object
*/
config: ResolvedConfig
/**
* A connect app instance.
* - Can be used to attach custom middlewares to the preview server.
* - Can also be used as the handler function of a custom http server
* or as a middleware in any connect-style Node.js frameworks
*
* https://github.com/senchalabs/connect#use-middleware
*/
middlewares: Connect.Server
/**
* native Node http server instance
*/
httpServer: http.Server
/**
* The resolved urls Vite prints on the CLI
*/
resolvedUrls: ResolvedServerUrls | null
/**
* Print server urls
*/
printUrls(): void
}
```

## `resolveConfig`

**Type Signature:**
Expand Down
5 changes: 3 additions & 2 deletions docs/guide/api-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,10 +309,11 @@ Vite plugins can also provide hooks that serve Vite-specific purposes. These hoo

### `configurePreviewServer`

- **Type:** `(server: { middlewares: Connect.Server, httpServer: http.Server }) => (() => void) | void | Promise<(() => void) | void>`
- **Type:** `(server: PreviewServerForHook) => (() => void) | void | Promise<(() => void) | void>`
- **Kind:** `async`, `sequential`
- **See also:** [PreviewServerForHook](./api-javascript#previewserverforhook)

Same as [`configureServer`](/guide/api-plugin.html#configureserver) but for the preview server. It provides the [connect](https://github.com/senchalabs/connect) server and its underlying [http server](https://nodejs.org/api/http.html). Similarly to `configureServer`, the `configurePreviewServer` hook is called before other middlewares are installed. If you want to inject a middleware **after** other middlewares, you can return a function from `configurePreviewServer`, which will be called after internal middlewares are installed:
Same as [`configureServer`](/guide/api-plugin.html#configureserver) but for the preview server. Similarly to `configureServer`, the `configurePreviewServer` hook is called before other middlewares are installed. If you want to inject a middleware **after** other middlewares, you can return a function from `configurePreviewServer`, which will be called after internal middlewares are installed:

```js
const myPlugin = () => ({
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,8 @@
},
"patchedDependencies": {
"[email protected]": "patches/[email protected]",
"[email protected]": "patches/[email protected]"
"[email protected]": "patches/[email protected]",
"[email protected]": "patches/[email protected]"
}
},
"stackblitz": {
Expand Down
37 changes: 0 additions & 37 deletions packages/vite/src/node/__tests__/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import {
asyncFlatten,
getHash,
getLocalhostAddressIfDiffersFromDNS,
getPotentialTsSrcPaths,
injectQuery,
isFileReadable,
isWindows,
Expand Down Expand Up @@ -137,42 +136,6 @@ describe('resolveHostname', () => {
})
})

test('ts import of file with .js extension', () => {
expect(getPotentialTsSrcPaths('test-file.js')).toEqual([
'test-file.ts',
'test-file.tsx',
])
})

test('ts import of file with .jsx extension', () => {
expect(getPotentialTsSrcPaths('test-file.jsx')).toEqual(['test-file.tsx'])
})

test('ts import of file .mjs,.cjs extension', () => {
expect(getPotentialTsSrcPaths('test-file.cjs')).toEqual([
'test-file.cts',
'test-file.ctsx',
])
expect(getPotentialTsSrcPaths('test-file.mjs')).toEqual([
'test-file.mts',
'test-file.mtsx',
])
})

test('ts import of file with .js before extension', () => {
expect(getPotentialTsSrcPaths('test-file.js.js')).toEqual([
'test-file.js.ts',
'test-file.js.tsx',
])
})

test('ts import of file with .js and query param', () => {
expect(getPotentialTsSrcPaths('test-file.js.js?lee=123')).toEqual([
'test-file.js.ts?lee=123',
'test-file.js.tsx?lee=123',
])
})

describe('posToNumber', () => {
test('simple', () => {
const actual = posToNumber('a\nb', { line: 2, column: 0 })
Expand Down
31 changes: 19 additions & 12 deletions packages/vite/src/node/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ import {
copyDir,
emptyDir,
joinUrlSegments,
lookupFile,
normalizePath,
requireResolveFromRootWithFallback,
} from './utils'
Expand All @@ -52,8 +51,8 @@ import {
initDepsOptimizer,
} from './optimizer'
import { loadFallbackPlugin } from './plugins/loadFallback'
import type { PackageData } from './packages'
import { watchPackageDataPlugin } from './packages'
import { findNearestPackageData, watchPackageDataPlugin } from './packages'
import type { PackageCache } from './packages'
import { ensureWatchPlugin } from './plugins/ensureWatch'
import { ESBUILD_MODULES_TARGET, VERSION } from './constants'
import { resolveChokidarOptions } from './watch'
Expand Down Expand Up @@ -578,7 +577,11 @@ export async function build(
const format = output.format || (cjsSsrBuild ? 'cjs' : 'es')
const jsExt =
ssrNodeBuild || libOptions
? resolveOutputJsExtension(format, getPkgJson(config.root)?.type)
? resolveOutputJsExtension(
format,
findNearestPackageData(config.root, config.packageCache)?.data
.type,
)
: 'js'
return {
dir: outDir,
Expand All @@ -595,7 +598,14 @@ export async function build(
? `[name].${jsExt}`
: libOptions
? ({ name }) =>
resolveLibFilename(libOptions, format, name, config.root, jsExt)
resolveLibFilename(
libOptions,
format,
name,
config.root,
jsExt,
config.packageCache,
)
: path.posix.join(options.assetsDir, `[name]-[hash].${jsExt}`),
chunkFileNames: libOptions
? `[name]-[hash].${jsExt}`
Expand Down Expand Up @@ -742,10 +752,6 @@ function prepareOutDir(
}
}

function getPkgJson(root: string): PackageData['data'] {
return JSON.parse(lookupFile(root, ['package.json']) || `{}`)
}

function getPkgName(name: string) {
return name?.[0] === '@' ? name.split('/')[1] : name
}
Expand All @@ -769,15 +775,16 @@ export function resolveLibFilename(
entryName: string,
root: string,
extension?: JsExt,
packageCache?: PackageCache,
): string {
if (typeof libOptions.fileName === 'function') {
return libOptions.fileName(format, entryName)
}

const packageJson = getPkgJson(root)
const packageJson = findNearestPackageData(root, packageCache)?.data
const name =
libOptions.fileName ||
(typeof libOptions.entry === 'string'
(packageJson && typeof libOptions.entry === 'string'
? getPkgName(packageJson.name)
: entryName)

Expand All @@ -786,7 +793,7 @@ export function resolveLibFilename(
'Name in package.json is required if option "build.lib.fileName" is not provided.',
)

extension ??= resolveOutputJsExtension(format, packageJson.type)
extension ??= resolveOutputJsExtension(format, packageJson?.type)

if (format === 'cjs' || format === 'es') {
return `${name}.${extension}`
Expand Down
19 changes: 9 additions & 10 deletions packages/vite/src/node/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ import type { JsonOptions } from './plugins/json'
import type { PluginContainer } from './server/pluginContainer'
import { createPluginContainer } from './server/pluginContainer'
import type { PackageCache } from './packages'
import { findNearestPackageData } from './packages'
import { loadEnv, resolveEnvPrefix } from './env'
import type { ResolvedSSROptions, SSROptions } from './ssr'
import { resolveSSROptions } from './ssr'
Expand Down Expand Up @@ -390,6 +391,7 @@ export async function resolveConfig(
let configFileDependencies: string[] = []
let mode = inlineConfig.mode || defaultMode
const isNodeEnvSet = !!process.env.NODE_ENV
const packageCache: PackageCache = new Map()

// some dependencies e.g. @vue/compiler-* relies on NODE_ENV for getting
// production-specific behavior, so set it early on
Expand Down Expand Up @@ -539,12 +541,12 @@ export async function resolveConfig(
)

// resolve cache directory
const pkgPath = lookupFile(resolvedRoot, [`package.json`], { pathOnly: true })
const pkgDir = findNearestPackageData(resolvedRoot, packageCache)?.dir
const cacheDir = normalizePath(
config.cacheDir
? path.resolve(resolvedRoot, config.cacheDir)
: pkgPath
? path.join(path.dirname(pkgPath), `node_modules/.vite`)
: pkgDir
? path.join(pkgDir, `node_modules/.vite`)
: path.join(resolvedRoot, `.vite`),
)

Expand Down Expand Up @@ -681,7 +683,7 @@ export async function resolveConfig(
return DEFAULT_ASSETS_RE.test(file) || assetsFilter(file)
},
logger,
packageCache: new Map(),
packageCache,
createResolver,
optimizeDeps: {
disabled: 'build',
Expand Down Expand Up @@ -926,7 +928,8 @@ export async function loadConfigFromFile(
// check package.json for type: "module" and set `isESM` to true
try {
const pkg = lookupFile(configRoot, ['package.json'])
isESM = !!pkg && JSON.parse(pkg).type === 'module'
isESM =
!!pkg && JSON.parse(fs.readFileSync(pkg, 'utf-8')).type === 'module'
} catch (e) {}
}

Expand Down Expand Up @@ -1090,11 +1093,7 @@ async function loadConfigFromBundledFile(
try {
return (await dynamicImport(fileUrl)).default
} finally {
try {
await fsp.unlink(fileNameTmp)
} catch {
// already removed if this function is called twice simultaneously
}
fs.unlink(fileNameTmp, () => {}) // Ignore errors
}
}
// for cjs, we can register a custom loader via `_require.extensions`
Expand Down
13 changes: 6 additions & 7 deletions packages/vite/src/node/env.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import fs from 'node:fs'
import path from 'node:path'
import { parse } from 'dotenv'
import { expand } from 'dotenv-expand'
import { arraify, lookupFile } from './utils'
import { arraify, tryStatSync } from './utils'
import type { UserConfig } from './config'

export function loadEnv(
Expand All @@ -26,12 +27,10 @@ export function loadEnv(

const parsed = Object.fromEntries(
envFiles.flatMap((file) => {
const path = lookupFile(envDir, [file], {
pathOnly: true,
rootDir: envDir,
})
if (!path) return []
return Object.entries(parse(fs.readFileSync(path)))
const filePath = path.join(envDir, file)
if (!tryStatSync(filePath)?.isFile()) return []

return Object.entries(parse(fs.readFileSync(filePath)))
}),
)

Expand Down
1 change: 1 addition & 0 deletions packages/vite/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export type {
export type {
PreviewOptions,
PreviewServer,
PreviewServerForHook,
PreviewServerHook,
ResolvedPreviewOptions,
} from './preview'
Expand Down
Loading

0 comments on commit 115b1a3

Please sign in to comment.