| [ Web Proxy ] |
| Viewing: https://pt.vite.dev/guide/api-javascript | [Back] [Original] |
As APIs de JavaScript da Vite so completamente tipadas, e recomendado utilizar a TypeScript ou ativar a verificao de tipo de JavaScript no Visual Studio Code para influenciar o sensor inteligente e a validao.
createServer Assinatura de Tipo:
async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>Exemplo de Utilizao:
import { fileURLToPath } from 'node:url'
import { createServer } from 'vite'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const server = await createServer({
// quaisquer opes vlidas de configurao do utilizador,
// mais `mode` e `configFile`
configFile: false,
root: __dirname,
server: {
port: 1337,
},
})
await server.listen()
server.printUrls()
server.bindCLIShortcuts({ print: true })NOTA
Quando usamos createServer e build no mesmo processo da Node.js, ambas funes dependem da process.env.NODE_ENV para funcionarem corretamente, que tambm dependem da opo de configurao mode. Para evitar comportamento conflituosos, definimos process.env.NODE_ENV ou a mode das duas APIs como development. Caso contrrio, possvel gerar um processo filho para executar as APIs separadamente.
NOTA
Quando usamos o modo intermedirio combinado com a configurao da delegao para tomada da Web, o servidor de HTTP pai deve ser fornecido em middlewareMode para ligar a delegao corretamente:
import http from 'http'
import { createServer } from 'vite'
const parentServer = http.createServer() // or express, koa, etc.
const vite = await createServer({
server: {
// Ativar o modo intermedirio
middlewareMode: {
// Fornecer o servidor de HTTP pai para
// tomada da Web (WebSocket)
server: parentServer,
},
proxy: {
'/ws': {
target: 'ws://localhost:3000',
// Delegando a tomada da Web
ws: true,
},
},
},
})
// @noErrors: 2339
parentServer.use(vite.middlewares)InlineConfig A interface InlineConfig estende o UserConfig com propriedades adicionais:
configFile: especifica o ficheiro de configurao utilizar. Se no for definido, a Vite tentar automaticamente resolver aquele a partir da raiz do projeto. Defina para false para desativar a resoluo automtica.envFile: defina para false para desativar os ficheiros .env.ResolvedConfig A interface ResolvedConfig tem todas as mesmas propriedade de uma UserConfig, exceto que a maioria das propriedades so resolvidas e no definidas. Ela tambm contm servios como:
config.assetsInclude: Uma funo para verificar se um id considerado um recurso.config.logger: O objeto do registador interno da Vite.ViteDevServer interface ViteDevServer {
/**
* The resolved Vite config object.
*/
config: ResolvedConfig
/**
* A connect app instance
* - Can be used to attach custom middlewares to the dev 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.
* Will be null in middleware mode.
*/
httpServer: http.Server | null
/**
* Chokidar watcher instance. If `config.server.watch` is set to `null`,
* it will not watch any files and calling `add` will have no effect.
* https://github.com/paulmillr/chokidar/tree/3.6.0#api
*/
watcher: FSWatcher
/**
* Web socket server with `send(payload)` method.
*/
ws: WebSocketServer
/**
* Rollup plugin container that can run plugin hooks on a given file.
*/
pluginContainer: PluginContainer
/**
* Module graph that tracks the import relationships, url to file mapping
* and hmr state.
*/
moduleGraph: ModuleGraph
/**
* The resolved urls Vite prints on the CLI (URL-encoded). Returns `null`
* in middleware mode or if the server is not listening on any port.
*/
resolvedUrls: ResolvedServerUrls | null
/**
* Programmatically resolve, load and transform a URL and get the result
* without going through the http request pipeline.
*/
transformRequest(
url: string,
options?: TransformOptions,
): Promise<TransformResult | null>
/**
* Apply Vite built-in HTML transforms and any plugin HTML transforms.
*/
transformIndexHtml(
url: string,
html: string,
originalUrl?: string,
): Promise<string>
/**
* Load a given URL as an instantiated module for SSR.
*/
ssrLoadModule(
url: string,
options?: { fixStacktrace?: boolean },
): Promise<Record<string, any>>
/**
* Fix ssr error stacktrace.
*/
ssrFixStacktrace(e: Error): void
/**
* Triggers HMR for a module in the module graph. You can use the `server.moduleGraph`
* API to retrieve the module to be reloaded. If `hmr` is false, this is a no-op.
*/
reloadModule(module: ModuleNode): Promise<void>
/**
* Start the server.
*/
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
/**
* Restart the server.
*
* @param forceOptimize - force the optimizer to re-bundle, same as --force cli flag
*/
restart(forceOptimize?: boolean): Promise<void>
/**
* Stop the server.
*/
close(): Promise<void>
/**
* Bind CLI shortcuts
*/
bindCLIShortcuts(options?: BindCLIShortcutsOptions<ViteDevServer>): void
/**
* Calling `await server.waitForRequestsIdle(id)` will wait until all static imports
* are processed. If called from a load or transform plugin hook, the id needs to be
* passed as a parameter to avoid deadlocks. Calling this function after the first
* static imports section of the module graph has been processed will resolve immediately.
* @experimental
*/
waitForRequestsIdle: (ignoredId?: string) => Promise<void>
}INFORMAO
waitForRequestsIdle is meant to be used as a escape hatch to improve DX for features that can't be implemented following the on-demand nature of the Vite dev server. It can be used during startup by tools like Tailwind to delay generating the app CSS classes until the app code has been seen, avoiding flashes of style changes. When this function is used in a load or transform hook, and the default HTTP1 server is used, one of the six http channels will be blocked until the server processes all static imports. Vite's dependency optimizer currently uses this function to avoid full-page reloads on missing dependencies by delaying loading of pre-bundled dependencies until all imported dependencies have been collected from static imported sources. Vite may switch to a different strategy in a future major release, setting optimizeDeps.crawlUntilStaticImports: false by default to avoid the performance hit in large applications during cold start.
build Assinatura de Tipo:
async function build(
inlineConfig?: InlineConfig,
): Promise<RollupOutput | RollupOutput[]>Exemplo de Utilizao:
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { build } from 'vite'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
await build({
root: path.resolve(__dirname, './project'),
base: '/foo/',
build: {
rollupOptions: {
// ...
},
},
})preview Assinatura de Tipo:
async function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>Exemplo de Utilizao:
import { preview } from 'vite'
const previewServer = await preview({
// quaisquer opes de configurao vlidas do utilizador,
// mais `mode` e `configFile`
preview: {
port: 8080,
open: true,
},
})
previewServer.printUrls()
previewServer.bindCLIShortcuts({ print: true })PreviewServer interface PreviewServer {
/**
* 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 (URL-encoded). Returns `null`
* if the server is not listening on any port.
*/
resolvedUrls: ResolvedServerUrls | null
/**
* Print server urls
*/
printUrls(): void
/**
* Bind CLI shortcuts
*/
bindCLIShortcuts(options?: BindCLIShortcutsOptions<PreviewServer>): void
}resolveConfig Assinatura de Tipo:
async function resolveConfig(
inlineConfig: InlineConfig,
command: 'build' | 'serve',
defaultMode = 'development',
defaultNodeEnv = 'development',
isPreview = false,
): Promise<ResolvedConfig>O valor de command serve em desenvolvimento e pr-visualizao, e build em construo.
mergeConfig Assinatura de Tipo:
function mergeConfig(
defaults: Record<string, any>,
overrides: Record<string, any>,
isRoot = true,
): Record<string, any>Combina profundamente duas configuraes de Vite. isRoot representa o nvel dentro da configurao de Vite que est sendo combinada. Por exemplo, defina para false se estiveres combinando duas opes de build.
NOTA
mergeConfig aceita apenas configurao na forma de objeto. Se tiveres uma configurao na forma de funo de resposta, deves cham-la antes de passar para mergeConfig.
Tu podes usar a auxiliar defineConfig para combinar uma configurao na forma de funo de resposta com uma outra configurao:
import {
defineConfig,
mergeConfig,
type UserConfigFnObject,
type UserConfig,
} from 'vite'
declare const configAsCallback: UserConfigFnObject
declare const configAsObject: UserConfig
// ---cut---
export default defineConfig((configEnv) =>
mergeConfig(configAsCallback(configEnv), configAsObject),
)searchForWorkspaceRoot Assinatura de Tipo:
function searchForWorkspaceRoot(
current: string,
root = searchForPackageRoot(current),
): stringRelacionado ao: server.fs.allow
Procura pela raiz do potencial espao de trabalho se cumprir as seguintes condies, caso contrrio recuaria para o root:
workspaces no package.jsonlerna.jsonpnpm-workspace.yamlloadEnv Assinatura de Tipo:
function loadEnv(
mode: string,
envDir: string,
prefixes: string | string[] = 'VITE_',
): Record<string, string>Relacionado ao: Ficheiros .env
Carrega os ficheiros .env dentro de envDir por padro, s as variveis de ambiente prefixadas com a VITE_ so carregadas, a menos que prefixes seja modificada.
normalizePath Assinatura de Tipo:
function normalizePath(id: string): stringRelacionado ao: Normalizao do Caminho
Normaliza um caminho para operar internamente entre as extenses de Vite.
transformWithEsbuild Assinatura de Tipo:
async function transformWithEsbuild(
code: string,
filename: string,
options?: EsbuildTransformOptions,
inMap?: object,
): Promise<ESBuildTransformResult>Transforma a JavaScript ou TypeScript com a esbuild. til para extenses que preferem harmonizao com transformao da esbuild interna da Vite.
loadConfigFromFile Assinatura de Tipo:
async function loadConfigFromFile(
configEnv: ConfigEnv,
configFile?: string,
configRoot: string = process.cwd(),
logLevel?: LogLevel,
customLogger?: Logger,
): Promise<{
path: string
config: UserConfig
dependencies: string[]
} | null>Carrega manualmente um ficheiro de configurao de Vite com a esbuild.
preprocessCSS Assinatura do Tipo:
async function preprocessCSS(
code: string,
filename: string,
config: ResolvedConfig,
): Promise<PreprocessCSSResult>
interface PreprocessCSSResult {
code: string
map?: SourceMapInput
modules?: Record<string, string>
deps?: Set<string>
}Pr-processa os ficheiros .css, .scss, .sass, .less, .styl e .stylus para CSS simples para poderem ser utilizados em navegadores ou analisados por outras ferramentas. Semelhante ao suporte de pr-processamento de CSS embutido, o pr-processador correspondente deve ser instalado se usado.
O pr-processador utilizado inferido a partir da extenso do filename. Se o filename terminar com module.{ext}, este inferido como um mdulo de CSS e o resultado retornado incluir um objeto de modules mapeando os nomes originais das classes para os transformados.
Notemos que o pr-processamento no resolver os endereos de localizao de recurso em url() ou image-set().
Lanada sob a Licena MIT. (b6c4bac9)
Direitos de Autor 2019-presente VoidZero Inc. & Colaboradores da Vite
| Web Proxy Viewer | New URL | Original Page |