美文网首页
Vite-前端构建工具

Vite-前端构建工具

作者: small_zeo | 来源:发表于2021-12-31 15:13 被阅读0次

    Vite

    Vite 是一种新型前端构建工具,能够显著提升前端开发体验。它主要由两部分组成:

    • 一个开发服务器,它基于原生ES模块提供了丰富的内建功能,如速度快到惊人的模块热更新(HMR)
    • 一套构建指令,它使用Rollup打包你的代码,并且它是预配置的,可输出用于生产环境的高度优化过的静态资源。
      Vite意在提供开箱即用的配置,同时它的插件API和JavaScript API带来了高度的可扩展性,并有完整的类型支持。

    为什么选Vite

    当我们开始构建越来越大型的应用时,需要处理的 JavaScript 代码量也呈指数级增长。包含数千个模块的大型项目相当普遍。我们开始遇到性能瓶颈 —— 使用 JavaScript 开发的工具通常需要很长时间(甚至是几分钟!)才能启动开发服务器,即使使用 HMR,文件修改后的效果也需要几秒钟才能在浏览器中反映出来。如此循环往复,迟钝的反馈会极大地影响开发者的开发效率和幸福感。

    Vite 旨在利用生态系统中的新进展解决上述问题:浏览器开始原生支持ES模块,且越来越多JavaScript 工作使用编译型语言编写。

    缓慢的服务器启动

    当冷启动开发服务器时,基于打包器的方式启动必须优先抓取并构建你的整个应用,然后才能提供服务。
    Vite通过在一开始将应用中的模块区分为依赖和源码两类,改进了开发服务器启动时间。

    • 依赖
      Vite 将会使用esbuild预构建依赖。Esbuild使用Go编写,并且比以JavaScript编写的打包器预构建依赖快10-100倍

    • 源码
      Vite 以原生ESM方式提供源码。这实际上是让浏览器接管了打包程序的部分工作:Vite只需要在浏览器请求源码时进行转换并按需提供源码。

    缓慢的更新

    基于打包器启动时,重建整个包的效率很低。原因显而易见: 因为这样更新速度会随着应用体积增长而直线下降。
    在Vite中, HMR是在原生ESM上执行的。当编辑一个文件时,Vite只需要精准地使已编辑的模块与其最近的HMR边界之间的链失活,使得无论应用大小如何,HMR始终能保持快速更新。
    Vite同时利用HTTP头来加速整个页面的重新加载:源码模块的请求会根据304 Not Modified 进行协商缓存,而依赖模块则会通过 Cache-Control: max-age=31,immutable 进行强缓存,因此一旦被缓存它们将不需要再次请求。
    ·

    源码分析

    server篇

    image.png
    • 1.解析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
    }
    
      1. 定义其他类型,由于非主线,这里不展开,只展示对应功能
    // 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
    }
    
      1. 核心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
    }
    
    

    client篇

      1. 从服务端我们了解到是接住websocket与客户端进行通信,下面我们来看一下客户端的代码:
        初始化websocket实例,socket协议以来当前的协议,如果是https那就使用wss,否则使用ws。子协议名称使用vite-hmr
    // packages/vite/src/client/client.ts
    
    const socketProtocol =
      __HMR_PROTOCOL__ || (location.protocol === 'https:' ? 'wss' : 'ws')
    const socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`
    const socket = new WebSocket(`${socketProtocol}://${socketHost}`, 'vite-hmr')
    const base = __BASE__ || '/'
    
      1. 添加socket消息监听事件,消息使用JSON.parse解析
    // packages/vite/src/client/client.ts
    
    socket.addEventListener('message', async ({ data }) => {
      handleMessage(JSON.parse(data))
    })
    
    async function handleMessage(payload: HMRPayload) {
      switch (payload.type) {
        case 'connected':
          console.log(`[vite] connected.`)
          // proxy(nginx, docker) hmr ws maybe caused timeout,
          // so send ping package let ws keep alive.
          setInterval(() => socket.send('ping'), __HMR_TIMEOUT__)
          break
        case 'update':
          notifyListeners('vite:beforeUpdate', payload)
          // if this is the first update and there's already an error overlay, it
          // means the page opened with existing server compile error and the whole
          // module script failed to load (since one of the nested imports is 500).
          // in this case a normal update won't work and a full reload is needed.
          if (isFirstUpdate && hasErrorOverlay()) {
            window.location.reload()
            return
          } else {
            clearErrorOverlay()
            isFirstUpdate = false
          }
          payload.updates.forEach((update) => {
            if (update.type === 'js-update') {
              queueUpdate(fetchUpdate(update))
            } else {
              // css-update
              // this is only sent when a css file referenced with <link> is updated
              let { path, timestamp } = update
              path = path.replace(/\?.*/, '')
              // can't use querySelector with `[href*=]` here since the link may be
              // using relative paths so we need to use link.href to grab the full
              // URL for the include check.
              const el = (
                [].slice.call(
                  document.querySelectorAll(`link`)
                ) as HTMLLinkElement[]
              ).find((e) => e.href.includes(path))
              if (el) {
                const newPath = `${path}${
                  path.includes('?') ? '&' : '?'
                }t=${timestamp}`
                el.href = new URL(newPath, el.href).href
              }
              console.log(`[vite] css hot updated: ${path}`)
            }
          })
          break
        case 'custom': {
          notifyListeners(payload.event as CustomEventName<any>, payload.data)
          break
        }
        case 'full-reload':
          notifyListeners('vite:beforeFullReload', payload)
          if (payload.path && payload.path.endsWith('.html')) {
            // if html file is edited, only reload the page if the browser is
            // currently on that page.
            const pagePath = location.pathname
            const payloadPath = base + payload.path.slice(1)
            if (
              pagePath === payloadPath ||
              (pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)
            ) {
              location.reload()
            }
            return
          } else {
            location.reload()
          }
          break
        case 'prune':
          notifyListeners('vite:beforePrune', payload)
          // After an HMR update, some modules are no longer imported on the page
          // but they may have left behind side effects that need to be cleaned up
          // (.e.g style injections)
          // TODO Trigger their dispose callbacks.
          payload.paths.forEach((path) => {
            const fn = pruneMap.get(path)
            if (fn) {
              fn(dataMap.get(path))
            }
          })
          break
        case 'error': {
          notifyListeners('vite:error', payload)
          const err = payload.err
          if (enableOverlay) {
            createErrorOverlay(err)
          } else {
            console.error(
              `[vite] Internal Server Error\n${err.message}\n${err.stack}`
            )
          }
          break
        }
        default: {
          const check: never = payload
          return check
        }
      }
    }
    

    参考文章

    官方中文文档
    vite-github
    [vite源码解析]server篇

    相关文章

      网友评论

          本文标题:Vite-前端构建工具

          本文链接:https://www.haomeiwen.com/subject/erehqrtx.html