Compare commits
No commits in common. "master" and "1.1.7" have entirely different histories.
21
LICENSE
21
LICENSE
|
@ -1,21 +0,0 @@
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2018
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
14
index.js
14
index.js
|
@ -19,12 +19,13 @@ const IS_WINDOWS = process.platform === 'win32'
|
||||||
const CONFIG_FILE = normalize(join(WORK_SPACE, 'fite.config.js'))
|
const CONFIG_FILE = normalize(join(WORK_SPACE, 'fite.config.js'))
|
||||||
const PROTOCOL = IS_WINDOWS ? 'file://' : ''
|
const PROTOCOL = IS_WINDOWS ? 'file://' : ''
|
||||||
const NODE_VERSION = process.versions.node.split('.').map(n => +n)
|
const NODE_VERSION = process.versions.node.split('.').map(n => +n)
|
||||||
const ABS_CONFIG_FILEPATH = PROTOCOL + CONFIG_FILE
|
|
||||||
|
|
||||||
let args = process.argv.slice(2)
|
let args = process.argv.slice(2)
|
||||||
let mode = args.shift() || 'prod'
|
let mode = args.shift() || 'prod'
|
||||||
let clean = !args.includes('--no-clean') //
|
let clean, verbose
|
||||||
let verbose = args.includes('--verbose') //
|
args = args.join(' ')
|
||||||
|
clean = args.includes('--no-clean') //
|
||||||
|
verbose = args.includes('--verbose') //
|
||||||
|
|
||||||
if (NODE_VERSION[0] < 16 || (NODE_VERSION[0] === 16 && NODE_VERSION[1] < 6)) {
|
if (NODE_VERSION[0] < 16 || (NODE_VERSION[0] === 16 && NODE_VERSION[1] < 6)) {
|
||||||
console.log(red('Error: 你当前的环境不满足 fite 构建工具的要求'))
|
console.log(red('Error: 你当前的环境不满足 fite 构建工具的要求'))
|
||||||
|
@ -41,9 +42,8 @@ switch (mode) {
|
||||||
case 'dev':
|
case 'dev':
|
||||||
process.env.NODE_ENV = 'development'
|
process.env.NODE_ENV = 'development'
|
||||||
|
|
||||||
import(ABS_CONFIG_FILEPATH)
|
import(PROTOCOL + CONFIG_FILE)
|
||||||
.then(function (conf) {
|
.then(function (conf) {
|
||||||
conf.default.ABS_CONFIG_FILEPATH = ABS_CONFIG_FILEPATH
|
|
||||||
createServer(WORK_SPACE, conf.default)
|
createServer(WORK_SPACE, conf.default)
|
||||||
})
|
})
|
||||||
.catch(err => {
|
.catch(err => {
|
||||||
|
@ -54,14 +54,12 @@ switch (mode) {
|
||||||
case 'build':
|
case 'build':
|
||||||
process.env.NODE_ENV = 'production'
|
process.env.NODE_ENV = 'production'
|
||||||
|
|
||||||
import(ABS_CONFIG_FILEPATH)
|
import(PROTOCOL + CONFIG_FILE)
|
||||||
.then(function (conf) {
|
.then(function (conf) {
|
||||||
let dist = conf.buildDir || 'dist'
|
let dist = conf.buildDir || 'dist'
|
||||||
if (clean && fs.isdir(dist)) {
|
if (clean && fs.isdir(dist)) {
|
||||||
console.log('清除dist目录...')
|
|
||||||
fs.rm(dist)
|
fs.rm(dist)
|
||||||
}
|
}
|
||||||
conf.default.ABS_CONFIG_FILEPATH = ABS_CONFIG_FILEPATH
|
|
||||||
compile(WORK_SPACE, dist, conf.default, verbose)
|
compile(WORK_SPACE, dist, conf.default, verbose)
|
||||||
})
|
})
|
||||||
.catch(err => {
|
.catch(err => {
|
||||||
|
|
|
@ -6,11 +6,16 @@
|
||||||
|
|
||||||
import fs from 'iofs'
|
import fs from 'iofs'
|
||||||
import scss from '@bytedo/sass'
|
import scss from '@bytedo/sass'
|
||||||
|
import { createHash, randomUUID } from 'node:crypto'
|
||||||
import Es from 'esbuild'
|
import Es from 'esbuild'
|
||||||
|
import { join } from 'node:path'
|
||||||
import { compile } from '@vue/compiler-dom'
|
import { compile } from '@vue/compiler-dom'
|
||||||
import { red, cyan, blue } from 'kolorist'
|
import { red, cyan, blue } from 'kolorist'
|
||||||
|
|
||||||
|
function uuid() {
|
||||||
|
return randomUUID().slice(-8)
|
||||||
|
}
|
||||||
|
|
||||||
import {
|
import {
|
||||||
JS_EXP,
|
JS_EXP,
|
||||||
STYLE_EXP,
|
STYLE_EXP,
|
||||||
|
@ -18,20 +23,25 @@ import {
|
||||||
CSS_SHEET_EXP,
|
CSS_SHEET_EXP,
|
||||||
V_DEEP,
|
V_DEEP,
|
||||||
PERCENT_EXP,
|
PERCENT_EXP,
|
||||||
SHEETS_DEF,
|
SHEETS_DEF
|
||||||
LEGACY_POLYFILL
|
|
||||||
} from './constants.js'
|
} from './constants.js'
|
||||||
import { createHmrScript, md5, uuid, urlJoin } from './utils.js'
|
import { createHmrScript } from './utils.js'
|
||||||
|
|
||||||
const OPTIONS = {
|
const OPTIONS = {
|
||||||
style: 'compressed'
|
style: 'compressed'
|
||||||
}
|
}
|
||||||
|
|
||||||
function minify(code) {
|
// 修正路径合并 避免在windows下被转义
|
||||||
return Es.transformSync(code, { minify: true }).code.trim()
|
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)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理css中的 :deep()
|
|
||||||
function parseVDeep(curr, val, scoped) {
|
function parseVDeep(curr, val, scoped) {
|
||||||
let res = V_DEEP.exec(curr)
|
let res = V_DEEP.exec(curr)
|
||||||
if (res) {
|
if (res) {
|
||||||
|
@ -42,7 +52,6 @@ function parseVDeep(curr, val, scoped) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理style中的scoped属性
|
|
||||||
function scopeCss(css = '', hash) {
|
function scopeCss(css = '', hash) {
|
||||||
return css.replace(CSS_SHEET_EXP, (m, selector) => {
|
return css.replace(CSS_SHEET_EXP, (m, selector) => {
|
||||||
if (!selector.startsWith('@')) {
|
if (!selector.startsWith('@')) {
|
||||||
|
@ -64,7 +73,7 @@ function scopeCss(css = '', hash) {
|
||||||
if (last.startsWith(':')) {
|
if (last.startsWith(':')) {
|
||||||
output = parseVDeep(last, output, true)
|
output = parseVDeep(last, output, true)
|
||||||
} else {
|
} else {
|
||||||
output = `${last}[data-${hash}] ${output}`
|
output = `${last} ${output}`
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (last.includes(':')) {
|
if (last.includes(':')) {
|
||||||
|
@ -115,9 +124,8 @@ export function compileScss(file, inject = '') {
|
||||||
export function parseJs(
|
export function parseJs(
|
||||||
code = '',
|
code = '',
|
||||||
imports,
|
imports,
|
||||||
{ IS_MPA, currentPage, IS_ENTRY, DEPLOY_PATH, LEGACY_MODE, define } = {},
|
{ IS_MPA, currentPage, IS_ENTRY, DEPLOY_PATH, LEGACY_MODE } = {},
|
||||||
filename,
|
filename
|
||||||
linePatch = 1
|
|
||||||
) {
|
) {
|
||||||
let fixedStyle = ''
|
let fixedStyle = ''
|
||||||
let ASSETS_DIR = '/@/'
|
let ASSETS_DIR = '/@/'
|
||||||
|
@ -131,21 +139,16 @@ export function parseJs(
|
||||||
code = Es.transformSync(code).code || ''
|
code = Es.transformSync(code).code || ''
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
let err = e.errors.pop()
|
let err = e.errors.pop()
|
||||||
let lines = code.split('\n')
|
console.log('%s: %s', red('Uncaught SyntaxError'), err.text)
|
||||||
|
console.log(
|
||||||
console.log('%s: %s', red('Uncaught SyntaxError'), red(err.text))
|
' @ line %d: %s',
|
||||||
// 将上下文几行都打印出来
|
err.location.line,
|
||||||
for (let i = err.location.line - 3; i <= err.location.line + 1; i++) {
|
cyan(err.location.lineText)
|
||||||
console.log(
|
)
|
||||||
' @ line %d: %s',
|
|
||||||
i + linePatch,
|
|
||||||
err.location.line === i + 1 ? red(lines[i]) : lines[i]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
console.log(
|
console.log(
|
||||||
' @ %s:%d:%d',
|
' @ %s:%d:%d',
|
||||||
blue(filename),
|
blue(filename),
|
||||||
err.location.line + linePatch - 1,
|
err.location.line,
|
||||||
err.location.column
|
err.location.column
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -154,7 +157,7 @@ export function parseJs(
|
||||||
.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|export) ([^'"]*?) from (["'])(.*?)\3/g,
|
/(import|export) ([\w\W]*?) from (["'])(.*?)\3/g,
|
||||||
function (m, t, alias, q, name) {
|
function (m, t, alias, q, name) {
|
||||||
if (name.startsWith('@/')) {
|
if (name.startsWith('@/')) {
|
||||||
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
|
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
|
||||||
|
@ -191,19 +194,9 @@ export function parseJs(
|
||||||
if (isBuild) {
|
if (isBuild) {
|
||||||
name = name.replace(/\.vue$/, '.js')
|
name = name.replace(/\.vue$/, '.js')
|
||||||
}
|
}
|
||||||
if (alias.trim() === '*') {
|
return `import ${alias} from '${name}'${
|
||||||
return `${t} ${alias} from '${name}'`
|
t === 'export' ? `\nexport ${alias}` : ''
|
||||||
}
|
}`
|
||||||
let _alias = alias
|
|
||||||
let _import = ''
|
|
||||||
if (alias.includes('* as')) {
|
|
||||||
_alias = ' default ' + alias.replace('* as', '').trim()
|
|
||||||
}
|
|
||||||
|
|
||||||
_import = `import ${alias} from '${name}'`
|
|
||||||
_import += t === 'export' ? `\nexport ${_alias}` : ''
|
|
||||||
|
|
||||||
return _import
|
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
.replace(/import\((['"])(.*?)\1\)/g, function (m, q, name) {
|
.replace(/import\((['"])(.*?)\1\)/g, function (m, q, name) {
|
||||||
|
@ -213,9 +206,6 @@ export function parseJs(
|
||||||
if (name.startsWith('@/')) {
|
if (name.startsWith('@/')) {
|
||||||
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
|
name = name.replace('@/', urlJoin(DEPLOY_PATH, ASSETS_DIR))
|
||||||
}
|
}
|
||||||
if (name.endsWith('.json')) {
|
|
||||||
name += '.js'
|
|
||||||
}
|
|
||||||
return `import('${name}')`
|
return `import('${name}')`
|
||||||
})
|
})
|
||||||
.replace(/import (["'])(.*?)\1/g, function (m, q, name) {
|
.replace(/import (["'])(.*?)\1/g, function (m, q, name) {
|
||||||
|
@ -231,30 +221,19 @@ export function parseJs(
|
||||||
let _name = name.replace(/\\/g, '/').replace('@/', '')
|
let _name = name.replace(/\\/g, '/').replace('@/', '')
|
||||||
let tmp = `style_${uuid()}`
|
let tmp = `style_${uuid()}`
|
||||||
|
|
||||||
// 因为esm语法的变更, 原先的 import xx from xx assets {type: css} 变为了 with
|
|
||||||
// 而这个语法的变化, 构建工具无法做版本判断, 故, 统一降级到fetch()加载
|
|
||||||
if (LEGACY_MODE) {
|
if (LEGACY_MODE) {
|
||||||
fixedStyle +=
|
fixedStyle += `${tmp}.then(r => {
|
||||||
`{\n` +
|
let stylesheet = document.createElement('style')
|
||||||
` let stylesheet = document.createElement('style');\n` +
|
stylesheet.setAttribute('name', '${_name}')
|
||||||
` stylesheet.setAttribute('name', '${_name}');\n` +
|
stylesheet.textContent = r
|
||||||
` stylesheet.textContent = ${tmp};\n` +
|
document.head.appendChild(stylesheet)
|
||||||
` document.head.appendChild(stylesheet);\n` +
|
})
|
||||||
`}\n`
|
`
|
||||||
|
return `const ${tmp} = window.fetch('${name}').then(r => r.text())`
|
||||||
return `let ${tmp};\n!(async function(){\n ${tmp} = await __fite_import('${name}', import.meta.url);\n})()`
|
|
||||||
} else {
|
} else {
|
||||||
// CSSStyleSheet.replaceSync 需要FF v101, Safari 16.4才支持
|
fixedStyle += `${tmp}.path = '${_name}'\n__sheets__.push(${tmp})\n`
|
||||||
fixedStyle +=
|
|
||||||
`{\n` +
|
|
||||||
` let stylesheet = new CSSStyleSheet();\n` +
|
|
||||||
` stylesheet.path = '${_name}';\n` +
|
|
||||||
` stylesheet.replaceSync(${tmp} );\n` +
|
|
||||||
` __sheets__.push(stylesheet);\n` +
|
|
||||||
` document.adoptedStyleSheets = __sheets__;\n` +
|
|
||||||
`}\n`
|
|
||||||
|
|
||||||
return `const ${tmp} = await __fite_import('${name}', import.meta.url)`
|
return `import ${tmp} from '${name}' assert { type: 'css' }`
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (name.startsWith('@/')) {
|
if (name.startsWith('@/')) {
|
||||||
|
@ -290,12 +269,8 @@ export function parseJs(
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
for (let key in define) {
|
|
||||||
code = code.replaceAll(key, define[key])
|
|
||||||
}
|
|
||||||
|
|
||||||
if (fixedStyle) {
|
if (fixedStyle) {
|
||||||
code += '\n\n' + (IS_ENTRY ? SHEETS_DEF : '') + fixedStyle
|
code += '\n\n' + (LEGACY_MODE ? '' : SHEETS_DEF) + fixedStyle
|
||||||
|
|
||||||
if (IS_ENTRY && !LEGACY_MODE) {
|
if (IS_ENTRY && !LEGACY_MODE) {
|
||||||
code += '\ndocument.adoptedStyleSheets = __sheets__'
|
code += '\ndocument.adoptedStyleSheets = __sheets__'
|
||||||
|
@ -310,7 +285,7 @@ export function parseJs(
|
||||||
* @param file <String> 文件路径
|
* @param file <String> 文件路径
|
||||||
* @return <String> 返回转换后的js代码
|
* @return <String> 返回转换后的js代码
|
||||||
*/
|
*/
|
||||||
export async function compileVue(file, imports, options = {}) {
|
export function compileVue(file, imports, options = {}) {
|
||||||
// 修正那反人类的windows路径
|
// 修正那反人类的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')
|
||||||
|
@ -322,7 +297,6 @@ export async function compileVue(file, imports, options = {}) {
|
||||||
let js = code.match(JS_EXP)
|
let js = code.match(JS_EXP)
|
||||||
let scss = [...code.matchAll(STYLE_EXP)]
|
let scss = [...code.matchAll(STYLE_EXP)]
|
||||||
let html = code.match(HTML_EXP) || ['', '']
|
let html = code.match(HTML_EXP) || ['', '']
|
||||||
let linePatch = code.slice(0, js?.index || 0).split('\n').length // js起始行数修正
|
|
||||||
|
|
||||||
let hash = md5(file)
|
let hash = md5(file)
|
||||||
let scopeId = 'data-' + hash
|
let scopeId = 'data-' + hash
|
||||||
|
@ -340,15 +314,10 @@ export async function compileVue(file, imports, options = {}) {
|
||||||
} else {
|
} else {
|
||||||
css = compileScss(it[1], options.INJECT_SCSS)
|
css = compileScss(it[1], options.INJECT_SCSS)
|
||||||
}
|
}
|
||||||
|
|
||||||
return css
|
return css
|
||||||
})
|
})
|
||||||
.join(' ')
|
.join(' ')
|
||||||
|
|
||||||
for (let fn of options.plugin) {
|
|
||||||
scss = await fn('css', scss)
|
|
||||||
}
|
|
||||||
|
|
||||||
js = js ? js[1] : 'export default {}'
|
js = js ? js[1] : 'export default {}'
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
@ -362,8 +331,8 @@ export async function compileVue(file, imports, options = {}) {
|
||||||
isCustomElement
|
isCustomElement
|
||||||
}).code.replace('export function render', 'function render')
|
}).code.replace('export function render', 'function render')
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
let lines = html[1].split('\n')
|
let tmp = html[1].split('\n')
|
||||||
let line = lines[err.loc?.start.line - 1]
|
let line = tmp[err.loc.start.line - 1]
|
||||||
|
|
||||||
console.log('%s: %s', red('SyntaxError'), red(err.message))
|
console.log('%s: %s', red('SyntaxError'), red(err.message))
|
||||||
console.log(
|
console.log(
|
||||||
|
@ -404,7 +373,7 @@ function render(_ctx, _cache) {
|
||||||
CACHE[file] = { changed: false, js, html }
|
CACHE[file] = { changed: false, js, html }
|
||||||
}
|
}
|
||||||
|
|
||||||
output += parseJs(js, imports, options, file, linePatch).replace(
|
output += parseJs(js, imports, options, file).replace(
|
||||||
'export default {',
|
'export default {',
|
||||||
`\n${
|
`\n${
|
||||||
options.LEGACY_MODE ? '' : SHEETS_DEF
|
options.LEGACY_MODE ? '' : SHEETS_DEF
|
||||||
|
@ -425,13 +394,13 @@ function render(_ctx, _cache) {
|
||||||
`
|
`
|
||||||
} else {
|
} else {
|
||||||
output += `
|
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__
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -453,8 +422,10 @@ export function parseHtml(html, { page, imports, entry, LEGACY_MODE }) {
|
||||||
'</head>',
|
'</head>',
|
||||||
`${
|
`${
|
||||||
process.env.NODE_ENV === 'development'
|
process.env.NODE_ENV === 'development'
|
||||||
? ` <script>${minify(createHmrScript(LEGACY_MODE))}</script>\n`
|
? ` <script>${Es.transformSync(createHmrScript(LEGACY_MODE), {
|
||||||
: ` <script>${minify(LEGACY_POLYFILL)}</script>\n`
|
minify: true
|
||||||
|
}).code.trim()}</script>\n`
|
||||||
|
: ''
|
||||||
}</head>`
|
}</head>`
|
||||||
)
|
)
|
||||||
.replace('{{title}}', page.title || '')
|
.replace('{{title}}', page.title || '')
|
||||||
|
|
113
lib/compile.js
113
lib/compile.js
|
@ -1,113 +0,0 @@
|
||||||
/**
|
|
||||||
* {}
|
|
||||||
* @author yutent<yutent.io@gmail.com>
|
|
||||||
* @date 2023/06/14 18:36:15
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { join, dirname, parse, normalize } from 'node:path'
|
|
||||||
import fs from 'iofs'
|
|
||||||
import Es from 'esbuild'
|
|
||||||
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
|
|
||||||
|
|
||||||
const template = fs.cat(join(process.cwd(), 'index.html')).toString()
|
|
||||||
|
|
||||||
export async function compileFiles(
|
|
||||||
currentPage,
|
|
||||||
page,
|
|
||||||
files,
|
|
||||||
options,
|
|
||||||
{ verbose, imports, dist } = {}
|
|
||||||
) {
|
|
||||||
let pageDir = options.IS_MPA && currentPage ? `pages/${currentPage}` : ''
|
|
||||||
options.currentPage = currentPage
|
|
||||||
|
|
||||||
for (let [path, it] of files) {
|
|
||||||
// 入口文件, 特殊处理
|
|
||||||
if (page && path === page.entry) {
|
|
||||||
let entry = fs.cat(page.entry).toString()
|
|
||||||
|
|
||||||
entry = parseJs(entry, imports, { ...options, IS_ENTRY: true })
|
|
||||||
|
|
||||||
let code = parseHtml(template, {
|
|
||||||
page,
|
|
||||||
imports,
|
|
||||||
entry,
|
|
||||||
LEGACY_MODE: options.LEGACY_MODE
|
|
||||||
})
|
|
||||||
|
|
||||||
fs.echo(code, join(dist, `${currentPage}.html`))
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
verbose && console.log(' 解析 %s ...', it.name)
|
|
||||||
|
|
||||||
switch (it.ext) {
|
|
||||||
case '.vue':
|
|
||||||
{
|
|
||||||
let code = await compileVue(path, imports, options)
|
|
||||||
|
|
||||||
await Es.transform(code, { minify: true }).then(async ({ code }) => {
|
|
||||||
for (let fn of options.plugin) {
|
|
||||||
code = await fn('js', code)
|
|
||||||
}
|
|
||||||
fs.echo(
|
|
||||||
code,
|
|
||||||
join(dist, 'assets/', pageDir, it.name.replace(/\.vue$/, '.js'))
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
break
|
|
||||||
|
|
||||||
case '.js':
|
|
||||||
{
|
|
||||||
let code = fs.cat(path)
|
|
||||||
|
|
||||||
code = parseJs(code + '', imports, options)
|
|
||||||
|
|
||||||
await Es.transform(code, { minify: true }).then(async ({ code }) => {
|
|
||||||
for (let fn of options.plugin) {
|
|
||||||
code = await fn('js', code)
|
|
||||||
}
|
|
||||||
fs.echo(code, join(dist, 'assets/', pageDir, it.name))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
break
|
|
||||||
// es2024之后esm的语法的assets 变成了with, 对构建工具来说无法适配到具体的浏览器
|
|
||||||
// 故把json文件改成js文件
|
|
||||||
case '.json':
|
|
||||||
{
|
|
||||||
let code = fs.cat(path)
|
|
||||||
|
|
||||||
code = 'export default ' + JSON.stringify(JSON.parse(code + ''))
|
|
||||||
|
|
||||||
fs.echo(code, join(dist, 'assets/', pageDir, it.name + '.js'))
|
|
||||||
}
|
|
||||||
break
|
|
||||||
|
|
||||||
case '.scss':
|
|
||||||
case '.css':
|
|
||||||
{
|
|
||||||
let target = join(
|
|
||||||
dist,
|
|
||||||
'assets/',
|
|
||||||
pageDir,
|
|
||||||
it.name.replace(/\.scss$/, '.css')
|
|
||||||
)
|
|
||||||
if (it.ext === '.css') {
|
|
||||||
fs.cp(path, target)
|
|
||||||
} else {
|
|
||||||
let code = compileScss(path)
|
|
||||||
for (let fn of options.plugin) {
|
|
||||||
code = await fn('css', code)
|
|
||||||
}
|
|
||||||
fs.echo(code, target)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break
|
|
||||||
|
|
||||||
default:
|
|
||||||
fs.cp(path, join(dist, 'assets/', pageDir, it.name))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -18,33 +18,3 @@ export const COMMON_HEADERS = {
|
||||||
|
|
||||||
export const SHEETS_DEF =
|
export const SHEETS_DEF =
|
||||||
'const __sheets__ = [...document.adoptedStyleSheets];\n'
|
'const __sheets__ = [...document.adoptedStyleSheets];\n'
|
||||||
|
|
||||||
export const LEGACY_POLYFILL = `!(function(){
|
|
||||||
function join(p1, p2) {
|
|
||||||
let tmp1 = p1.split('/')
|
|
||||||
let tmp2 = p2.split('/')
|
|
||||||
if (tmp1.at(-1) === '') {
|
|
||||||
tmp1.pop()
|
|
||||||
}
|
|
||||||
while (tmp2.length) {
|
|
||||||
let tmp = tmp2.shift()
|
|
||||||
if (tmp === '.' || tmp === '') {
|
|
||||||
continue
|
|
||||||
} else if (tmp === '..') {
|
|
||||||
tmp1.pop()
|
|
||||||
} else {
|
|
||||||
tmp1.push(tmp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return tmp1.join('/')
|
|
||||||
}
|
|
||||||
|
|
||||||
window.__fite_import = function(url,relPath){
|
|
||||||
let absPath = relPath.split('/').slice(0, -1).join('/')
|
|
||||||
let req
|
|
||||||
if(url.startsWith('./') || url.startsWith('../')) {
|
|
||||||
url = join(absPath, url)
|
|
||||||
}
|
|
||||||
return window.fetch(url).then(r => r.text())
|
|
||||||
}
|
|
||||||
})()`
|
|
||||||
|
|
148
lib/dev.js
148
lib/dev.js
|
@ -1,5 +1,5 @@
|
||||||
import http from 'node:http'
|
import http from 'node:http'
|
||||||
import https from 'node:http2'
|
import https from 'node:https'
|
||||||
import fs from 'iofs'
|
import fs from 'iofs'
|
||||||
import { join, dirname } from 'node:path'
|
import { join, dirname } from 'node:path'
|
||||||
import { parse } from 'node:url'
|
import { parse } from 'node:url'
|
||||||
|
@ -7,7 +7,7 @@ import socket from './ws.js'
|
||||||
import chokidar from 'chokidar'
|
import chokidar from 'chokidar'
|
||||||
import { red } from 'kolorist'
|
import { red } from 'kolorist'
|
||||||
|
|
||||||
import { friendlyErrors, defaultCustomElement, gzip } from './utils.js'
|
import { friendlyErrors, isCustomElement } from './utils.js'
|
||||||
|
|
||||||
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
|
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
|
||||||
|
|
||||||
|
@ -15,7 +15,7 @@ import MIME_TYPES from './mime-tpyes.js'
|
||||||
import { COMMON_HEADERS } from './constants.js'
|
import { COMMON_HEADERS } from './constants.js'
|
||||||
|
|
||||||
const noc = Buffer.from('')
|
const noc = Buffer.from('')
|
||||||
const SERVER_OPTIONS = { allowHTTP1: true }
|
const SERVER_OPTIONS = {}
|
||||||
const CACHE = {} //文件缓存, 用于hmr
|
const CACHE = {} //文件缓存, 用于hmr
|
||||||
|
|
||||||
function readFile(file) {
|
function readFile(file) {
|
||||||
|
@ -32,9 +32,6 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
const DOMAIN = conf.devServer.domain || 'localhost'
|
const DOMAIN = conf.devServer.domain || 'localhost'
|
||||||
const INJECT_SCSS = readFile(conf.inject?.scss)
|
const INJECT_SCSS = readFile(conf.inject?.scss)
|
||||||
const LEGACY_MODE = !!conf.legacy
|
const LEGACY_MODE = !!conf.legacy
|
||||||
const ENABLE_GZIP = !!conf.devServer.gzip
|
|
||||||
const { isCustomElement = defaultCustomElement } = conf.compileOptions || {}
|
|
||||||
const { plugin = [], define = {} } = conf
|
|
||||||
|
|
||||||
if (conf.imports['vue-dev']) {
|
if (conf.imports['vue-dev']) {
|
||||||
conf.imports.vue = conf.imports['vue-dev']
|
conf.imports.vue = conf.imports['vue-dev']
|
||||||
|
@ -43,10 +40,6 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
conf.imports['vue-router'] = conf.imports['vue-router-dev']
|
conf.imports['vue-router'] = conf.imports['vue-router-dev']
|
||||||
}
|
}
|
||||||
|
|
||||||
if (conf.devServer.headers) {
|
|
||||||
Object.assign(COMMON_HEADERS, conf.devServer.headers)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (USE_HTTPS) {
|
if (USE_HTTPS) {
|
||||||
Object.assign(SERVER_OPTIONS, conf.devServer.ssl)
|
Object.assign(SERVER_OPTIONS, conf.devServer.ssl)
|
||||||
|
|
||||||
|
@ -57,7 +50,7 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
}
|
}
|
||||||
|
|
||||||
const server = (USE_HTTPS ? https : http)
|
const server = (USE_HTTPS ? https : http)
|
||||||
[USE_HTTPS ? 'createSecureServer' : 'createServer'](SERVER_OPTIONS)
|
.createServer(SERVER_OPTIONS)
|
||||||
.listen(PORT)
|
.listen(PORT)
|
||||||
|
|
||||||
const ws = socket(server)
|
const ws = socket(server)
|
||||||
|
@ -74,7 +67,7 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
currentPage = ''
|
currentPage = ''
|
||||||
|
|
||||||
server
|
server
|
||||||
.on('request', async function (req, res) {
|
.on('request', function (req, res) {
|
||||||
let prefix = DEPLOY_PATH ? DEPLOY_PATH.replace(/\/$/, '') : ''
|
let prefix = DEPLOY_PATH ? DEPLOY_PATH.replace(/\/$/, '') : ''
|
||||||
let url =
|
let url =
|
||||||
prefix && req.url.startsWith(prefix)
|
prefix && req.url.startsWith(prefix)
|
||||||
|
@ -87,7 +80,7 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
|
|
||||||
if (prefix && req.url === '/') {
|
if (prefix && req.url === '/') {
|
||||||
res.setHeader('Location', DEPLOY_PATH)
|
res.setHeader('Location', DEPLOY_PATH)
|
||||||
res.writeHead(302, USE_HTTPS ? void 0 : 'Redirect')
|
res.writeHead(302, 'Redirect')
|
||||||
return res.end('')
|
return res.end('')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -112,7 +105,7 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
pageName = tmp.join('.')
|
pageName = tmp.join('.')
|
||||||
// 页面不存在时输出404, 避免进程崩溃退出
|
// 页面不存在时输出404, 避免进程崩溃退出
|
||||||
if (!conf.pages[pageName]) {
|
if (!conf.pages[pageName]) {
|
||||||
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
res.writeHead(404, 'Not Found')
|
||||||
return res.end(`Oops!!! 404 Not Found`)
|
return res.end(`Oops!!! 404 Not Found`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -150,12 +143,11 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
|
|
||||||
if (isIndex) {
|
if (isIndex) {
|
||||||
res.setHeader('content-type', MIME_TYPES.html)
|
res.setHeader('content-type', MIME_TYPES.html)
|
||||||
res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
|
res.writeHead(200, 'OK')
|
||||||
res.end(
|
res.end(
|
||||||
'<style>body{font:14px/1.5 Arial}ol{display:flex;flex-wrap:wrap;}li{width:30%;}a{color:teal}a:visited{color:orange;}</style>' +
|
'<div>注意: 你看到这个页面, 仅在开发时可见。<br>仅为了方便开发多页应用时访问自己想要修改的页面, 而不需要手动输入地址。</div><ul>' +
|
||||||
'<div>注意: 你看到这个页面, 仅在开发时可见。<br>仅为了方便开发多页应用时访问自己想要修改的页面, 而不需要手动输入地址。</div><ol>' +
|
|
||||||
indexPage +
|
indexPage +
|
||||||
'</ol>'
|
'</ul>'
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
res.setHeader('accept-ranges', 'bytes')
|
res.setHeader('accept-ranges', 'bytes')
|
||||||
|
@ -171,25 +163,13 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
let entry = fs.cat(page.entry)?.toString()
|
let entry = fs.cat(page.entry)?.toString()
|
||||||
let html = fs.cat(join(process.cwd(), 'index.html')).toString()
|
let html = fs.cat(join(process.cwd(), 'index.html')).toString()
|
||||||
|
|
||||||
entry = parseJs(
|
entry = parseJs(entry, conf.imports, {
|
||||||
entry,
|
IS_MPA,
|
||||||
conf.imports,
|
currentPage,
|
||||||
{
|
IS_ENTRY: true,
|
||||||
IS_MPA,
|
DEPLOY_PATH,
|
||||||
currentPage,
|
LEGACY_MODE
|
||||||
IS_ENTRY: true,
|
})
|
||||||
DEPLOY_PATH,
|
|
||||||
LEGACY_MODE,
|
|
||||||
isCustomElement,
|
|
||||||
plugin,
|
|
||||||
define
|
|
||||||
},
|
|
||||||
page.entry
|
|
||||||
)
|
|
||||||
|
|
||||||
for (let fn of plugin) {
|
|
||||||
entry = await fn('js', entry)
|
|
||||||
}
|
|
||||||
|
|
||||||
code = parseHtml(html, {
|
code = parseHtml(html, {
|
||||||
page,
|
page,
|
||||||
|
@ -218,12 +198,12 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
}
|
}
|
||||||
if (!fs.isfile(file)) {
|
if (!fs.isfile(file)) {
|
||||||
friendlyErrors(pathname, ext)
|
friendlyErrors(pathname, ext)
|
||||||
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
res.writeHead(404, 'Not Found')
|
||||||
res.end('')
|
res.end('')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
code = await compileVue(file, conf.imports, {
|
code = compileVue(file, conf.imports, {
|
||||||
IS_MPA,
|
IS_MPA,
|
||||||
currentPage,
|
currentPage,
|
||||||
SOURCE_DIR,
|
SOURCE_DIR,
|
||||||
|
@ -231,15 +211,9 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
DEPLOY_PATH,
|
DEPLOY_PATH,
|
||||||
INJECT_SCSS,
|
INJECT_SCSS,
|
||||||
LEGACY_MODE,
|
LEGACY_MODE,
|
||||||
isCustomElement,
|
isCustomElement: conf.isCustomElement || isCustomElement
|
||||||
plugin,
|
|
||||||
define
|
|
||||||
})
|
})
|
||||||
|
|
||||||
for (let fn of plugin) {
|
|
||||||
code = await fn('js', code)
|
|
||||||
}
|
|
||||||
|
|
||||||
res.setHeader('content-type', MIME_TYPES.js)
|
res.setHeader('content-type', MIME_TYPES.js)
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
@ -253,37 +227,26 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
|
|
||||||
if (!fs.isfile(file)) {
|
if (!fs.isfile(file)) {
|
||||||
friendlyErrors(pathname, ext)
|
friendlyErrors(pathname, ext)
|
||||||
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
res.writeHead(404, 'Not Found')
|
||||||
res.end('')
|
res.end('')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (file === conf.inject?.scss) {
|
if (file === conf.inject?.scss) {
|
||||||
console.log(red('设置为注入的样式文件不可被vue/js文件引用\n'))
|
console.log(red('设置为注入的样式文件不可被vue/js文件引用\n'))
|
||||||
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
res.writeHead(404, 'Not Found')
|
||||||
res.end('')
|
res.end('')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
code = compileScss(file)
|
code = compileScss(file)
|
||||||
for (let fn of plugin) {
|
|
||||||
code = await fn('css', code)
|
|
||||||
}
|
|
||||||
res.setHeader('content-type', MIME_TYPES.css)
|
res.setHeader('content-type', MIME_TYPES.css)
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
|
||||||
case 'js':
|
case 'js':
|
||||||
case 'wasm':
|
|
||||||
{
|
{
|
||||||
let rpath = pathname.replace('@/', '')
|
let rpath = pathname.replace('@/', '')
|
||||||
let file
|
let file
|
||||||
let isJson = false
|
|
||||||
let isWasm = rpath.endsWith('.wasm')
|
|
||||||
|
|
||||||
if (rpath.endsWith('json.js')) {
|
|
||||||
isJson = true
|
|
||||||
rpath = rpath.slice(0, -3)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (IS_MPA) {
|
if (IS_MPA) {
|
||||||
// 判断前后2个值相等, 避免出现目录名和页面名字相同时走错逻辑
|
// 判断前后2个值相等, 避免出现目录名和页面名字相同时走错逻辑
|
||||||
|
@ -299,43 +262,20 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
if (fs.isfile(file)) {
|
if (fs.isfile(file)) {
|
||||||
code = fs.cat(file)
|
code = fs.cat(file)
|
||||||
} else if (fs.isfile(join(PUBLIC_DIR, rpath))) {
|
} else if (fs.isfile(join(PUBLIC_DIR, rpath))) {
|
||||||
file = join(PUBLIC_DIR, rpath)
|
code = fs.cat(join(PUBLIC_DIR, rpath))
|
||||||
code = fs.cat(file)
|
|
||||||
} else {
|
} else {
|
||||||
friendlyErrors(rpath, ext)
|
friendlyErrors(rpath, ext)
|
||||||
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
res.writeHead(404, 'Not Found')
|
||||||
res.end('')
|
res.end('')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (isJson) {
|
code = parseJs(code + '', conf.imports, {
|
||||||
try {
|
IS_MPA,
|
||||||
code =
|
currentPage,
|
||||||
'export default ' + JSON.stringify(JSON.parse(code + ''))
|
DEPLOY_PATH,
|
||||||
} catch (err) {
|
LEGACY_MODE
|
||||||
console.log('%s 语法错误: %s', rpath, red(err.message))
|
})
|
||||||
}
|
res.setHeader('content-type', MIME_TYPES.js)
|
||||||
} else if (isWasm) {
|
|
||||||
//
|
|
||||||
} else {
|
|
||||||
code = parseJs(
|
|
||||||
code + '',
|
|
||||||
conf.imports,
|
|
||||||
{
|
|
||||||
IS_MPA,
|
|
||||||
currentPage,
|
|
||||||
DEPLOY_PATH,
|
|
||||||
LEGACY_MODE,
|
|
||||||
isCustomElement,
|
|
||||||
plugin,
|
|
||||||
define
|
|
||||||
},
|
|
||||||
file
|
|
||||||
)
|
|
||||||
for (let fn of plugin) {
|
|
||||||
code = await fn('js', code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
res.setHeader('content-type', MIME_TYPES[ext])
|
|
||||||
}
|
}
|
||||||
|
|
||||||
break
|
break
|
||||||
|
@ -368,23 +308,16 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
}
|
}
|
||||||
if (code === null) {
|
if (code === null) {
|
||||||
friendlyErrors(pathname, ext)
|
friendlyErrors(pathname, ext)
|
||||||
res.writeHead(404, USE_HTTPS ? void 0 : 'Not Found')
|
res.writeHead(404, 'Not Found')
|
||||||
res.end('')
|
res.end('')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ENABLE_GZIP) {
|
res.setHeader('content-length', Buffer.byteLength(code || noc))
|
||||||
code = gzip(code || noc)
|
res.writeHead(200, 'OK')
|
||||||
res.setHeader('Content-Encoding', 'gzip')
|
res.end(code || noc)
|
||||||
} else {
|
|
||||||
code = code || noc
|
|
||||||
}
|
|
||||||
|
|
||||||
res.setHeader('Content-Length', Buffer.byteLength(code))
|
|
||||||
res.writeHead(200, USE_HTTPS ? void 0 : 'OK')
|
|
||||||
res.end(code)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -414,7 +347,7 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
)
|
)
|
||||||
chokidar
|
chokidar
|
||||||
.watch([SOURCE_DIR, PUBLIC_DIR, join(root, './index.html')])
|
.watch([SOURCE_DIR, PUBLIC_DIR, join(root, './index.html')])
|
||||||
.on('all', async (act, filePath) => {
|
.on('all', (act, filePath) => {
|
||||||
if (ready) {
|
if (ready) {
|
||||||
let file = filePath.slice(SOURCE_DIR.length)
|
let file = filePath.slice(SOURCE_DIR.length)
|
||||||
|
|
||||||
|
@ -434,9 +367,6 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
} else {
|
} else {
|
||||||
content = fs.cat(filePath).toString()
|
content = fs.cat(filePath).toString()
|
||||||
}
|
}
|
||||||
for (let fn of plugin) {
|
|
||||||
content = await fn('css', content)
|
|
||||||
}
|
|
||||||
ws.send({
|
ws.send({
|
||||||
action: 'render',
|
action: 'render',
|
||||||
data: { path: file.replace(/\\/g, '/'), content }
|
data: { path: file.replace(/\\/g, '/'), content }
|
||||||
|
@ -446,7 +376,7 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
|
|
||||||
case 'vue':
|
case 'vue':
|
||||||
{
|
{
|
||||||
let content = await compileVue(filePath, conf.imports, {
|
let content = compileVue(filePath, conf.imports, {
|
||||||
IS_MPA,
|
IS_MPA,
|
||||||
currentPage,
|
currentPage,
|
||||||
SOURCE_DIR,
|
SOURCE_DIR,
|
||||||
|
@ -454,9 +384,7 @@ export default async function createServer(root = '', conf = {}) {
|
||||||
DEPLOY_PATH,
|
DEPLOY_PATH,
|
||||||
INJECT_SCSS,
|
INJECT_SCSS,
|
||||||
LEGACY_MODE,
|
LEGACY_MODE,
|
||||||
isCustomElement,
|
isCustomElement: conf.isCustomElement || isCustomElement
|
||||||
plugin,
|
|
||||||
define
|
|
||||||
})
|
})
|
||||||
let tmp = CACHE[filePath]
|
let tmp = CACHE[filePath]
|
||||||
if (tmp.changed) {
|
if (tmp.changed) {
|
||||||
|
|
261
lib/prod.js
261
lib/prod.js
|
@ -1,79 +1,33 @@
|
||||||
import { join, dirname, parse, normalize } from 'node:path'
|
import { join, dirname, parse } from 'node:path'
|
||||||
import { Worker, parentPort } from 'node:worker_threads'
|
|
||||||
import os from 'node:os'
|
|
||||||
import fs from 'iofs'
|
import fs from 'iofs'
|
||||||
|
import Es from 'esbuild'
|
||||||
import { compileFiles } from './compile.js'
|
import { compileScss, parseJs, compileVue, parseHtml } from './compile-vue.js'
|
||||||
import { defaultCustomElement } from './utils.js'
|
import { isCustomElement } from './utils.js'
|
||||||
|
|
||||||
const IS_WIN = process.platform === 'win32'
|
const IS_WIN = process.platform === 'win32'
|
||||||
const PREFIX = IS_WIN ? 'pages\\' : 'pages/'
|
const PREFIX = IS_WIN ? 'pages\\' : 'pages/'
|
||||||
// 4核(或4线程)以上的CPU, 才开启多线程编译。且线程开销太高, 开太多线程效率反而不高。
|
|
||||||
const CPU_CORES = os.cpus().length > 5 ? 6 : os.cpus().length
|
|
||||||
const THREADS_NUM = CPU_CORES > 3 ? CPU_CORES - 1 : 0
|
|
||||||
const __filename = normalize(import.meta.url.slice(IS_WIN ? 8 : 7))
|
|
||||||
const __dirname = dirname(__filename)
|
|
||||||
const WORKER_POOL = new Set() // 线程池
|
|
||||||
const JOBS_QUEUE = [] // 任务队列
|
|
||||||
|
|
||||||
function readFile(file) {
|
function readFile(file) {
|
||||||
return (file && fs.cat(file)?.toString()) || ''
|
return (file && fs.cat(file)?.toString()) || ''
|
||||||
}
|
}
|
||||||
|
|
||||||
function doJob() {
|
|
||||||
while (JOBS_QUEUE.length && WORKER_POOL.size) {
|
|
||||||
let job = JOBS_QUEUE.shift()
|
|
||||||
let worker = WORKER_POOL.values().next().value
|
|
||||||
|
|
||||||
WORKER_POOL.delete(worker)
|
|
||||||
|
|
||||||
worker.once('message', _ => {
|
|
||||||
if (JOBS_QUEUE.length) {
|
|
||||||
WORKER_POOL.add(worker)
|
|
||||||
doJob()
|
|
||||||
} else {
|
|
||||||
worker.terminate()
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
worker.postMessage(job)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function compile(root = '', dist = '', conf = {}, verbose) {
|
export default function compile(root = '', dist = '', conf = {}, verbose) {
|
||||||
//
|
//
|
||||||
const SOURCE_DIR = join(root, 'src')
|
const SOURCE_DIR = join(root, 'src')
|
||||||
const PUBLIC_DIR = join(root, 'public')
|
const PUBLIC_DIR = join(root, 'public')
|
||||||
const DEPLOY_PATH = conf.base || '' // 部署目录, 默认是根目录部署
|
const DEPLOY_PATH = conf.base || '' // 部署目录, 默认是根目录部署
|
||||||
const PAGES_KEYS = Object.keys(conf.pages)
|
const IS_MPA = Object.keys(conf.pages).length > 1
|
||||||
const IS_MPA = PAGES_KEYS.length > 1
|
const PAGES_PREFIX = Object.keys(conf.pages).map(it =>
|
||||||
const PAGES_PREFIX = PAGES_KEYS.map(it =>
|
|
||||||
IS_WIN ? `${PREFIX + it}\\` : `${PREFIX + it}/`
|
IS_WIN ? `${PREFIX + it}\\` : `${PREFIX + it}/`
|
||||||
)
|
)
|
||||||
const INJECT_SCSS = readFile(conf.inject?.scss)
|
const INJECT_SCSS = readFile(conf.inject?.scss)
|
||||||
const LEGACY_MODE = !!conf.legacy
|
const LEGACY_MODE = !!conf.legacy
|
||||||
const {
|
|
||||||
ABS_CONFIG_FILEPATH,
|
|
||||||
compileOptions = {},
|
|
||||||
define = {},
|
|
||||||
plugin = []
|
|
||||||
} = conf
|
|
||||||
const { isCustomElement = defaultCustomElement } = compileOptions
|
|
||||||
|
|
||||||
conf.inject = conf.inject || { scss: '' }
|
conf.inject = conf.inject || { scss: '' }
|
||||||
|
|
||||||
let timeStart = Date.now()
|
let timeStart = Date.now()
|
||||||
let template = fs.cat(join(process.cwd(), 'index.html')).toString()
|
let template = fs.cat(join(process.cwd(), 'index.html')).toString()
|
||||||
let list = new Map()
|
let list = {}
|
||||||
let options = {
|
|
||||||
IS_MPA,
|
|
||||||
SOURCE_DIR,
|
|
||||||
DEPLOY_PATH,
|
|
||||||
INJECT_SCSS,
|
|
||||||
LEGACY_MODE,
|
|
||||||
ABS_CONFIG_FILEPATH,
|
|
||||||
define
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.ls(SOURCE_DIR, true).forEach(path => {
|
fs.ls(SOURCE_DIR, true).forEach(path => {
|
||||||
if (fs.isdir(path)) {
|
if (fs.isdir(path)) {
|
||||||
|
@ -82,43 +36,109 @@ export default function compile(root = '', dist = '', conf = {}, verbose) {
|
||||||
|
|
||||||
let name = path.slice(SOURCE_DIR.length + 1)
|
let name = path.slice(SOURCE_DIR.length + 1)
|
||||||
let it = {
|
let it = {
|
||||||
|
path,
|
||||||
name,
|
name,
|
||||||
ext: parse(name).ext
|
ext: parse(name).ext
|
||||||
}
|
}
|
||||||
if (it.ext) {
|
if (it.ext !== '') {
|
||||||
if (IS_MPA && it.name.startsWith(PREFIX)) {
|
if (IS_MPA && it.name.startsWith(PREFIX)) {
|
||||||
if (PAGES_PREFIX.some(it => it.startsWith(it.name))) {
|
if (PAGES_PREFIX.some(it => it.startsWith(it.name))) {
|
||||||
list.set(path, it)
|
return (list[path] = it)
|
||||||
|
} else {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (it.path === conf.inject.scss) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if (path === conf.inject.scss) {
|
list[path] = it
|
||||||
return
|
|
||||||
}
|
|
||||||
list.set(path, it)
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
// 创建线程池
|
let compileFiles = function (currentPage, page, files) {
|
||||||
if (THREADS_NUM > 0 && (IS_MPA || list.size > THREADS_NUM * 10)) {
|
let options = {
|
||||||
// 页面数过少时, 线程数量不能比页面数多
|
IS_MPA,
|
||||||
let max = Math.min(THREADS_NUM, PAGES_KEYS.length)
|
currentPage,
|
||||||
|
SOURCE_DIR,
|
||||||
for (let i = 0; i < max; i++) {
|
DEPLOY_PATH,
|
||||||
WORKER_POOL.add(
|
INJECT_SCSS,
|
||||||
new Worker(join(__dirname, './thread.js'), {
|
LEGACY_MODE,
|
||||||
workerData: {
|
isCustomElement: conf.isCustomElement || isCustomElement
|
||||||
options,
|
}
|
||||||
verbose,
|
|
||||||
dist,
|
for (let k in files) {
|
||||||
imports: conf.imports
|
let it = files[k]
|
||||||
}
|
// 入口文件, 特殊处理
|
||||||
})
|
if (page && it.path === page.entry) {
|
||||||
)
|
let entry = fs.cat(page.entry).toString()
|
||||||
|
|
||||||
|
entry = parseJs(entry, conf.imports, { ...options, IS_ENTRY: true })
|
||||||
|
|
||||||
|
let code = parseHtml(template, {
|
||||||
|
page,
|
||||||
|
imports: conf.imports,
|
||||||
|
entry,
|
||||||
|
LEGACY_MODE
|
||||||
|
})
|
||||||
|
|
||||||
|
fs.echo(code, join(dist, `${currentPage}.html`))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
verbose && console.log(' 解析 %s ...', it.name)
|
||||||
|
|
||||||
|
let pageDir = IS_MPA && currentPage ? `pages/${currentPage}` : ''
|
||||||
|
|
||||||
|
switch (it.ext) {
|
||||||
|
case '.vue':
|
||||||
|
{
|
||||||
|
let code = compileVue(it.path, conf.imports, options)
|
||||||
|
|
||||||
|
Es.transform(code, { minify: true }).then(r => {
|
||||||
|
fs.echo(
|
||||||
|
r.code,
|
||||||
|
join(dist, 'assets/', pageDir, it.name.replace(/\.vue$/, '.js'))
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
break
|
||||||
|
|
||||||
|
case '.js':
|
||||||
|
{
|
||||||
|
let code = fs.cat(it.path)
|
||||||
|
|
||||||
|
code = parseJs(code + '', conf.imports, options)
|
||||||
|
|
||||||
|
Es.transform(code, { minify: true }).then(r => {
|
||||||
|
fs.echo(r.code, join(dist, 'assets/', pageDir, it.name))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
break
|
||||||
|
|
||||||
|
case '.scss':
|
||||||
|
case '.css':
|
||||||
|
{
|
||||||
|
let target = join(
|
||||||
|
dist,
|
||||||
|
'assets/',
|
||||||
|
it.name.replace(/\.scss$/, '.css')
|
||||||
|
)
|
||||||
|
if (it.ext === '.css') {
|
||||||
|
fs.cp(it.path, target)
|
||||||
|
} else {
|
||||||
|
let code = compileScss(it.path)
|
||||||
|
fs.echo(code, target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
|
||||||
|
default:
|
||||||
|
fs.cp(it.path, join(dist, it.name))
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
options.isCustomElement = isCustomElement
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 优先处理静态目录, 之后的源码目录中, 以便如果有产生相同的文件名, 则覆盖静态目录中的文件
|
// 优先处理静态目录, 之后的源码目录中, 以便如果有产生相同的文件名, 则覆盖静态目录中的文件
|
||||||
|
@ -127,21 +147,25 @@ export default function compile(root = '', dist = '', conf = {}, verbose) {
|
||||||
fs.ls(PUBLIC_DIR, true).forEach(it => {
|
fs.ls(PUBLIC_DIR, true).forEach(it => {
|
||||||
let ext = parse(it).ext
|
let ext = parse(it).ext
|
||||||
|
|
||||||
if (ext && fs.isfile(it)) {
|
if (ext === '') {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fs.isfile(it)) {
|
||||||
let name = it.slice(PUBLIC_DIR.length + 1)
|
let name = it.slice(PUBLIC_DIR.length + 1)
|
||||||
verbose && console.log(' 复制 %s ...', name)
|
verbose && console.log(' 复制 %s ...', name)
|
||||||
fs.cp(it, join(dist, name))
|
fs.cp(it, join(dist, name))
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
console.log('')
|
||||||
|
|
||||||
if (IS_MPA) {
|
for (let currentPage in conf.pages) {
|
||||||
for (let currentPage of PAGES_KEYS) {
|
let page = conf.pages[currentPage]
|
||||||
let page = conf.pages[currentPage]
|
let dir = dirname(page.entry)
|
||||||
let dir = dirname(page.entry)
|
let files = list
|
||||||
let files = new Map()
|
if (IS_MPA) {
|
||||||
let chunk = new Map()
|
files = {}
|
||||||
|
|
||||||
fs.ls(dir, true).forEach(path => {
|
fs.ls(dir, true).forEach(path => {
|
||||||
if (fs.isdir(path)) {
|
if (fs.isdir(path)) {
|
||||||
return
|
return
|
||||||
|
@ -154,68 +178,17 @@ export default function compile(root = '', dist = '', conf = {}, verbose) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
list.delete(path)
|
delete list[path]
|
||||||
files.set(path, { name, ext })
|
files[path] = { name, path, ext }
|
||||||
})
|
|
||||||
|
|
||||||
if (THREADS_NUM > 0) {
|
|
||||||
chunk.set(currentPage, { page, files })
|
|
||||||
JOBS_QUEUE.push(chunk)
|
|
||||||
doJob()
|
|
||||||
} else {
|
|
||||||
console.log(`正在生成 ${currentPage}.html ...`)
|
|
||||||
compileFiles(currentPage, page, files, options, {
|
|
||||||
verbose,
|
|
||||||
dist,
|
|
||||||
imports: conf.imports
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 公共依赖
|
|
||||||
if (THREADS_NUM > 0) {
|
|
||||||
let chunk = new Map()
|
|
||||||
chunk.set('', { page: null, files: list })
|
|
||||||
|
|
||||||
JOBS_QUEUE.push(chunk)
|
|
||||||
doJob()
|
|
||||||
} else {
|
|
||||||
console.log('\n正在解析公共依赖 ...')
|
|
||||||
compileFiles('', null, list, options, {
|
|
||||||
verbose,
|
|
||||||
dist,
|
|
||||||
imports: conf.imports
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
} else {
|
console.log('正在生成 %s ...', `${currentPage}.html`)
|
||||||
// 每个线程处理的文件数
|
compileFiles(currentPage, page, files)
|
||||||
let chunkSize = Math.ceil(list.size / THREADS_NUM)
|
}
|
||||||
let currentPage = PAGES_KEYS[0]
|
|
||||||
let page = conf.pages[currentPage]
|
|
||||||
|
|
||||||
console.log(`正在生成 ${currentPage}.html ...`)
|
if (IS_MPA) {
|
||||||
|
console.log('\n正在解析公共依赖 ...')
|
||||||
if (THREADS_NUM > 0 && list.size > THREADS_NUM * 10) {
|
compileFiles('', null, list)
|
||||||
list = [...list]
|
|
||||||
for (let i = 0; i < THREADS_NUM; i++) {
|
|
||||||
let start = i * chunkSize
|
|
||||||
let end = start + chunkSize
|
|
||||||
let chunk = new Map()
|
|
||||||
|
|
||||||
chunk.set(currentPage, { page, files: list.slice(start, end) })
|
|
||||||
|
|
||||||
JOBS_QUEUE.push(chunk)
|
|
||||||
doJob()
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
options.plugin = plugin
|
|
||||||
options.isCustomElement = isCustomElement
|
|
||||||
compileFiles(currentPage, page, list, options, {
|
|
||||||
verbose,
|
|
||||||
dist,
|
|
||||||
imports: conf.imports
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
process.on('exit', _ => {
|
process.on('exit', _ => {
|
||||||
|
|
|
@ -1,40 +0,0 @@
|
||||||
/**
|
|
||||||
* 子线程
|
|
||||||
* @author yutent<yutent.io@gmail.com>
|
|
||||||
* @date 2023/06/14 16:15:39
|
|
||||||
*/
|
|
||||||
import { parentPort, workerData } from 'node:worker_threads'
|
|
||||||
import { compileFiles } from './compile.js'
|
|
||||||
import { defaultCustomElement } from './utils.js'
|
|
||||||
|
|
||||||
const { options, verbose, dist, imports } = workerData
|
|
||||||
const { ABS_CONFIG_FILEPATH } = options
|
|
||||||
|
|
||||||
const { compileOptions = {}, plugin = [] } = await import(
|
|
||||||
ABS_CONFIG_FILEPATH
|
|
||||||
).then(r => r.default)
|
|
||||||
|
|
||||||
const { isCustomElement = defaultCustomElement } = compileOptions
|
|
||||||
options.isCustomElement = isCustomElement
|
|
||||||
options.plugin = plugin
|
|
||||||
|
|
||||||
//
|
|
||||||
async function doJob(job) {
|
|
||||||
let [currentPage, { page, files }] = job.entries().next().value
|
|
||||||
|
|
||||||
options.IS_MPA &&
|
|
||||||
console.log(
|
|
||||||
currentPage
|
|
||||||
? `正在生成 ${currentPage}.html ...`
|
|
||||||
: '\n正在解析公共依赖 ...'
|
|
||||||
)
|
|
||||||
|
|
||||||
await compileFiles(currentPage, page, files, options, {
|
|
||||||
verbose,
|
|
||||||
dist,
|
|
||||||
imports
|
|
||||||
})
|
|
||||||
parentPort.postMessage(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
parentPort.on('message', doJob)
|
|
48
lib/utils.js
48
lib/utils.js
|
@ -4,30 +4,8 @@
|
||||||
* @date 2023/05/22 14:52:00
|
* @date 2023/05/22 14:52:00
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { createHash, randomUUID } from 'node:crypto'
|
|
||||||
import { join } from 'node:path'
|
|
||||||
import { gzipSync } from 'node:zlib'
|
|
||||||
import { red, cyan, blue } from 'kolorist'
|
import { red, cyan, blue } from 'kolorist'
|
||||||
import { LEGACY_POLYFILL } from './constants.js'
|
import { Worker } from 'node:worker_threads'
|
||||||
|
|
||||||
// 修正路径合并 避免在windows下被转义
|
|
||||||
export function urlJoin(...args) {
|
|
||||||
return join(...args).replace(/\\/g, '/')
|
|
||||||
}
|
|
||||||
|
|
||||||
export function uuid() {
|
|
||||||
return randomUUID().slice(-8)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function md5(str = '') {
|
|
||||||
let sum = createHash('md5')
|
|
||||||
sum.update(str, 'utf8')
|
|
||||||
return sum.digest('hex').slice(0, 8)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function gzip(val) {
|
|
||||||
return gzipSync(val)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function friendlyErrors(pathname, ext = '') {
|
export function friendlyErrors(pathname, ext = '') {
|
||||||
console.log(cyan(pathname), red(`not found!!!`))
|
console.log(cyan(pathname), red(`not found!!!`))
|
||||||
|
@ -37,10 +15,10 @@ export function friendlyErrors(pathname, ext = '') {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createHmrScript(legacy, session = '') {
|
export function createHmrScript(legacy) {
|
||||||
return `
|
return `
|
||||||
!(function vue_live_hmr(){
|
!(function vue_live_hmr(){
|
||||||
let ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-fite-hmr?session=\${btoa(location.pathname).replace(/[=\+\/]/g, '')}&lock=\${localStorage.getItem(location.pathname) || 0}\`)
|
var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-fite-hmr\`)
|
||||||
|
|
||||||
ws.addEventListener('open', function (r) {
|
ws.addEventListener('open', function (r) {
|
||||||
if(vue_live_hmr.closed){
|
if(vue_live_hmr.closed){
|
||||||
|
@ -52,9 +30,6 @@ export function createHmrScript(legacy, session = '') {
|
||||||
|
|
||||||
ws.addEventListener('close', function(){
|
ws.addEventListener('close', function(){
|
||||||
vue_live_hmr.closed = true
|
vue_live_hmr.closed = true
|
||||||
if (localStorage.getItem(location.pathname) === '1') {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
setTimeout(vue_live_hmr, 2000)
|
setTimeout(vue_live_hmr, 2000)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
@ -94,12 +69,23 @@ export function createHmrScript(legacy, session = '') {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
${LEGACY_POLYFILL}
|
|
||||||
})()
|
})()
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
|
|
||||||
// 默认的 web components 判断
|
export function isCustomElement(tag) {
|
||||||
export function defaultCustomElement(tag) {
|
|
||||||
return tag.startsWith('wc-')
|
return tag.startsWith('wc-')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function startWorker(file) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let worker = new Worker(file)
|
||||||
|
worker.on('message', resolve)
|
||||||
|
worker.on('error', reject)
|
||||||
|
worker.on('exit', code => {
|
||||||
|
if (code !== 0) {
|
||||||
|
reject(new Error(`Worker stopped with exit code ${code}`))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
34
lib/ws.js
34
lib/ws.js
|
@ -6,40 +6,28 @@
|
||||||
import { WebSocketServer } from 'ws'
|
import { WebSocketServer } from 'ws'
|
||||||
|
|
||||||
class WebSocket {
|
class WebSocket {
|
||||||
#clients = new Map()
|
#ws = null // ws实例
|
||||||
#queue = [] // 消息队列
|
#queue = [] // 消息队列
|
||||||
|
|
||||||
constructor(server) {
|
constructor(server) {
|
||||||
if (server.listening) {
|
if (server.listening) {
|
||||||
let conn = new WebSocketServer({ server, path: '/ws-fite-hmr' })
|
let conn = new WebSocketServer({ server, path: '/ws-fite-hmr' })
|
||||||
conn.on('connection', (client, req) => {
|
conn.on('connection', ws => {
|
||||||
let params = new URLSearchParams(req.url.slice(req.url.indexOf('?')))
|
this.#ws = ws
|
||||||
let session = params.get('session')
|
// ws.on('message', data => {
|
||||||
let lock = +params.get('lock')
|
// console.log(data + '');
|
||||||
|
// })
|
||||||
if (lock === 1) {
|
while (this.#queue.length) {
|
||||||
client.close()
|
let msg = this.#queue.shift()
|
||||||
} else {
|
this.send(msg)
|
||||||
this.#clients.set(session, client)
|
|
||||||
|
|
||||||
client.once('close', _ => {
|
|
||||||
this.#clients.delete(session)
|
|
||||||
})
|
|
||||||
|
|
||||||
while (this.#queue.length) {
|
|
||||||
let msg = this.#queue.shift()
|
|
||||||
this.send(msg)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
send(msg = {}) {
|
send(msg = {}) {
|
||||||
if (this.#clients.size) {
|
if (this.#ws) {
|
||||||
for (let [key, client] of this.#clients) {
|
this.#ws.send(JSON.stringify(msg))
|
||||||
client.send(JSON.stringify(msg))
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
this.#queue.push(msg)
|
this.#queue.push(msg)
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
{
|
{
|
||||||
"name": "fite",
|
"name": "fite",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"version": "1.4.4",
|
"version": "1.1.7",
|
||||||
"bin": {
|
"bin": {
|
||||||
"fite": "index.js"
|
"fite": "index.js"
|
||||||
},
|
},
|
||||||
|
@ -19,6 +19,5 @@
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.6.0"
|
"node": ">=16.6.0"
|
||||||
},
|
}
|
||||||
"license": "MIT"
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue