/** * {} * @author yutent * @date 2022/09/06 14:43:01 */ import fs from 'iofs' import scss from '@bytedo/sass' import { createHash } from 'crypto' import Es from 'esbuild' import { join } from 'path' import { compile } from '@vue/compiler-dom' import { red, cyan, blue } from 'kolorist' import { JS_EXP, STYLE_EXP, HTML_EXP, CSS_SHEET_EXP, HMR_SCRIPT, V_DEEP, PERCENT_EXP } from './constants.js' const OPTIONS = { indentType: 'space', indentWidth: 2 } // 修正路径合并 避免在windows下被转义 function urlJoin(...args) { return join(...args).replace(/\\/g, '/') } function md5(str = '') { let sum = createHash('md5') sum.update(str, 'utf8') return sum.digest('hex').slice(0, 8) } function parseVDeep(curr, val, scoped) { let res = V_DEEP.exec(curr) if (res) { scoped && (val = val.replace(/\[data\-[^\]]+\]/g, '')) return `${res[1] + res[2]} ${val}` } else { return `${curr} ${val}` } } function scopeCss(css = '', hash) { return css.replace(CSS_SHEET_EXP, (m, selector) => { if (!selector.startsWith('@')) { selector = selector.split(',') selector = selector .map(s => { // 针对 @keyframe的处理 if (s === 'from' || s === 'to' || PERCENT_EXP.test(s)) { return s } let tmp = s.split(' ') let output = '' let last let scoped = false while ((last = tmp.pop())) { if (scoped) { if (last.startsWith(':')) { output = parseVDeep(last, output, true) } else { output = `${last} ${output}` } } else { if (last.includes(':')) { if (last.startsWith(':')) { output = parseVDeep(last, output) } else { scoped = true last = last.replace(':', `[data-${hash}]:`) output = `${last} ${output}` } } else { scoped = true output = `${last}[data-${hash}] ${output}` } } } return output }) .join(', ') } return selector + '{' }) } /** * 编译scss为css * @param file 文件路径或scss代码 * @param mini 是否压缩 */ export function compileScss(file, mini = true) { let style = mini ? 'compressed' : 'expanded' try { if (fs.isfile(file)) { return scss.compile(file, { style, ...OPTIONS }).css.trim() } else { return scss.compileString(file, { style, ...OPTIONS }).css.trim() } } catch (err) { console.log('compile scss: ', file) console.error(err) } } /** * 解析js * 主要是处理js的依赖引用 * @param code js代码 */ export function parseJs( code = '', imports, { IS_MPA, currentPage, IS_ENTRY, DEPLOY_PATH } = {}, isBuild, filename ) { let fixedStyle = '\n\n' let ASSETS_DIR = '/@/' if (isBuild) { ASSETS_DIR = '/assets/' // + (IS_MPA ? 'pages/' : '') } try { code = Es.transformSync(code).code || '' } catch (e) { let err = e.errors.pop() console.log('%s: %s', red('Uncaught SyntaxError'), err.text) console.log( ' @ line %d: %s', err.location.line, cyan(err.location.lineText) ) console.log( ' @ %s:%d:%d', blue(filename), err.location.line, err.location.column ) } return ( code .replace(/\r\n/g, '\n') .replace( /import ([\w\W]*?) from (["'])(.*?)\2/g, 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('@/')) { 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('@/', '/') } if (isBuild) { name = name.replace(/\.scss/, '.css') } let tmp = `style${Date.now()}` fixedStyle += ` let __sheets__ = [...document.adoptedStyleSheets] __sheets__.push(${tmp}) document.adoptedStyleSheets = __sheets__ ` // 修正那反人类的windows路径 return `import ${tmp} from '${name}' assert { type: 'css' }\n${tmp}.path = '${name.replace( /\\/g, '/' )}'` } 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}'` } }) + fixedStyle ) } /** * 将vue转为js * @param file 文件路径 * @return 返回转换后的js代码 */ export function compileVue(file, imports, options = {}, isBuild) { let filename = file.slice(options.SOURCE_DIR.length).replace(/\\/g, '/') let code = (fs.cat(file) || '').toString().replace(/\r\n/g, '\n') let CACHE = options.CACHE || {} let output = '', scoped = false let js = code.match(JS_EXP) let scss = [...code.matchAll(STYLE_EXP)] let html = code.match(HTML_EXP) || ['', ''] let hash = md5(file) let scopeId = 'data-' + hash scss = scss .map(it => { let css if (it.length > 2) { css = compileScss(it[2]) if (it[1].includes('scoped')) { scoped = true css = scopeCss(css, hash) } } else { css = compileScss(it[1]) } return css }) .join(' ') js = js ? js[1] : '' html = compile(html[1], { mode: 'module', prefixIdentifiers: true, hoistStatic: true, cacheHandlers: true, scopeId: scoped ? scopeId : void 0, sourceMap: false, isCustomElement: tag => tag.startsWith('wc-') }).code.replace('export function render', 'function render') output += html + '\n\n' if (CACHE[file]) { CACHE[file] = { changed: CACHE[file].js !== js || CACHE[file].html !== html, js, html } } else { CACHE[file] = { changed: false, js, html } } output += parseJs(js, imports, options, isBuild, file).replace( 'export default {', 'const __sfc__ = {\n render,\n' ) if (scss) { CACHE[file].css = scss // 修正那反人类的windows路径 output += ` let stylesheet = new CSSStyleSheet() let __sheets__ = [...document.adoptedStyleSheets] stylesheet.path = '${filename}' stylesheet.replaceSync(\`${scss}\`) __sheets__.push(stylesheet) document.adoptedStyleSheets = __sheets__ ` } if (scoped) { output += `__sfc__.__scopeId = '${scopeId}'\n` } output += `__sfc__.__file = '${filename}'\nexport default __sfc__` return output } /** * 解析模板html */ export function parseHtml(html, { page, imports, entry }, isBuild = false) { return html .replace(/\r\n/g, '\n') .replace( '', ` \n${ isBuild ? '' : ` ` }` ) .replace('{{title}}', page.title || '') .replace('{{keywords}}', page.keywords || '') .replace('{{description}}', page.description || '') .replace('{{importmap}}', JSON.stringify({ imports })) .replace( '', `` ) }