Commit ad3cebdd authored by Evan You's avatar Evan You

refactor: improve hmr code generation

parent f418bd95
const hotReloadAPIPath = require.resolve('vue-hot-reload-api')
module.exports = function genHotReloadCode (id, functional) {
exports.genHotReloadCode = (id, functional) => {
// TODO handle CSSModules and style injection disposal
return wrap(`
if (!module.hot.data) {
api.createRecord('${id}', component.options)
} else {
api.${functional ? `rerender` : `reload`}('${id}', component.options)
}
`)
}
exports.genTemplateHotReloadCode = id => {
return wrap(`
if (module.hot.data) {
require('${hotReloadAPIPath}').rerender('${id}', {
render: render,
staticRenderFns: staticRenderFns
})
}
`)
}
function wrap (inner) {
return `
/* hot reload */
if (module.hot) {
......@@ -9,11 +30,7 @@ if (module.hot) {
api.install(require('vue'))
if (api.compatible) {
module.hot.accept()
if (!module.hot.data) {
api.createRecord('${id}', component.options)
} else {
api.${functional ? `rerender` : `reload`}('${id}', component.options)
}
${inner.trim()}
}
}
`.trim()
......
......@@ -5,7 +5,7 @@ const qs = require('querystring')
const loaderUtils = require('loader-utils')
const selectBlock = require('./selector')
const plugin = require('./plugin')
const genHotReloadCode = require('./hotReload')
const { genHotReloadCode } = require('./hotReload')
const componentNormalizerPath = require.resolve('./runtime/componentNormalizer')
module.exports = function (source) {
......
......@@ -6,7 +6,7 @@ const compiler = require('vue-template-compiler')
const transpile = require('vue-template-es2015-compiler')
const transformAssetUrl = require('./modules/assetUrl')
const transformSrcset = require('./modules/srcset')
const hotReloadAPIPath = require.resolve('vue-hot-reload-api')
const { genTemplateHotReloadCode } = require('../hotReload')
// Loader that compiles raw template into JavaScript functions.
// This is injected by the global pitcher (../pitch) for template
......@@ -141,16 +141,10 @@ function actuallyCompile (sourceTemplate, options, loaderContext, query) {
}
code += `export { render, staticRenderFns }`
}
// hot-reload
if (needsHotReload) {
code +=
'\nif (module.hot) {\n' +
' module.hot.accept()\n' +
' if (module.hot.data) {\n' +
' require("' + hotReloadAPIPath + '")' +
' .rerender("' + options.id + '", { render: render, staticRenderFns: staticRenderFns })\n' +
' }\n' +
'}'
code += genTemplateHotReloadCode(id)
}
return code
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment