修复使用独立的样式文件时热更新失效的bug; 增加legacy模式的支持

pull/1/head 1.1.0
yutent 2023-05-18 12:04:24 +08:00
parent 7ed5f81da2
commit 27afea8649
5 changed files with 202 additions and 160 deletions

View File

@ -21,9 +21,10 @@ import {
STYLE_EXP, STYLE_EXP,
HTML_EXP, HTML_EXP,
CSS_SHEET_EXP, CSS_SHEET_EXP,
HMR_SCRIPT,
V_DEEP, V_DEEP,
PERCENT_EXP PERCENT_EXP,
SHEETS_DEF,
createHmrScript
} from './constants.js' } from './constants.js'
const OPTIONS = { const OPTIONS = {
@ -126,7 +127,7 @@ export function parseJs(
{ IS_MPA, currentPage, IS_ENTRY, DEPLOY_PATH, LEGACY_MODE } = {}, { IS_MPA, currentPage, IS_ENTRY, DEPLOY_PATH, LEGACY_MODE } = {},
filename filename
) { ) {
let fixedStyle = '\n\n' let fixedStyle = ''
let ASSETS_DIR = '/@/' let ASSETS_DIR = '/@/'
let isBuild = process.env.NODE_ENV === 'production' let isBuild = process.env.NODE_ENV === 'production'
@ -134,10 +135,6 @@ export function parseJs(
ASSETS_DIR = '/assets/' ASSETS_DIR = '/assets/'
} }
if (IS_ENTRY) {
fixedStyle += 'const __sheets__ = [...document.adoptedStyleSheets];\n'
}
try { try {
code = Es.transformSync(code).code || '' code = Es.transformSync(code).code || ''
} catch (e) { } catch (e) {
@ -156,8 +153,7 @@ export function parseJs(
) )
} }
return ( code = code
code
.replace(/\r\n/g, '\n') .replace(/\r\n/g, '\n')
.replace(/process\.env\.NODE_ENV/g, `'${process.env.NODE_ENV}'`) .replace(/process\.env\.NODE_ENV/g, `'${process.env.NODE_ENV}'`)
.replace( .replace(
@ -216,18 +212,18 @@ export function parseJs(
name = name.replace(/\.scss/, '.css') name = name.replace(/\.scss/, '.css')
} }
// 修正那反人类的windows路径 // 修正那反人类的windows路径
let _name = name.replace(/\\/g, '/') let _name = name.replace(/\\/g, '/').replace('@/', '')
let tmp = `style_${uuid()}` let tmp = `style_${uuid()}`
if (LEGACY_MODE) { if (LEGACY_MODE) {
fixedStyle += `${tmp}.then(r => { fixedStyle += `${tmp}.then(r => {
let stylesheet = new CSSStyleSheet() let stylesheet = document.createElement('style')
stylesheet.path = '${_name}' stylesheet.setAttribute('name', '${_name}')
stylesheet.replaceSync(r) stylesheet.textContent = r
__sheets__.push(stylesheet) document.head.appendChild(stylesheet)
}) })
` `
return `${tmp} = window.fetch('${name}').then(r => r.text())` return `const ${tmp} = window.fetch('${name}').then(r => r.text())`
} else { } else {
fixedStyle += `${tmp}.path = '${_name}'\n__sheets__.push(${tmp})\n` fixedStyle += `${tmp}.path = '${_name}'\n__sheets__.push(${tmp})\n`
@ -261,10 +257,17 @@ export function parseJs(
return `import '${name}'` return `import '${name}'`
} }
}) + })
fixedStyle +
(IS_ENTRY ? '\ndocument.adoptedStyleSheets = __sheets__' : '') if (fixedStyle) {
) code += '\n\n' + (LEGACY_MODE ? '' : SHEETS_DEF) + fixedStyle
if (IS_ENTRY && !LEGACY_MODE) {
code += '\ndocument.adoptedStyleSheets = __sheets__'
}
}
return code
} }
/** /**
@ -273,6 +276,7 @@ export function parseJs(
* @return <String> 返回转换后的js代码 * @return <String> 返回转换后的js代码
*/ */
export function compileVue(file, imports, options = {}) { export function compileVue(file, imports, options = {}) {
// 修正那反人类的windows路径
let filename = file.slice(options.SOURCE_DIR.length).replace(/\\/g, '/') let filename = file.slice(options.SOURCE_DIR.length).replace(/\\/g, '/')
let code = (fs.cat(file) || '').toString().replace(/\r\n/g, '\n') let code = (fs.cat(file) || '').toString().replace(/\r\n/g, '\n')
let CACHE = options.CACHE || {} let CACHE = options.CACHE || {}
@ -360,23 +364,35 @@ function render(_ctx, _cache) {
output += parseJs(js, imports, options, file).replace( output += parseJs(js, imports, options, file).replace(
'export default {', 'export default {',
`\nconst __sheets__ = [...document.adoptedStyleSheets]\n${html}\n\nconst __sfc__ = {\n render,\n` `\n${
options.LEGACY_MODE ? '' : SHEETS_DEF
}${html}\n\nconst __sfc__ = {\n render,\n`
) )
if (scss) { if (scss) {
CACHE[file].css = scss CACHE[file].css = scss
// 修正那反人类的windows路径 if (options.LEGACY_MODE) {
output += ` output += `
{ {
let stylesheet = document.createElement('style')
stylesheet.setAttribute('name', '${filename}')
stylesheet.textContent = \`${scss}\`
document.head.appendChild(stylesheet)
}
`
} else {
output += `
{
let stylesheet = new CSSStyleSheet() let stylesheet = new CSSStyleSheet()
stylesheet.path = '${filename}' stylesheet.path = '${filename}'
stylesheet.replaceSync(\`${scss}\`) stylesheet.replaceSync(\`${scss}\`)
__sheets__.push(stylesheet) __sheets__.push(stylesheet)
} }
document.adoptedStyleSheets = __sheets__ document.adoptedStyleSheets = __sheets__
` `
} }
}
if (scoped) { if (scoped) {
output += `__sfc__.__scopeId = '${scopeId}'\n` output += `__sfc__.__scopeId = '${scopeId}'\n`
} }
@ -388,14 +404,14 @@ document.adoptedStyleSheets = __sheets__
/** /**
* 解析模板html * 解析模板html
*/ */
export function parseHtml(html, { page, imports, entry }) { export function parseHtml(html, { page, imports, entry, LEGACY_MODE }) {
return html return html
.replace(/\r\n/g, '\n') .replace(/\r\n/g, '\n')
.replace( .replace(
'</head>', '</head>',
`${ `${
process.env.NODE_ENV === 'development' process.env.NODE_ENV === 'development'
? ` <script>${Es.transformSync(HMR_SCRIPT, { ? ` <script>${Es.transformSync(createHmrScript(LEGACY_MODE), {
minify: true minify: true
}).code.trim()}</script>\n` }).code.trim()}</script>\n`
: '' : ''

View File

@ -16,8 +16,12 @@ export const COMMON_HEADERS = {
'Cache-Control': 'no-store' 'Cache-Control': 'no-store'
} }
export const HMR_SCRIPT = ` export const SHEETS_DEF =
!(function vue_live_hmr(){ 'const __sheets__ = [...document.adoptedStyleSheets];\n'
export function createHmrScript(legacy) {
return `
!(function vue_live_hmr(){
var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-vue-live\`) var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-vue-live\`)
ws.addEventListener('open', function (r) { ws.addEventListener('open', function (r) {
@ -43,6 +47,15 @@ export const HMR_SCRIPT = `
case 'render': case 'render':
{ {
${
legacy
? `
let stylesheet = document.head.children.namedItem(data.path)
if (stylesheet) {
stylesheet.textContent = data.content
}
`
: `
let tmp = [...document.adoptedStyleSheets] let tmp = [...document.adoptedStyleSheets]
for (let i = -1, it; (it = tmp[++i]); ) { for (let i = -1, it; (it = tmp[++i]); ) {
if (it.path === data.path) { if (it.path === data.path) {
@ -54,9 +67,12 @@ export const HMR_SCRIPT = `
break break
} }
} }
`
}
} }
break break
} }
}) })
})() })()
` `
}

View File

@ -164,14 +164,19 @@ export default async function createServer(root = '', conf = {}) {
LEGACY_MODE LEGACY_MODE
}) })
code = parseHtml(html, { page, imports: conf.imports, entry }) code = parseHtml(html, {
page,
imports: conf.imports,
entry,
LEGACY_MODE
})
} }
break break
case 'vue': case 'vue':
{ {
let rpath = pathname.replace(/@\//, '') let rpath = pathname.replace('@/', '')
let file let file
if (IS_MPA) { if (IS_MPA) {
@ -208,9 +213,9 @@ export default async function createServer(root = '', conf = {}) {
case 'scss': case 'scss':
case 'css': case 'css':
{ {
let file = join(SOURCE_DIR, pathname.replace(/@\//, '')) let file = join(SOURCE_DIR, pathname.replace('@/', ''))
if (!fs.isfile(file)) { if (!fs.isfile(file)) {
file = join(PUBLIC_DIR, pathname.replace(/@\//, '')) file = join(PUBLIC_DIR, pathname.replace('@/', ''))
if (!fs.isfile(file)) { if (!fs.isfile(file)) {
friendlyErrors(pathname, ext) friendlyErrors(pathname, ext)
@ -232,7 +237,7 @@ export default async function createServer(root = '', conf = {}) {
case 'js': case 'js':
{ {
let rpath = pathname.replace(/@\//, '') let rpath = pathname.replace('@/', '')
let file let file
if (IS_MPA) { if (IS_MPA) {

View File

@ -60,7 +60,12 @@ export default function compile(root = '', dist = '', conf = {}) {
entry = parseJs(entry, conf.imports, { ...options, IS_ENTRY: true }) entry = parseJs(entry, conf.imports, { ...options, IS_ENTRY: true })
let code = parseHtml(template, { page, imports: conf.imports, entry }) let code = parseHtml(template, {
page,
imports: conf.imports,
entry,
LEGACY_MODE
})
fs.echo(code, join(dist, `${currentPage}.html`)) fs.echo(code, join(dist, `${currentPage}.html`))
continue continue

View File

@ -1,7 +1,7 @@
{ {
"name": "fite", "name": "fite",
"type": "module", "type": "module",
"version": "1.0.3", "version": "1.1.0",
"bin": { "bin": {
"fite": "index.js" "fite": "index.js"
}, },