1、createServer
.创建vite服务器
async function createServer(inlineConfig?: InlineConfig): Promise<ViteDevServer>
参数:
inlineConfig接口扩展了 UserConfig 并添加了以下属性
.configFile:指明要使用的配置文件。如果没有设置,Vite 将尝试从项目根目录自动解析。设置为 false 可以禁用自动解析功能
.envFile:设置为 false 时,则禁用 .env 文件
返回值:
ViteDevServer
interface ViteDevServer {
config: ResolvedConfig,被解析的 Vite 配置对象
/**
* 一个 connect 应用实例
* - 可以用于将自定义中间件附加到开发服务器。
* - 还可以用作自定义http服务器的处理函数。
或作为中间件用于任何 connect 风格的 Node.js 框架。
*
* https://github.com/senchalabs/connect#use-middleware
*/
middlewares: Connect.Server
httpServer: http.Server | null, 本机 node http 服务器实例
watcher: FSWatcher, chokidar监听器实例
ws: WebSocketServer, web socket 服务器,带有 `send(payload)` 方法。
pluginContainer: PluginContainer, Rollup 插件容器,可以针对给定文件运行插件钩子。
moduleGraph: ModuleGraph, 跟踪导入关系、url 到文件映射和 hmr 状态的模块图。
/**
* 以代码方式解析、加载和转换 url 并获取结果
* 而不需要通过 http 请求管道。
*/
transformRequest(
url: string,
options?: TransformOptions
): Promise<TransformResult | null>
/**
* 应用 Vite 内建 HTML 转换和任意插件 HTML 转换
*/
transformIndexHtml(url: string, html: string): Promise<string>
/**
* 加载一个给定的 URL 作为 SSR 的实例化模块
*/
ssrLoadModule(
url: string,
options?: { fixStacktrace?: boolean }
): Promise<Record<string, any>>
/**
* 解决 ssr 错误堆栈信息
*/
ssrFixStacktrace(e: Error): void
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>, 启动服务器
/**
* 重启服务器
*
* @param forceOptimize - 强制优化器打包,和命令行内使用 --force 一致
*/
restart(forceOptimize?: boolean): Promise<void>
/**
* 停止服务器
*/
close(): Promise<void>
}
示例:
const { createServer } = require('vite')
;(async () => {
const server = await createServer({
// 任何合法的用户配置选项,加上 `mode` 和 `configFile`
configFile: false,
root: __dirname,
server: {
port: 1337
}
})
await server.listen()
server.printUrls()
})()
2、build
async function build(
inlineConfig?: InlineConfig
): Promise<RollupOutput | RollupOutput[]>
const path = require('path')
const { build } = require('vite')
;(async () => {
await build({
root: path.resolve(__dirname, './project'),
base: '/foo/',
build: {
rollupOptions: {
// ...
}
}
})
})()
3、preview
async function preview(inlineConfig?: InlineConfig): Promise<PreviewServer>
const { preview } = require('vite')
;(async () => {
const previewServer = await preview({
// 任何有效的用户配置项,将加上 `mode` 和 `configFile`
preview: {
port: 8080,
open: true
}
})
previewServer.printUrls()
})()
4、resolveConfig
async function resolveConfig(
inlineConfig: InlineConfig,
command: 'build' | 'serve',
defaultMode?: string
): Promise<ResolvedConfig>
5、transformWithEsbuild
async function transformWithEsbuild(
code: string,
filename: string,
options?: EsbuildTransformOptions,
inMap?: object
): Promise<ESBuildTransformResult>
6、normalizePath
路径规范化
normalizePath('foo\\bar') // 'foo/bar'
normalizePath('foo/bar') // 'foo/bar'
vite 函数相关api
最新推荐文章于 2024-05-31 18:20:13 发布