我们从上一篇的cli可以看到cli中主要通过下面的示例启动了对应的服务,下面我们就来进一步解析vite如何设计服务
// packages/vite/src/node/server/index.ts
const server = await createServer({
root,
base: options.base,
mode: options.mode,
configFile: options.config,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
server: cleanOptions(options) as ServerOptions
})
第1步:定义server参数
// packages/vite/src/node/server/index.ts
export interface ServerOptions {
host?: string | boolean
port?: number
/**
* Enable TLS + HTTP/2.
* Note: this downgrades to TLS only when the proxy option is also used.
*/
https?: boolean | https.ServerOptions
/**
* Open browser window on startup
*/
open?: boolean | string
/**
* Force dep pre-optimization regardless of whether deps have changed.
*/
force?: boolean
/**
* Configure HMR-specific options (port, host, path & protocol)
*/
hmr?: HmrOptions | boolean
/**
* chokidar watch options
* https://github.com/paulmillr/chokidar#api
*/
watch?: WatchOptions
/**
* Configure custom proxy rules for the dev server. Expects an object
* of `{ key: options }` pairs.
* Uses [`http-proxy`](https://github.com/http-party/node-http-proxy).
* Full options [here](https://github.com/http-party/node-http-proxy#options).
*
* Example `vite.config.js`:
* ``` js
* module.exports = {
* proxy: {
* // string shorthand
* '/foo': 'http://localhost:4567/foo',
* // with options
* '/api': {
* target: 'http://jsonplaceholder.typicode.com',
* changeOrigin: true,
* rewrite: path => path.replace(/^\/api/, '')
* }
* }
* }
* ```
*/
proxy?: Record<string, string | ProxyOptions>
/**
* Configure CORS for the dev server.
* Uses https://github.com/expressjs/cors.
* Set to `true` to allow all methods from any origin, or configure separately
* using an object.
*/
cors?: CorsOptions | boolean
/**
* If enabled, vite will exit if specified port is already in use
*/
strictPort?: boolean
/**
* Create Vite dev server to be used as a middleware in an existing server
*/
middlewareMode?: boolean | 'html' | 'ssr'
/**
* Prepend this folder to http requests, for use when proxying vite as a subfolder
* Should start and end with the `/` character
*/
base?: string
/**
* Options for files served via '/\@fs/'.
*/
fs?: FileSystemServeOptions
}
第2步:
定义其他类型,由于非主线,这里不展开,只展示对应功能
// packages/vite/src/node/server/index.ts
// resolved 服务参数
export interface ResolvedServerOptions extends ServerOptions {
fs: Required<FileSystemServeOptions>
}
// 文件系统服务参数
export interface FileSystemServeOptions {
/**
* Strictly restrict file accessing outside of allowing paths.
*
* Set to `false` to disable the warning
* Default to false at this moment, will enabled by default in the future versions.
*
* @expiremental
* @default undefined
*/
strict?: boolean | undefined
/**
* Restrict accessing files outside the allowed directories.
*
* Accepts absolute path or a path relative to project root.
* Will try to search up for workspace root by default.
*
* @expiremental
*/
allow?: string[]
}
/**
* 标准的cors参数
* https://github.com/expressjs/cors#configuration-options
*/
export interface CorsOptions {
origin?:
| CorsOrigin
| ((origin: string, cb: (err: Error, origins: CorsOrigin) => void) => void)
methods?: string | string[]
allowedHeaders?: string | string[]
exposedHeaders?: string | string[]
credentials?: boolean
maxAge?: number
preflightContinue?: boolean
optionsSuccessStatus?: number
}
// vite 开发服务器
/**
*/
export 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
/**
* @deprecated use `server.middlewares` instead
*/
app: Connect.Server
/**
* native Node http server instance
* will be null in middleware mode
*/
httpServer: http.Server | null
/**
* chokidar watcher instance
* https://github.com/paulmillr/chokidar#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
/**
* 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>
/**
* Util for transforming a file with esbuild.
* Can be useful for certain plugins.
*/
transformWithEsbuild(
code: string,
filename: string,
options?: EsbuildTransformOptions,
inMap?: object
): Promise<ESBuildTransformResult>
/**
* Load a given URL as an instantiated module for SSR.
*/
ssrLoadModule(url: string): Promise<Record<string, any>>
/**
* Fix ssr error stacktrace
*/
ssrFixStacktrace(e: Error): void
/**
* Start the server.
*/
listen(port?: number, isRestart?: boolean): Promise<ViteDevServer>
/**
* Stop the server.
*/
close(): Promise<void>
/**
* @internal
*/
_optimizeDepsMetadata: DepOptimizationMetadata | null
/**
* Deps that are externalized
* @internal
*/
_ssrExternals: string[] | null
/**
* @internal
*/
_globImporters: Record<
string,
{
module: ModuleNode
importGlobs: {
base: string
pattern: string
}[]
}
>
/**
* @internal
*/
_isRunningOptimizer: boolean
/**
* @internal
*/
_registerMissingImport:
| ((id: string, resolved: string, ssr: boolean | undefined) => void)
| null
/**
* @internal
*/
_pendingReload: Promise<void> | null
}
第4步: 核心createServer
输入为配置参数,输出为上面定义的ViteDevServer
// packages/vite/src/node/server/index.ts
export async function createServer(
inlineConfig: InlineConfig = {}
): Promise<ViteDevServer> {
// 参数解析
const config = await resolveConfig(inlineConfig, 'serve', 'development')
const root = config.root
const serverConfig = config.server
const httpsOptions = await resolveHttpsConfig(config)
let { middlewareMode } = serverConfig
if (middlewareMode === true) {
middlewareMode = 'ssr'
}
// 创建websocket服务:服务端与客户端基于ws通信
const middlewares = connect() as Connect.Server
const httpServer = middlewareMode
? null
: await resolveHttpServer(serverConfig, middlewares, httpsOptions)
const ws = createWebSocketServer(httpServer, config, httpsOptions)
// 使用chokidar监控root目录,忽略node_modules和.git及其他配置的忽略目录
const { ignored = [], ...watchOptions } = serverConfig.watch || {}
const watcher = chokidar.watch(path.resolve(root), {
ignored: ['**/node_modules/**', '**/.git/**', ...ignored],
ignoreInitial: true,
ignorePermissionErrors: true,
disableGlobbing: true,
...watchOptions
}) as FSWatcher
// 创建插件容器,将配置及watcher传入
const plugins = config.plugins
const container = await createPluginContainer(config, watcher)
// module graph基于插件容器来创建
const moduleGraph = new ModuleGraph(container)
const closeHttpServer = createServerCloseFn(httpServer)
// eslint-disable-next-line prefer-const
let exitProcess: () => void
// 创建ViteDevServer
const server: ViteDevServer = {
config: config,
middlewares,
get app() {
config.logger.warn(
`ViteDevServer.app is deprecated. Use ViteDevServer.middlewares instead.`
)
return middlewares
},
httpServer,
watcher,
pluginContainer: container,
ws,
moduleGraph,
transformWithEsbuild,
transformRequest(url, options) {
return transformRequest(url, server, options)
},
transformIndexHtml: null as any,
ssrLoadModule(url) {
if (!server._ssrExternals) {
server._ssrExternals = resolveSSRExternal(
config,
server._optimizeDepsMetadata
? Object.keys(server._optimizeDepsMetadata.optimized)
: []
)
}
return ssrLoadModule(url, server)
},
ssrFixStacktrace(e) {
if (e.stack) {
e.stack = ssrRewriteStacktrace(e.stack, moduleGraph)
}
},
listen(port?: number, isRestart?: boolean) {
return startServer(server, port, isRestart)
},
async close() {
process.off('SIGTERM', exitProcess)
if (!process.stdin.isTTY) {
process.stdin.off('end', exitProcess)
}
await Promise.all([
watcher.close(),
ws.close(),
container.close(),
closeHttpServer()
])
},
_optimizeDepsMetadata: null,
_ssrExternals: null,
_globImporters: {},
_isRunningOptimizer: false,
_registerMissingImport: null,
_pendingReload: null
}
server.transformIndexHtml = createDevHtmlTransformFn(server)
exitProcess = async () => {
try {
await server.close()
} finally {
process.exit(0)
}
}
process.once('SIGTERM', exitProcess)
if (process.env.CI !== 'true') {
process.stdin.on('end', exitProcess)
process.stdin.resume()
}
// 配置watcher的change,add, unlink事件
// 基于配置设置middlewares:proxy,decodeURL,servePublicMiddleware,transformMiddleware,serveRawFsMiddleware,serveStaticMiddleware,indexHtmlMiddleware,errorMiddleware等
return server
}
备注
- connect :针对http服务的中间件模型,类似koa
- chokidar:精简的跨端文件监控库
- acorn: js语法解析pkg
- magic-string: js 源码string操作pkg