修复使用独立的样式文件时热更新失效的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,115 +153,121 @@ 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( /import ([\w\W]*?) from (["'])(.*?)\2/g,
/import ([\w\W]*?) from (["'])(.*?)\2/g, function (m, alias, q, name) {
function (m, alias, q, name) {
if (name.startsWith('@/')) {
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
if (!imports[name]) {
if (name.startsWith('./') || name.startsWith('../')) {
if (IS_ENTRY) {
if (IS_MPA) {
name = `pages/${currentPage}/` + name
}
name = urlJoin(DEPLOY_PATH, ASSETS_DIR, name)
}
} else if (
name.startsWith('/') &&
!name.startsWith('//') &&
!name.startsWith(urlJoin(DEPLOY_PATH, ASSETS_DIR))
) {
name = name.replace(/^\//, urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
if (!name.endsWith('.js') && !name.endsWith('.vue')) {
if (name.includes('components')) {
name += '.vue'
} else {
name += '.js'
}
}
}
if (isBuild) {
name = name.replace(/\.vue$/, '.js')
}
return `import ${alias} from '${name}'`
}
)
.replace(/import\((['"])(.*?)\1\)/g, function (m, q, name) {
if (isBuild) {
name = name.replace(/\.vue$/, '.js')
}
if (name.startsWith('@/')) { if (name.startsWith('@/')) {
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR)) name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
} }
return `import('${name}')`
})
.replace(/import (["'])(.*?)\1/g, function (m, q, name) {
if (name.endsWith('.css') || name.endsWith('.scss')) {
if (name.startsWith('@/')) {
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
if (isBuild) { if (!imports[name]) {
name = name.replace(/\.scss/, '.css') if (name.startsWith('./') || name.startsWith('../')) {
} if (IS_ENTRY) {
// 修正那反人类的windows路径 if (IS_MPA) {
let _name = name.replace(/\\/g, '/') name = `pages/${currentPage}/` + name
let tmp = `style_${uuid()}`
if (LEGACY_MODE) {
fixedStyle += `${tmp}.then(r => {
let stylesheet = new CSSStyleSheet()
stylesheet.path = '${_name}'
stylesheet.replaceSync(r)
__sheets__.push(stylesheet)
})
`
return `${tmp} = window.fetch('${name}').then(r => r.text())`
} else {
fixedStyle += `${tmp}.path = '${_name}'\n__sheets__.push(${tmp})\n`
return `import ${tmp} from '${name}' assert { type: 'css' }`
}
} else {
if (name.startsWith('@/')) {
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
//
if (!imports[name]) {
if (name.startsWith('./') || name.startsWith('../')) {
if (IS_ENTRY) {
if (IS_MPA) {
name = `${currentPage}/` + name
}
name = urlJoin(DEPLOY_PATH, ASSETS_DIR, name)
} }
} else if ( name = urlJoin(DEPLOY_PATH, ASSETS_DIR, name)
name.startsWith('/') &&
!name.startsWith('//') &&
!name.startsWith(urlJoin(DEPLOY_PATH, ASSETS_DIR))
) {
name = name.replace(/^\//, urlJoin(DEPLOY_PATH, ASSETS_DIR))
} }
} else if (
name.startsWith('/') &&
!name.startsWith('//') &&
!name.startsWith(urlJoin(DEPLOY_PATH, ASSETS_DIR))
) {
name = name.replace(/^\//, urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
if (!name.endsWith('.js') && !name.endsWith('.vue')) { if (!name.endsWith('.js') && !name.endsWith('.vue')) {
if (name.includes('components')) {
name += '.vue'
} else {
name += '.js' name += '.js'
} }
} }
return `import '${name}'`
} }
}) + if (isBuild) {
fixedStyle + name = name.replace(/\.vue$/, '.js')
(IS_ENTRY ? '\ndocument.adoptedStyleSheets = __sheets__' : '') }
) return `import ${alias} from '${name}'`
}
)
.replace(/import\((['"])(.*?)\1\)/g, function (m, q, name) {
if (isBuild) {
name = name.replace(/\.vue$/, '.js')
}
if (name.startsWith('@/')) {
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
return `import('${name}')`
})
.replace(/import (["'])(.*?)\1/g, function (m, q, name) {
if (name.endsWith('.css') || name.endsWith('.scss')) {
if (name.startsWith('@/')) {
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
if (isBuild) {
name = name.replace(/\.scss/, '.css')
}
// 修正那反人类的windows路径
let _name = name.replace(/\\/g, '/').replace('@/', '')
let tmp = `style_${uuid()}`
if (LEGACY_MODE) {
fixedStyle += `${tmp}.then(r => {
let stylesheet = document.createElement('style')
stylesheet.setAttribute('name', '${_name}')
stylesheet.textContent = r
document.head.appendChild(stylesheet)
})
`
return `const ${tmp} = window.fetch('${name}').then(r => r.text())`
} else {
fixedStyle += `${tmp}.path = '${_name}'\n__sheets__.push(${tmp})\n`
return `import ${tmp} from '${name}' assert { type: 'css' }`
}
} else {
if (name.startsWith('@/')) {
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
//
if (!imports[name]) {
if (name.startsWith('./') || name.startsWith('../')) {
if (IS_ENTRY) {
if (IS_MPA) {
name = `${currentPage}/` + name
}
name = urlJoin(DEPLOY_PATH, ASSETS_DIR, name)
}
} else if (
name.startsWith('/') &&
!name.startsWith('//') &&
!name.startsWith(urlJoin(DEPLOY_PATH, ASSETS_DIR))
) {
name = name.replace(/^\//, urlJoin(DEPLOY_PATH, ASSETS_DIR))
}
if (!name.endsWith('.js') && !name.endsWith('.vue')) {
name += '.js'
}
}
return `import '${name}'`
}
})
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,22 +364,34 @@ 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 = new CSSStyleSheet() let stylesheet = document.createElement('style')
stylesheet.path = '${filename}' stylesheet.setAttribute('name', '${filename}')
stylesheet.replaceSync(\`${scss}\`) stylesheet.textContent = \`${scss}\`
__sheets__.push(stylesheet) document.head.appendChild(stylesheet)
} }
document.adoptedStyleSheets = __sheets__
` `
} else {
output += `
{
let stylesheet = new CSSStyleSheet()
stylesheet.path = '${filename}'
stylesheet.replaceSync(\`${scss}\`)
__sheets__.push(stylesheet)
}
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,47 +16,63 @@ 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'
var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-vue-live\`)
ws.addEventListener('open', function (r) { export function createHmrScript(legacy) {
if(vue_live_hmr.closed){ return `
delete vue_live_hmr.closed !(function vue_live_hmr(){
location.reload() var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-vue-live\`)
}
console.log('vue-live hmr ready...')
})
ws.addEventListener('close', function(){ ws.addEventListener('open', function (r) {
vue_live_hmr.closed = true if(vue_live_hmr.closed){
setTimeout(vue_live_hmr, 2000) delete vue_live_hmr.closed
})
ws.addEventListener('message', function (ev) {
var { action, data } = JSON.parse(ev.data)
switch (action) {
case 'reload':
location.reload() location.reload()
break }
console.log('vue-live hmr ready...')
})
case 'render': ws.addEventListener('close', function(){
{ vue_live_hmr.closed = true
let tmp = [...document.adoptedStyleSheets] setTimeout(vue_live_hmr, 2000)
for (let i = -1, it; (it = tmp[++i]); ) { })
if (it.path === data.path) {
let stylesheet = new CSSStyleSheet() ws.addEventListener('message', function (ev) {
stylesheet.path = data.path var { action, data } = JSON.parse(ev.data)
stylesheet.replaceSync(data.content)
tmp[i] = stylesheet switch (action) {
document.adoptedStyleSheets = tmp case 'reload':
break location.reload()
break
case 'render':
{
${
legacy
? `
let stylesheet = document.head.children.namedItem(data.path)
if (stylesheet) {
stylesheet.textContent = data.content
}
`
: `
let tmp = [...document.adoptedStyleSheets]
for (let i = -1, it; (it = tmp[++i]); ) {
if (it.path === data.path) {
let stylesheet = new CSSStyleSheet()
stylesheet.path = data.path
stylesheet.replaceSync(data.content)
tmp[i] = stylesheet
document.adoptedStyleSheets = tmp
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"
}, },