Vite一經發布就吸引了不少人的關注,NPM下載量一路攀升:javascript
而在Vite以前,還有Snowpack也一樣採用了No-Bundler構建方案。那麼No-Bundler模式與傳統老牌構建工具Webpack孰優孰劣呢?可否實現平滑遷移和完美取代?css
下面就帶着問題一塊兒分析一下Vite二、Snowpack3和Webpack5吧!html
Webpack是近年來使用量最大,同時社區最完善的前端打包構建工具,5.x版本對構建細節進行了優化,某些場景下打包速度提高明顯,但也沒能解決以前一直被人詬病的大項目編譯慢的問題,這也和Webpack自己的機制相關。前端
已經有不少文章講解Webpack的運行原理了,本文就再也不贅述,咱們着重分析一下後起之秀。vue
首次提出利用瀏覽器原生ESM能力的工具並不是是Vite,而是一個叫作Snowpack的工具。前身是@pika/web
,從1.x版本開始改名爲Snowpack。java
Snowpack在其官網是這樣進行自我介紹的:「Snowpack是一種閃電般快速的前端構建工具,專爲現代Web設計。 它是開發工做流程較重,較複雜的打包工具(如Webpack或Parcel)的替代方案。Snowpack利用JavaScript的本機模塊系統(稱爲ESM)來避免沒必要要的工做並保持流暢的開發體驗」。 node
Snowpack的理念是減小或避免整個bundle的打包,每次保存單個文件時,傳統的JavaScript構建工具(例如Webpack和Parcel)都須要從新構建和從新打包應用程序的整個bundle。從新打包時增長了在保存更改和看到更改反映在瀏覽器之間的時間間隔。在開發過程當中**,** Snowpack爲你的應用程序提供unbundled server**。**每一個文件只須要構建一次,就能夠永久緩存。文件更改時,Snowpack會從新構建該單個文件。在從新構建每次變動時沒有任何的時間浪費,只須要在瀏覽器中進行HMR更新。webpack
再瞭解一下發明Snowpack的團隊Pika,Pika團隊有一個宏偉的使命:讓Web應用提速90%:git
爲此,Pika團隊開發並維護了兩個技術體系:構建相關的Snowpack和造福大衆的Skypack。github
在這裏咱們簡單聊一下Skypack的初衷,當前許多Web應用都是在不一樣NPM包的基礎上進行構建的,而這些NPM包都被Webpack之類的打包工具打成了一個bundle,若是這些NPM包都來源於同一個CDN地址,且支持跨域緩存,那麼這些NPM包在緩存生效期內都只須要加載一次,其餘網站用到了一樣的NPM包,就不須要從新下載,而是直接讀取本地緩存。
例如,智聯的官網與B端都是基於vue+vuex開發的,當HR在B端發完職位後,進入官網預覽本身的公司對外主頁都不用從新下載,只須要下載智聯官網相關的一些業務代碼便可。爲此,Pika專門創建了一個CDN(Skypack)用來下載NPM上的ESM模塊。
後來Snowpack發佈的時候,Pika團隊順便發表了一篇名爲《A Future Without Webpack》 的文章,告訴你們能夠嘗試拋棄Webpack,採用全新的打包構建方案,下圖取自其官網,展現了bundled與unbundled之間的區別。
在HTTP/2和5G網絡的加持下,咱們能夠預見到HTTP請求數量再也不成爲問題,而隨着Web領域新標準的普及,瀏覽器也在逐步支持ESM(<script module>
)。
啓動構建時會調用源碼src/index.ts
中的cli方法,該方法的代碼刪減版以下:
import {command as buildCommand} from './commands/build';
export async function cli(args: string[]) {
const cliFlags = yargs(args, {
array: ['install', 'env', 'exclude', 'external']
}) as CLIFlags;
if (cmd === 'build') {
await buildCommand(commandOptions);
return process.exit(0);
}
}
複製代碼
進入commands/build文件,執行大體邏輯以下:
export async function build(commandOptions: CommandOptions): Promise<SnowpackBuildResult> {
// 讀取config代碼
// ...
for (const runPlugin of config.plugins) {
if (runPlugin.run) {
// 執行插件
}
}
// 將 `import.meta.env` 的內容寫入文件
await fs.writeFile(
path.join(internalFilESbuildLoc, 'env.js'),
generateEnvModule({mode: 'production', isSSR}),
);
// 若是 HMR,則加載 hmr 工具文件
if (getIsHmrEnabled(config)) {
await fs.writeFile(path.resolve(internalFilESbuildLoc, 'hmr-client.js'), HMR_CLIENT_CODE);
await fs.writeFile(
path.resolve(internalFilESbuildLoc, 'hmr-error-overlay.js'),
HMR_OVERLAY_CODE,
);
hmrEngine = new EsmHmrEngine({port: config.devOptions.hmrPort});
}
// 開始構建源文件
logger.info(colors.yellow('! building source files...'));
const buildStart = performance.now();
const buildPipelineFiles: Record<string, FileBuilder> = {};
// 根據主 buildPipelineFiles 列表安裝全部須要的依賴項,對應下面第三部
async function installDependencies() {
const scannedFiles = Object.values(buildPipelineFiles)
.map((f) => Object.values(f.filesToResolve))
.reduce((flat, item) => flat.concat(item), []);
// 指定安裝的目標文件夾
const installDest = path.join(buildDirectoryLoc, config.buildOptions.metaUrlPath, 'pkg');
// installOptimizedDependencies 方法調用了 esinstall 包,包內部調用了 rollup 進行模塊分析及 commonjs 轉 esm
const installResult = await installOptimizedDependencies(
scannedFiles,
installDest,
commandOptions,
);
return installResult
}
// 下面因代碼繁多,僅展現源碼中的註釋
// 0. Find all source files.
// 1. Build all files for the first time, from source.
// 2. Install all dependencies. This gets us the import map we need to resolve imports.
// 3. Resolve all built file imports.
// 4. Write files to disk.
// 5. Optimize the build.
// "--watch" mode - Start watching the file system.
// Defer "chokidar" loading to here, to reduce impact on overall startup time
logger.info(colors.cyan('watching for changes...'));
const chokidar = await import('chokidar');
// 本地文件刪除時清除 buildPipelineFiles 對應的文件
function onDeleteEvent(fileLoc: string) {
delete buildPipelineFiles[fileLoc];
}
// 本地文件建立及修改時觸發
async function onWatchEvent(fileLoc: string) {
// 1. Build the file.
// 2. Resolve any ESM imports. Handle new imports by triggering a re-install.
// 3. Write to disk. If any proxy imports are needed, write those as well.
// 觸發 HMR
if (hmrEngine) {
hmrEngine.broadcastMessage({type: 'reload'});
}
}
// 建立文件監聽器
const watcher = chokidar.watch(Object.keys(config.mount), {
ignored: config.exclude,
ignoreInitial: true,
persistent: true,
disableGlobbing: false,
useFsEvents: isFsEventsEnabled(),
});
watcher.on('add', (fileLoc) => onWatchEvent(fileLoc));
watcher.on('change', (fileLoc) => onWatchEvent(fileLoc));
watcher.on('unlink', (fileLoc) => onDeleteEvent(fileLoc));
// 返回一些方法給 plugin 使用
return {
result: buildResultManifest,
onFileChange: (callback) => (onFileChangeCallback = callback),
async shutdown() {
await watcher.close();
},
};
}
export async function command(commandOptions: CommandOptions) {
try {
await build(commandOptions);
} catch (err) {
logger.error(err.message);
logger.debug(err.stack);
process.exit(1);
}
if (commandOptions.config.buildOptions.watch) {
// We intentionally never want to exit in watch mode!
return new Promise(() => {});
}
}
複製代碼
全部的模塊會通過install進行安裝,此處的安裝是將模塊轉換成ESM放在pkg目錄下,並非npm包安裝的概念。
在Snowpack3中增長了一些老版本不支持的能力,如:內部默認集成Node服務、支持CSS Modules、支持HMR等。
Vite(法語單詞「 fast」,發音爲/vit/)是一種構建工具,旨在爲現代Web項目提供更快,更精簡的開發體驗。它包括兩個主要部分:
隨着vue3的推出,Vite也隨之成名,起初是一個針對Vue3的打包編譯工具,目前2.x版本發佈面向了任何前端框架,不侷限於Vue,在Vite的README中也提到了在某些想法上參考了Snowpack。
在已有方案上Vue本能夠拋棄Webpack選擇Snowpack,但選擇開發Vite來造一個新的輪子也有Vue團隊本身的考量。
在Vite官方文檔列舉了Vite與Snowpack的異同,其實本質是說明Vite相較於Snowpack的優點。
相同點,引用Vite官方的話:
Snowpack is also a no-bundle native ESM dev server that is very similar in scope to Vite。
不一樣點:
Snowpack的build默認是不打包的,好處是能夠靈活選擇Rollup、Webpack等打包工具,壞處就是不一樣打包工具帶來了不一樣的體驗,當前ESbuild做爲生產環境打包尚不穩定,Rollup也沒有官方支持Snowpack,不一樣的工具會產生不一樣的配置文件;
Vite支持多page打包;
Vite支持Library Mode;
Vite支持CSS代碼拆分,Snowpack默認是CSS in JS;
Vite優化了異步代碼加載;
Vite支持動態引入 polyfill;
Vite官方的 legacy mode plugin,能夠同時生成 ESM 和 NO ESM;
First Class Vue Support。
第5點Vite官網有詳細介紹,在非優化方案中,當A
導入異步塊時,瀏覽器必須先請求並解析,A
而後才能肯定它也須要公共塊C
。這會致使額外的網絡往返:
Entry ---> A ---> C
複製代碼
Vite經過預加載步驟自動重寫代碼拆分的動態導入調用,以便在A
請求時並行C
獲取:
Entry ---> (A + C)
複製代碼
可能C
會屢次導入,這將致使在未優化的狀況下發出屢次請求。Vite的優化將跟蹤全部import,以徹底消除重複請求,示意圖以下:
第8點的First Class Vue Support,雖然在列表的最後一項,實則是點睛之筆。
Vite在啓動時,若是不是中間件模式,內部默認會啓一個http server。
export async function createServer( inlineConfig: InlineConfig = {} ): Promise<ViteDevServer> {
// 獲取 config
const config = await resolveConfig(inlineConfig, 'serve', 'development')
const root = config.root
const serverConfig = config.server || {}
// 判斷是不是中間件模式
const middlewareMode = !!serverConfig.middlewareMode
const middlewares = connect() as Connect.Server
// 中間件模式不建立 http 服務,容許外部以中間件形式調用:https://Vitejs.dev/guide/api-javascript.html#using-the-Vite-server-as-a-middleware
const httpServer = middlewareMode
? null
: await resolveHttpServer(serverConfig, middlewares)
// 建立 websocket 服務
const ws = createWebSocketServer(httpServer, config)
// 建立文件監聽器
const { ignored = [], ...watchOptions } = serverConfig.watch || {}
const watcher = chokidar.watch(path.resolve(root), {
ignored: ['**/node_modules/**', '**/.git/**', ...ignored],
ignoreInitial: true,
ignorePermissionErrors: true,
...watchOptions
}) as FSWatcher
const plugins = config.plugins
const container = await createPluginContainer(config, watcher)
const moduleGraph = new ModuleGraph(container)
const closeHttpServer = createSeverCloseFn(httpServer)
const server: ViteDevServer = {
// 前面定義的常量,包含:config、中間件、websocket、文件監聽器、ESbuild 等
}
// 監聽進程關閉
process.once('SIGTERM', async () => {
try {
await server.close()
} finally {
process.exit(0)
}
})
watcher.on('change', async (file) => {
file = normalizePath(file)
// 文件更改時使模塊圖緩存無效
moduleGraph.onFileChange(file)
if (serverConfig.hmr !== false) {
try {
// 大體邏輯是修改 env 文件時直接重啓 server,根據 moduleGraph 精準刷新,必要時所有刷新
await handleHMRUpdate(file, server)
} catch (err) {
ws.send({
type: 'error',
err: prepareError(err)
})
}
}
})
// 監聽文件建立
watcher.on('add', (file) => {
handleFileAddUnlink(normalizePath(file), server)
})
// 監聽文件刪除
watcher.on('unlink', (file) => {
handleFileAddUnlink(normalizePath(file), server, true)
})
// 掛載插件的服務配置鉤子
const postHooks: ((() => void) | void)[] = []
for (const plugin of plugins) {
if (plugin.configureServer) {
postHooks.push(await plugin.configureServer(server))
}
}
// 加載多箇中間件,包含 cors、proxy、open-in-editor、靜態文件服務等
// 運行post鉤子,在html中間件以前應用的,這樣外部中間件就能夠提供自定義內容取代 index.html
postHooks.forEach((fn) => fn && fn())
if (!middlewareMode) {
// 轉換 html
middlewares.use(indexHtmlMiddleware(server, plugins))
// 處理 404
middlewares.use((_, res) => {
res.statusCode = 404
res.end()
})
}
// errorHandler 中間件
middlewares.use(errorMiddleware(server, middlewareMode))
// 執行優化邏輯
const runOptimize = async () => {
if (config.optimizeCacheDir) {
// 將使用 ESbuild 將依賴打包並寫入 node_modules/.Vite/xxx
await optimizeDeps(config)
// 更新 metadata 文件
const dataPath = path.resolve(config.optimizeCacheDir, 'metadata.json')
if (fs.existsSync(dataPath)) {
server._optimizeDepsMetadata = JSON.parse(
fs.readFileSync(dataPath, 'utf-8')
)
}
}
}
if (!middlewareMode && httpServer) {
// 在服務器啓動前覆蓋listen方法並運行優化器
const listen = httpServer.listen.bind(httpServer)
httpServer.listen = (async (port: number, ...args: any[]) => {
await container.buildStart({})
await runOptimize()
return listen(port, ...args)
}) as any
httpServer.once('listening', () => {
// 更新實際端口,由於這可能與初始端口不一樣
serverConfig.port = (httpServer.address() as AddressInfo).port
})
} else {
await runOptimize()
}
// 最後返回服務
return server
}
複製代碼
訪問Vite服務的時候,默認會返回index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="module" src="/@Vite/client"></script>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>
複製代碼
處理import文件邏輯,在node/plugins/importAnalysis.ts文件內:
export function importAnalysisPlugin(config: ResolvedConfig): Plugin {
const clientPublicPath = path.posix.join(config.base, CLIENT_PUBLIC_PATH)
let server: ViteDevServer
return {
name: 'Vite:import-analysis',
configureServer(_server) {
server = _server
},
async transform(source, importer, ssr) {
const rewriteStart = Date.now()
// 使用 es-module-lexer 進行語法解析
await init
let imports: ImportSpecifier[] = []
try {
imports = parseImports(source)[0]
} catch (e) {
const isVue = importer.endsWith('.vue')
const maybeJSX = !isVue && isJSRequest(importer)
// 判斷文件後綴給不一樣的提示信息
const msg = isVue
? `Install @Vitejs/plugin-vue to handle .vue files.`
: maybeJSX
? `If you are using JSX, make sure to name the file with the .jsx or .tsx extension.`
: `You may need to install appropriate plugins to handle the ${path.extname(
importer
)} file format.`
this.error(
`Failed to parse source for import analysis because the content ` +
`contains invalid JS syntax. ` +
msg,
e.idx
)
}
// 將代碼字符串取出
let s: MagicString | undefined
const str = () => s || (s = new MagicString(source))
// 解析 env、glob 等並處理
// 轉換 cjs 成 esm
}
}
}
複製代碼
拿Vue的NPM包舉例經優化器處理後的路徑以下:
// before
- import { createApp } from 'vue'
+ import { createApp } from '/node_modules/.Vite/vue.runtime.esm-bundler.js?v=d17c1aa4'
import App from '/src/App.vue'
createApp(App).mount('#app')
複製代碼
截圖中的/src/App.vue路徑通過Vite處理髮生了什麼?
首先須要引用 @Vitejs/plugin-vue 來處理,內部使用Vue官方的編譯器@vue/compiler-sfc,plugin處理邏輯同rollup的plugin,Vite在Rollup的插件機制上進行了擴展。
詳細可參考:Vitejs.dev/guide/api-p…,這裏不作展開。
編譯後的App.vue文件以下:
import { createHotContext as __Vite__createHotContext } from "/@Vite/client";
import.meta.hot = __Vite__createHotContext("/src/App.vue");
import HelloWorld from '/src/components/HelloWorld.vue'
const _sfc_main = {
expose: [],
setup(__props) {
return { HelloWorld }
}
}
import {
createVNode as _createVNode,
Fragment as _Fragment,
openBlock as _openBlock,
createBlock as _createBlock
} from "/node_modules/.Vite/vue.runtime.esm-bundler.js?v=d17c1aa4"
const _hoisted_1 = /*#__PURE__*/_createVNode("img", {
alt: "Vue logo",
src: "/src/assets/logo.png"
}, null, -1 /* HOISTED */)
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
return (_openBlock(), _createBlock(_Fragment, null, [
_hoisted_1,
_createVNode($setup["HelloWorld"], { msg: "Hello Vue 3 + Vite" })
], 64 /* STABLE_FRAGMENT */))
}
import "/src/App.vue?vue&type=style&index=0&lang.css"
_sfc_main.render = _sfc_render
_sfc_main.__file = "/Users/orange/build/Vite-vue3/src/App.vue"
export default _sfc_main
_sfc_main.__hmrId = "7ba5bd90"
typeof __VUE_HMR_RUNTIME__ !== 'undefined' && __VUE_HMR_RUNTIME__.createRecord(_sfc_main.__hmrId, _sfc_main)
import.meta.hot.accept(({ default: updated, _rerender_only }) => {
if (_rerender_only) {
__VUE_HMR_RUNTIME__.rerender(updated.__hmrId, updated.render)
} else {
__VUE_HMR_RUNTIME__.reload(updated.__hmrId, updated)
}
})
複製代碼
能夠發現,Vite自己並不會遞歸編譯,這個過程交給了瀏覽器,當瀏覽器運行到import HelloWorld from '/src/components/HelloWorld.vue' 時,又會發起新的請求,經過中間件來編譯 vue,以此類推,爲了證實咱們的結論,能夠看到 HelloWorld.vue 的請求信息:
通過分析源碼後,能判定的是,Snowpack與Vite在啓動服務的時間會遠超Webpack,但複雜工程的首次編譯到徹底可運行的時間須要進一步測試,不一樣場景下可能產生大相徑庭的結果。
Vite@2.0.3 | Webpack@5.24.2 | Snowpack@3.0.13 | |
---|---|---|---|
支持Vue2 | 非官方支持: github.com/underfin/vi… | 支持:vue-loader@^15.0.0 | 非官方支持: www.npmjs.com/package/@le… |
支持Vue3 | 支持 | 支持:vue-loader@^16.0.0(github.com/Jamie-Yang/…) | 支持: www.npmjs.com/package/@Sn… |
支持Typescript | 支持:ESbuild (默認無類型檢查) | 支持:ts-loader | 支持: github.com/Snowpackjs/… |
支持CSS預處理器 | 支持: vitejs.dev/guide/featu… | 支持:vue-loader.vuejs.org/guide/pre-p… | 部分支持:官方僅提供了Sass和Postcss,且存在未解決BUG |
支持CSS Modules | 支持: vitejs.dev/guide/featu… | 支持:vue-loader.vuejs.org/guide/css-m… | 支持 |
支持靜態文件 | 支持 | 支持 | 支持 |
開發環境 | no-bundle native ESM(CJS → ESM) | bundle(CJS/UMD/ESM) | no-bundle native ESM(CJS → ESM) |
HMR | 支持 | 支持 | 支持 |
生產環境 | Rollup | Webpack | Webpack, Rollup, or even ESbuild |
Node API 調用能力 | 支持 | 支持 | 支持 |
下面一組測試的代碼徹底相同,都是Hellow World工程,沒有任何複雜邏輯,Webpack與Snowpack分別引入了對應的Vue plugin,Vite無需任何插件。
工程目錄:
控制檯輸出:
工程目錄:
控制檯輸出:
工程目錄:
控制檯輸出:
測試案例:已存在的複雜邏輯vue工程
通過簡單的測試及調研結果,首先從生態和性能上排除了Snowpack,下面將測試Webpack5與Vite2。
遷移Vite2遇到的問題:
1.不支持省略.vue後綴,由於此路由機制與編譯處理強關聯;
2.不支持.vue後綴文件內寫jsx,若寫jsx,須要改文件後綴爲.jsx;
3.不建議import { ... } from "dayjs"與import duration from 'dayjs/plugin/duration'同時使用,從源碼會發如今optimizeDeps階段已經把ESM編譯到了緩存文件夾,若同時使用會報錯:
4.當optimizeDeps忽略後文件路徑錯誤,node_modules/dayjs/dayjs.main.js?version=xxxxx,此處不該該在query中添加version;
5.組件庫中window.$方法找不到,不能強依賴關聯順序,跟請求返回順序有關;
6.當dependencies首次未被寫入緩存時,補充寫入會報錯,須要二次重啓;
7.在依賴關係複雜場景,Vue被屢次cache,會出現ESM二次封裝的狀況,也就是ESM裏面嵌套ESM的狀況;
種種緣由,調試到這裏終結了,結論就是Vite2目前處於初期,尚不穩定,處理深層次依賴就目前的moduleGraph機制還有所欠缺,有待完善。
效果和咱們以前測試相同代碼在Webpack4下50+秒相比提高明顯,實際場景可能存在偏差,但WebpackConfig配置細節基本一致。
不知你們是否有遇到這個問題:
<--- Last few GCs --->
[59757:0x103000000] 32063 ms: Mark-sweep 1393.5 (1477.7) -> 1393.5 (1477.7) MB, 109.0 / 0.0 ms allocation failure GC in old space requested
<--- JS stacktrace --->
==== JS stack trace =========================================
Security context: 0x24d9482a5ec1 <JSObject>
...
複製代碼
或者在 92% 的進度裏卡好久:
Webpack chunk asset optimization (92%) TerserPlugin
複製代碼
隨着產物愈來愈大,編譯上線和CI的時間都愈來愈長,而其中1/3及更多的時間則是在作壓縮的部分。OOM的問題也一般來源於壓縮。
如何解決壓縮慢和佔內存的問題,一直是逃避不開的話題,Vite採用了ESbuild,接下來分析一下ESbuild。
下面是官方的構建時間對比圖,並無說明場景,文件大小等,因此不具有實際參考價值。
之因此快,其中最主要的應該是用go寫,而後編譯爲Native代碼。而後npm安裝時動態去下對應平臺的二進制包,支持Mac、Linux和Windows,好比esbuild-darwin-64。
相同思路的還有es-module-lexer、swc等,都是用編譯成Native代碼的方式進行提速,用來彌補Node在密集CPU計算場景的短板。
ESbuild有兩個功能,bundler和minifier。bundler的功能和babel以及Webpack相比差別很大,直接使用對現有業務的風險較大;而minifier能夠嘗試,在Webpack和babel產物的基礎上作一次生產環境壓縮,能夠節省terser plugin的壓縮時間。
同時針對Webpack提供了esbuild-webpack-plugin,能夠在Webpack內直接使用ESbuild。
缺點:
優勢:
缺點:
優勢:
缺點:
回到咱們文章開始的問題,通過上文的遷移測試環節,咱們須要調整大量代碼進行Vite遷移適配,因爲原有Vue工程未遵循Vite的開發範式,遷移過程比較坎坷,新工程只要遵循Vite官方的開發文檔,會規避上文提到的大部分問題。
因此已有Webpack工程遷移成本仍是較大的,另外一方面也是須要重點關注的就是本地開發與生產環境的差別問題,若是本機開發環境採用No-Bundle機制,而生產發佈環境採用Bundle機制,這種不一致性會給測試和排查問題帶來困擾和風險,在生態還沒有齊備以前,建議審慎嘗試。