前言
熱替換(Hot Module Replacement)或熱重載(Hot Reload)是指在不停機狀态下,實時更新,在前端利于來說,在各大架構中及庫中都有展現,比如NG從5開始就提供了熱更新,RN也有對應的熱更新技術,其實用戶端技術很早就已經有這方面的探索,本文主要針對Vue腳手架的熱更新,其實主要是 Vue-hot-reload-api 這個包的應用,對webpack的HMR比較感興趣的同學推薦冉四夕大佬的這篇文章 Webpack HMR 原了解析 ,多說一句,個人認為Webpack可能是最好的node.js的工具庫應用。
目錄
- vue-cli腳手架結構
- vue-hot-reload-api源碼分析
- vue-cli熱更新 vs webpack熱更新
探索案例
vue-cli腳手架結構
[目錄結構]
- binvuevue-buildvue-initvue-list
- libask.js (自定義工具-用于詢問開發者)check-version.jseval.jsfilter.js (自定義工具-用于檔案過濾)generate.jsgit-user.jslocal-path.jslogger.js (自定義工具-用于日志列印)options.js (自定義工具-用于擷取模闆配置)warnings.js
[目錄描述] vue-cli2的目錄結構就是bin下的相關子產品,vue-cli最新版将各個子產品又單獨抽成了獨立的檔案,并引入了插件機pwa等相關周邊的工具引入,使得腳手架更加豐富(見下圖),但主要建構流程并未改變,主要就是在bin目錄下去配置相關的指令,主要用到了commander處理指令行的包,對于想獨立開發個人腳手架的同學可以參考這兩篇文章 教你從零開始搭建一款前端腳手架工具 , 走進Vue-cli源碼,自己動手搭建前端腳手架工具
vue-hot-reload-api源碼分析
let Vue // late bindlet versionconst map = Object.create(null)if (typeof window !== 'undefined') { window.__VUE_HOT_MAP__ = map}let installed = falselet isBrowserify = falselet initHookName = 'beforeCreate'exports.install = (vue, browserify) => { if (installed) return installed = true Vue = vue.__esModule ? vue.default : vue version = Vue.version.split('.').map(Number) isBrowserify = browserify // compat with < 2.0.0-alpha.7 if (Vue.config._lifecycleHooks.indexOf('init') > -1) { initHookName = 'init' } exports.compatible = version[0] >= 2 if (!exports.compatible) { console.warn( '[HMR] You are using a version of vue-hot-reload-api that is ' + 'only compatible with Vue.js core ^2.0.0.' ) return }}/** * Create a record for a hot module, which keeps track of its constructor * and instances * * @param {String} id * @param {Object} options */exports.createRecord = (id, options) => { if(map[id]) return let Ctor = null if (typeof options === 'function') { Ctor = options options = Ctor.options } makeOptionsHot(id, options) map[id] = { Ctor, options, instances: [] }}/** * Check if module is recorded * * @param {String} id */exports.isRecorded = (id) => { return typeof map[id] !== 'undefined'}/** * Make a Component options object hot. * * @param {String} id * @param {Object} options */function makeOptionsHot(id, options) { if (options.functional) { const render = options.render options.render = (h, ctx) => { const instances = map[id].instances if (ctx && instances.indexOf(ctx.parent) < 0) { instances.push(ctx.parent) } return render(h, ctx) } } else { injectHook(options, initHookName, function() { const record = map[id] if (!record.Ctor) { record.Ctor = this.constructor } record.instances.push(this) }) injectHook(options, 'beforeDestroy', function() { const instances = map[id].instances instances.splice(instances.indexOf(this), 1) }) }}/** * Inject a hook to a hot reloadable component so that * we can keep track of it. * * @param {Object} options * @param {String} name * @param {Function} hook */function injectHook(options, name, hook) { const existing = options[name] options[name] = existing ? Array.isArray(existing) ? existing.concat(hook) : [existing, hook] : [hook]}function tryWrap(fn) { return (id, arg) => { try { fn(id, arg) } catch (e) { console.error(e) console.warn( 'Something went wrong during Vue component hot-reload. Full reload required.' ) } }}function updateOptions (oldOptions, newOptions) { for (const key in oldOptions) { if (!(key in newOptions)) { delete oldOptions[key] } } for (const key in newOptions) { oldOptions[key] = newOptions[key] }}exports.rerender = tryWrap((id, options) => { const record = map[id] if (!options) { record.instances.slice().forEach(instance => { instance.$forceUpdate() }) return } if (typeof options === 'function') { options = options.options } if (record.Ctor) { record.Ctor.options.render = options.render record.Ctor.options.staticRenderFns = options.staticRenderFns record.instances.slice().forEach(instance => { instance.$options.render = options.render instance.$options.staticRenderFns = options.staticRenderFns // reset static trees // pre 2.5, all static trees are cached together on the instance if (instance._staticTrees) { instance._staticTrees = [] } // 2.5.0 if (Array.isArray(record.Ctor.options.cached)) { record.Ctor.options.cached = [] } // 2.5.3 if (Array.isArray(instance.$options.cached)) { instance.$options.cached = [] } // post 2.5.4: v-once trees are cached on instance._staticTrees. // Pure static trees are cached on the staticRenderFns array // (both already reset above) // 2.6: temporarily mark rendered scoped slots as unstable so that // child components can be forced to update const restore = patchScopedSlots(instance) instance.$forceUpdate() instance.$nextTick(restore) }) } else { // functional or no instance created yet record.options.render = options.render record.options.staticRenderFns = options.staticRenderFns // handle functional component re-render if (record.options.functional) { // rerender with full options if (Object.keys(options).length > 2) { updateOptions(record.options, options) } else { // template-only rerender. // need to inject the style injection code for CSS modules // to work properly. const injectStyles = record.options._injectStyles if (injectStyles) { const render = options.render record.options.render = (h, ctx) => { injectStyles.call(ctx) return render(h, ctx) } } } record.options._Ctor = null // 2.5.3 if (Array.isArray(record.options.cached)) { record.options.cached = [] } record.instances.slice().forEach(instance => { instance.$forceUpdate() }) } }})exports.reload = tryWrap((id, options) => { const record = map[id] if (options) { if (typeof options === 'function') { options = options.options } makeOptionsHot(id, options) if (record.Ctor) { if (version[1] < 2) { // preserve pre 2.2 behavior for global mixin handling record.Ctor.extendOptions = options } const newCtor = record.Ctor.super.extend(options) // prevent record.options._Ctor from being overwritten accidentally newCtor.options._Ctor = record.options._Ctor record.Ctor.options = newCtor.options record.Ctor.cid = newCtor.cid record.Ctor.prototype = newCtor.prototype if (newCtor.release) { // temporary global mixin strategy used in < 2.0.0-alpha.6 newCtor.release() } } else { updateOptions(record.options, options) } } record.instances.slice().forEach(instance => { if (instance.$vnode && instance.$vnode.context) { instance.$vnode.context.$forceUpdate() } else { console.warn( 'Root or manually mounted instance modified. Full reload required.' ) } })})// 2.6 optimizes template-compiled scoped slots and skips updates if child// only uses scoped slots. We need to patch the scoped slots resolving helper// to temporarily mark all scoped slots as unstable in order to force child// updates.function patchScopedSlots (instance) { if (!instance._u) return // https://github.com/vuejs/vue/blob/dev/src/core/instance/render-helpers/resolve-scoped-slots.js const original = instance._u instance._u = slots => { try { // 2.6.4 ~ 2.6.6 return original(slots, true) } catch (e) { // 2.5 / >= 2.6.7 return original(slots, null, true) } } return () => { instance._u = original }}
整體來說vue-hot-reload-api的思路還是很清晰的,主要就是通過維護一個map映射對象,通過對component名稱進行對比,這裡主要維護了一個Ctor對象,通過hook的方法在vue的生命周期中進行watch監聽,然後更新後進行rerender以及reload
vue-cli熱更新 vs webpack熱更新
vue-cli熱重載和webpack熱更新不同的差別主要在于:
1、依賴:vue-cli熱重載是強依賴于vue架構的,利用的是vue自身的Watcher監聽,通過vue的生命周期函數進行名稱子產品的變更的替換;而webpack則是不依賴于架構,利用的是sock.js進行浏覽器端和本地服務端的通信,本地的watch監聽則是webpack和webpack-dev-server對子產品名稱的監聽,替換過程用的則是jsonp/ajax的傳遞;
2、粒度:vue-cli熱重載主要是利用的vue自身架構的component粒度的更新,雖然vue-cli也用到了webpack,其主要是打包和本地服務的用途;而webpack的熱更新則是子產品粒度的,其主要是子產品名稱的變化定位去更新,由于其自身是一個工具應用,因而不能确定是哪個架構具體的生命周期,因而其監聽内容變化就必須通過自身去實作一套類似的周期變化監聽;
3、定位:vue-cli定位就是vue架構的指令行工具,因而其并不需要特别大的考慮到雙方通信以及自定義擴充性等;而webpack本身定位在一個打包工具,或者說其實基于node.js運作時環境的應用,因而也就決定了它必須有更友善、更個性化的擴充和抽象性
總結
在簡單小型項目中,直接使用vue-cli腳手架進行vue相關應用的開發即可,但在開發過程中遇到了相關不太明白的渲染問題,也需要弄懂弄通其深層原理(ps:這次就是基于一個生命周期渲染的問題引發的探究,大概描述下就是頁面渲染在f5重新整理和vue-cli熱重載下會出現不同的資料形式,然後便研究了下vue-cli的源碼);而對于大型定制化項目,或者說需要對前端項目組提供一整套的前端工程化工具模闆的開發,webpack還是首當其沖的選擇,畢竟webpack還是在node.js運作時下有壓倒性優勢的工具應用。