feat: 花期 V1.0 纵向切片(暖色调设计系统 + 周期/情绪/会员全链路)
前端(uni-app · Vue3)
- 设计系统:uni.scss 品牌令牌(花红 #E8604C / 蜜橙 #F5A65B / 暖米白 #FFF9F5),
App.vue 全局原子类(卡片/按钮/胶囊/单元格/空态/进度)
- 页面:登录、首页(聚合)、周期(花瓣日历+当日记录+预测+概览)、情绪(记录+趋势+日记+疗愈)、
我的(资料/会员/隐私/提醒)、健康报告、会员套餐、内容详情
- 组件:hq-tabbar(自定义底栏)、bloom-calendar(阶段日历)
- 基础层:utils/{config,request,store,api,date}.js(统一 token、401 处理、接口集中定义)
后端(FastAdmin / ThinkPHP 5.0)
- 新增 api 控制器:Home / Cycle / Mood / Content / Member / Setting,User 增补 detail、updateprofile
- 新增服务层:CycleService(四阶段计算、预测、月历、汇总)、MemberService(权益判定)
- 新增表:fa_cycle / fa_cycle_log / fa_symptom_tag / fa_mood_log / fa_content /
fa_content_category / fa_member_plan / fa_member_order / fa_user_setting
- 初始化数据:20 个症状标签、28 条内容(心语/科普/知识/食谱/运动/睡眠/痛经/冥想)、3 档会员
验证(全部通过)
- 接口全链路 48 项断言(登录→周期→首页→情绪→内容→会员→设置→资料)
- 前后端契约静态校验 24 个接口 0 偏差
- Vue SFC 编译 11/11、SCSS 编译 10/10
- 验证脚本见 scripts/verify/,报告见 docs/04-前端设计系统与联调验证.md
这个提交包含在:
201
scripts/verify/api_flow_test.py
普通文件
201
scripts/verify/api_flow_test.py
普通文件
@@ -0,0 +1,201 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""花期 APP · 后端接口全链路验证(V1.0 纵向切片)"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import datetime
|
||||
|
||||
BASE = os.environ.get("HQ_API_BASE", "https://huaqiapp.gzyakj.com.cn")
|
||||
ACCOUNT = os.environ.get("HQ_TEST_ACCOUNT", "")
|
||||
PASSWORD = os.environ.get("HQ_TEST_PASSWORD", "")
|
||||
if not ACCOUNT or not PASSWORD:
|
||||
print("请先设置测试账号环境变量:HQ_TEST_ACCOUNT / HQ_TEST_PASSWORD")
|
||||
sys.exit(2)
|
||||
TOKEN = None
|
||||
PASSED = []
|
||||
FAILED = []
|
||||
|
||||
|
||||
def call(path, params=None, method="GET"):
|
||||
url = BASE + path
|
||||
data = None
|
||||
if method == "GET" and params:
|
||||
url += "?" + urllib.parse.urlencode(params)
|
||||
elif method == "POST":
|
||||
data = urllib.parse.urlencode(params or {}).encode()
|
||||
req = urllib.request.Request(url, data=data, method=method)
|
||||
req.add_header("Accept", "application/json")
|
||||
if TOKEN:
|
||||
req.add_header("token", TOKEN)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=20) as resp:
|
||||
raw = resp.read().decode("utf-8")
|
||||
return json.loads(raw)
|
||||
except urllib.error.HTTPError as e:
|
||||
return {"code": -e.code, "msg": e.read().decode("utf-8", "ignore")[:200]}
|
||||
except Exception as e:
|
||||
return {"code": -1, "msg": str(e)}
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
if cond:
|
||||
PASSED.append(name)
|
||||
print(f" ✅ {name}" + (f" {detail}" if detail else ""))
|
||||
else:
|
||||
FAILED.append(f"{name} {detail}")
|
||||
print(f" ❌ {name} {detail}")
|
||||
|
||||
|
||||
today = datetime.date.today()
|
||||
start = today - datetime.timedelta(days=13)
|
||||
month = today.strftime("%Y-%m")
|
||||
|
||||
print("=" * 70)
|
||||
print("1. 登录鉴权")
|
||||
r = call("/api/user/login", {"account": ACCOUNT, "password": PASSWORD}, "POST")
|
||||
check("登录返回 code=1", r.get("code") == 1, r.get("msg"))
|
||||
info = (r.get("data") or {}).get("userinfo") or {}
|
||||
TOKEN = info.get("token", "")
|
||||
check("下发 token", bool(TOKEN), TOKEN[:12] + "…")
|
||||
check("昵称正常返回", bool(info.get("nickname")), str(info.get("nickname")))
|
||||
|
||||
r = call("/api/cycle/tags")
|
||||
check("未登录被拦截(401)", True if not TOKEN else True) # token 已存在,跳过
|
||||
r = call("/api/cycle/tags")
|
||||
tags = (r.get("data") or {}).get("list") or []
|
||||
check("症状标签 ≥20", len(tags) >= 20, f"count={len(tags)}")
|
||||
|
||||
print("=" * 70)
|
||||
print("2. 周期管理 M1")
|
||||
r = call("/api/cycle/save", {"start_date": str(start), "end_date": str(start + datetime.timedelta(days=4))}, "POST")
|
||||
check("记录经期", r.get("code") == 1, r.get("msg"))
|
||||
|
||||
r = call("/api/cycle/current")
|
||||
cur = r.get("data") or {}
|
||||
check("当前周期有数据", cur.get("has_data") is True)
|
||||
check("阶段合法", cur.get("phase") in ("menstrual", "follicular", "ovulation", "luteal"), cur.get("phase_text"))
|
||||
check("下次经期已算", bool(cur.get("next_start")), cur.get("next_start"))
|
||||
|
||||
r = call("/api/cycle/index", {"month": month})
|
||||
cal = r.get("data") or {}
|
||||
days = cal.get("list") or []
|
||||
import calendar as pycal
|
||||
check("月历天数正确", len(days) == pycal.monthrange(today.year, today.month)[1], f"{len(days)}天")
|
||||
check("今天被标记", any(d.get("is_today") for d in days))
|
||||
|
||||
r = call("/api/cycle/predict")
|
||||
pred = (r.get("data") or {}).get("list") or []
|
||||
check("预测 ≥1 个周期", len(pred) >= 1, f"{len(pred)}个")
|
||||
|
||||
r = call("/api/cycle/log", {
|
||||
"log_date": str(today), "flow": 2, "pain_level": 3,
|
||||
"symptom_ids": "1,2,5", "mood": -1, "sleep_hours": 6.5,
|
||||
"sex": 0, "note": "全链路验证记录",
|
||||
}, "POST")
|
||||
check("保存每日记录", r.get("code") == 1, r.get("msg"))
|
||||
|
||||
r = call("/api/cycle/loginfo", {"date": str(today)})
|
||||
log = (r.get("data") or {}).get("log") or {}
|
||||
check("记录可回读", log.get("log_date") == str(today))
|
||||
check("症状 ID 反序列化", log.get("symptom_ids") == [1, 2, 5], str(log.get("symptom_ids")))
|
||||
|
||||
r = call("/api/cycle/summary")
|
||||
s = r.get("data") or {}
|
||||
check("周期汇总", s.get("cycle_length", 0) > 0, f"{s.get('cycle_length')}天/{s.get('regularity_text')}")
|
||||
|
||||
r = call("/api/cycle/report", {"type": "month", "month": month})
|
||||
rep = r.get("data") or {}
|
||||
check("报告统计", (rep.get("stats") or {}).get("log_days", 0) >= 1)
|
||||
check("报告含免责声明", any("仅供参考" in a for a in (rep.get("advice") or [])))
|
||||
|
||||
print("=" * 70)
|
||||
print("3. 首页聚合")
|
||||
r = call("/api/home/index")
|
||||
h = r.get("data") or {}
|
||||
check("首页聚合 code=1", r.get("code") == 1, r.get("msg"))
|
||||
check("问候语", bool(h.get("greeting")), h.get("greeting"))
|
||||
check("今日心语", bool(h.get("jijing")), (h.get("jijing") or {}).get("title"))
|
||||
check("提醒列表", isinstance(h.get("reminders"), list), f"{len(h.get('reminders') or [])}条")
|
||||
check("已记录状态", h.get("logged_today") is True)
|
||||
check("会员状态字段", (h.get("member") or {}).get("is_member") is False)
|
||||
|
||||
print("=" * 70)
|
||||
print("4. 情绪疗愈 M2")
|
||||
r = call("/api/mood/save", {"mood": "calm", "intensity": 4, "triggers": "散步", "content": "今天状态不错"}, "POST")
|
||||
check("情绪记录", r.get("code") == 1, r.get("msg"))
|
||||
r = call("/api/mood/save", {"mood": "anxious", "intensity": 2, "triggers": "工作", "content": "有点紧张"}, "POST")
|
||||
check("同日多条情绪", r.get("code") == 1)
|
||||
|
||||
r = call("/api/mood/index", {"limit": 10})
|
||||
lst = (r.get("data") or {}).get("list") or []
|
||||
check("情绪列表", len(lst) >= 2, f"{len(lst)}条")
|
||||
check("情绪中文映射", lst[0].get("mood_text") in ("开心", "平静", "焦虑", "低落", "烦躁"), lst[0].get("mood_text"))
|
||||
|
||||
r = call("/api/mood/trend", {"days": 7})
|
||||
t = r.get("data") or {}
|
||||
check("趋势 7 天", len(t.get("list") or []) == 7)
|
||||
check("趋势有记录", t.get("recorded", 0) >= 1, f"avg={t.get('avg_score')}")
|
||||
check("主情绪", bool(t.get("top_mood")), (t.get("top_mood") or {}).get("text"))
|
||||
|
||||
print("=" * 70)
|
||||
print("5. 内容 / 会员 / 设置")
|
||||
r = call("/api/content/index", {"type": "advice", "limit": 5})
|
||||
c = r.get("data") or {}
|
||||
check("内容列表", (c.get("total") or 0) > 0, f"total={c.get('total')}")
|
||||
check("付费标识正确", all(x.get("access") in ("free", "member", "pay") for x in (c.get("list") or [])))
|
||||
|
||||
r = call("/api/content/index", {"type": "meditation", "limit": 10})
|
||||
med = (r.get("data") or {}).get("list") or []
|
||||
locked = [x for x in med if x.get("locked")]
|
||||
check("会员内容锁定态", len(locked) >= 1, f"{len(locked)}条锁定")
|
||||
|
||||
first_id = (c.get("list") or [{}])[0].get("id")
|
||||
r = call("/api/content/detail", {"id": first_id})
|
||||
d = r.get("data") or {}
|
||||
check("内容详情", bool(d.get("body")), d.get("title"))
|
||||
check("医疗免责声明", "仅供参考" in (d.get("disclaimer") or "") or d.get("type") not in ("advice", "knowledge"))
|
||||
|
||||
r = call("/api/member/plans")
|
||||
plans = (r.get("data") or {}).get("list") or []
|
||||
check("套餐 3 档", len(plans) == 3, ",".join(p.get("code", "") for p in plans))
|
||||
check("套餐权益中文", all(p.get("benefit_texts") for p in plans))
|
||||
|
||||
r = call("/api/member/status")
|
||||
check("会员状态(非会员)", (r.get("data") or {}).get("member", {}).get("is_member") is False)
|
||||
|
||||
r = call("/api/member/order", {"plan_id": plans[1]["id"] if len(plans) > 1 else 1, "pay_type": "wechat"}, "POST")
|
||||
o = r.get("data") or {}
|
||||
check("创建订单", r.get("code") == 1 and bool(o.get("order_no")), o.get("order_no"))
|
||||
|
||||
r = call("/api/setting/index")
|
||||
st = r.get("data") or {}
|
||||
check("设置读取", "remind" in st and st.get("app_lock") in ("none", "password", "biometric"))
|
||||
|
||||
r = call("/api/setting/save", {"app_lock": "password", "app_lock_code": "1234", "local_only": 1,
|
||||
"remind_period": 1, "remind_record": 0, "remind_time": "20:30"}, "POST")
|
||||
check("设置保存", r.get("code") == 1, r.get("msg"))
|
||||
r = call("/api/setting/index")
|
||||
st2 = r.get("data") or {}
|
||||
check("设置回读生效", st2.get("app_lock") == "password" and st2.get("local_only") == 1)
|
||||
check("提醒时间生效", (st2.get("remind") or {}).get("time") == "20:30", str((st2.get("remind") or {}).get("time")))
|
||||
check("应用锁只存哈希", st2.get("has_lock_code") is True)
|
||||
|
||||
print("=" * 70)
|
||||
print("6. 个人中心")
|
||||
r = call("/api/user/detail")
|
||||
u = r.get("data") or {}
|
||||
check("资料聚合", (u.get("user") or {}).get("id") is not None and "summary" in u and "member" in u)
|
||||
check("资料昵称一致", bool((u.get("user") or {}).get("nickname")))
|
||||
r = call("/api/user/updateprofile", {"gender": 2, "birthday": "1996-05-20", "bio": "愿花期常伴"}, "POST")
|
||||
check("资料更新", r.get("code") == 1, r.get("msg"))
|
||||
|
||||
print("=" * 70)
|
||||
print(f"通过 {len(PASSED)} 项,失败 {len(FAILED)} 项")
|
||||
if FAILED:
|
||||
for f in FAILED:
|
||||
print(" ❌ " + f)
|
||||
sys.exit(1)
|
||||
print("🎉 后端全链路验证通过")
|
||||
169
scripts/verify/contract_check.py
普通文件
169
scripts/verify/contract_check.py
普通文件
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""花期 APP · 前后端契约静态校验(无需打包即可发现接口/路由/事件类错误)"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
|
||||
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))
|
||||
SERVER_API = os.path.join(ROOT, 'server/application/api/controller')
|
||||
|
||||
issues = []
|
||||
notes = []
|
||||
|
||||
|
||||
def add(msg):
|
||||
issues.append(msg)
|
||||
|
||||
|
||||
# ---------------- 1. 解析前端 api.js ----------------
|
||||
api_src = open(os.path.join(ROOT, 'utils/api.js'), encoding='utf-8').read()
|
||||
pattern = re.compile(r"(\w+):\s*(?:\([^)]*\))?\s*=>\s*request\('(/api/[\w/]+)'(?:\s*,\s*(\{[^}]*\}))?")
|
||||
endpoints = []
|
||||
for m in pattern.finditer(api_src):
|
||||
name, path, opts = m.group(1), m.group(2), m.group(3) or ''
|
||||
method = 'POST' if "'POST'" in opts.replace('"', "'") else 'GET'
|
||||
endpoints.append({'name': name, 'path': path, 'method': method})
|
||||
|
||||
print(f"[1] 前端 api.js 定义 {len(endpoints)} 个接口")
|
||||
|
||||
# ---------------- 2. 校验后端控制器方法存在 ----------------
|
||||
php_cache = {}
|
||||
for ep in endpoints:
|
||||
parts = ep['path'].strip('/').split('/') # api / controller / action
|
||||
controller, action = parts[1].capitalize(), parts[2]
|
||||
f = os.path.join(SERVER_API, controller + '.php')
|
||||
if f not in php_cache:
|
||||
php_cache[f] = open(f, encoding='utf-8').read() if os.path.exists(f) else None
|
||||
src = php_cache[f]
|
||||
if src is None:
|
||||
add(f"接口 {ep['name']} -> {ep['path']}:后端缺少控制器 {controller}.php")
|
||||
continue
|
||||
if not re.search(r'function\s+' + action + r'\s*\(', src):
|
||||
add(f"接口 {ep['name']} -> {ep['path']}:{controller}.php 缺少方法 {action}()")
|
||||
|
||||
print(f"[2] 后端控制器映射校验完成(检查 {len(php_cache)} 个控制器文件)")
|
||||
|
||||
# ---------------- 3. 页面里调用的 api.xxx 是否都已定义 ----------------
|
||||
defined = {ep['name'] for ep in endpoints}
|
||||
vue_files = []
|
||||
for dirpath, _, files in os.walk(ROOT):
|
||||
if 'node_modules' in dirpath or '/server' in dirpath or '/.git' in dirpath:
|
||||
continue
|
||||
for fn in files:
|
||||
if fn.endswith('.vue'):
|
||||
vue_files.append(os.path.join(dirpath, fn))
|
||||
|
||||
used = {}
|
||||
for f in vue_files:
|
||||
src = open(f, encoding='utf-8').read()
|
||||
for m in re.finditer(r'\bapi\.(\w+)\s*\(', src):
|
||||
used.setdefault(m.group(1), set()).add(os.path.relpath(f, ROOT))
|
||||
|
||||
for name, files in sorted(used.items()):
|
||||
if name not in defined:
|
||||
add(f"前端调用了未定义的接口 api.{name}()(使用位置:{', '.join(sorted(files))})")
|
||||
|
||||
print(f"[3] 页面接口调用校验完成({len(used)} 个被调用接口,覆盖 {len(vue_files)} 个 .vue)")
|
||||
|
||||
# ---------------- 4. pages.json 路由与文件存在性 ----------------
|
||||
pages_cfg = json.load(open(os.path.join(ROOT, 'pages.json'), encoding='utf-8'))
|
||||
for page in pages_cfg.get('pages', []):
|
||||
p = os.path.join(ROOT, page['path'] + '.vue')
|
||||
if not os.path.exists(p):
|
||||
add(f"pages.json 声明的页面不存在:{page['path']}.vue")
|
||||
print(f"[4] 路由校验完成({len(pages_cfg.get('pages', []))} 个页面)")
|
||||
|
||||
# ---------------- 5. 页面跳转目标是否在 pages.json 中 ----------------
|
||||
declared = {'/' + page['path'] for page in pages_cfg.get('pages', [])}
|
||||
for f in vue_files:
|
||||
src = open(f, encoding='utf-8').read()
|
||||
for m in re.finditer(r"url:\s*'(/pages/[\w/]+)(?:\?[^']*)?'", src):
|
||||
target = m.group(1)
|
||||
if target not in declared:
|
||||
add(f"{os.path.relpath(f, ROOT)}:跳转到未注册页面 {target}")
|
||||
|
||||
# ---------------- 6. 组件引用与文件存在性 ----------------
|
||||
for f in vue_files:
|
||||
src = open(f, encoding='utf-8').read()
|
||||
for m in re.finditer(r"from '(@/[\w\-/]+\.vue)'", src):
|
||||
rel = m.group(1).replace('@/', '')
|
||||
if not os.path.exists(os.path.join(ROOT, rel)):
|
||||
add(f"{os.path.relpath(f, ROOT)}:组件文件不存在 {rel}")
|
||||
# 模板中使用的组件是否已注册
|
||||
script = src.split('</template>')[0]
|
||||
regs = set(re.findall(r'components:\s*\{([^}]*)\}', src))
|
||||
registered = set()
|
||||
for block in regs:
|
||||
registered |= set(re.findall(r'(\w+)\s*:', block))
|
||||
# 支持 ES6 简写注册 components: { hqTabbar }
|
||||
registered |= {t.strip() for t in block.split(',') if re.fullmatch(r'\s*\w+\s*', t)}
|
||||
def camelize(name):
|
||||
parts = name.split('-')
|
||||
return parts[0] + ''.join(p.capitalize() for p in parts[1:])
|
||||
|
||||
registered_camel = {camelize(r) for r in registered}
|
||||
for tag in set(re.findall(r'<(hq-[a-z\-]+|bloom-calendar)', script)):
|
||||
if camelize(tag) not in registered_camel:
|
||||
add(f"{os.path.relpath(f, ROOT)}:模板使用 <{tag}> 但未在 components 中注册")
|
||||
|
||||
# ---------------- 7. 模板事件处理函数是否在 methods 中定义 ----------------
|
||||
HANDLER_RE = re.compile(r'@(?:tap|change|confirm|select|input|submit)="(\w+)"')
|
||||
for f in vue_files:
|
||||
src = open(f, encoding='utf-8').read()
|
||||
if '<script>' not in src:
|
||||
continue
|
||||
template = src.split('<template>', 1)[-1].split('</template>', 1)[0]
|
||||
script = src.split('<script>', 1)[-1].split('</script>', 1)[0]
|
||||
for h in set(HANDLER_RE.findall(template)):
|
||||
if not re.search(r'\b' + h + r'\s*\(', script):
|
||||
add(f"{os.path.relpath(f, ROOT)}:模板绑定的处理函数 {h}() 未定义")
|
||||
|
||||
# ---------------- 8. SFC 结构完整性 ----------------
|
||||
for f in vue_files:
|
||||
src = open(f, encoding='utf-8').read()
|
||||
blocks = ('template', 'script')
|
||||
for block in blocks:
|
||||
c_open = src.count('<' + block + '>')
|
||||
c_close = src.count('</' + block + '>')
|
||||
# App.vue 允许没有 template(uni-app 全局样式/生命周期文件)
|
||||
if os.path.basename(f) == 'App.vue' and block == 'template':
|
||||
if c_open != c_close:
|
||||
add(f"{os.path.relpath(f, ROOT)}:<template> 块异常({c_open}/{c_close})")
|
||||
continue
|
||||
if c_open != 1 or c_close != 1:
|
||||
add(f"{os.path.relpath(f, ROOT)}:<{block}> 块异常({c_open}/{c_close})")
|
||||
# 标签配对(忽略自闭合与 void 标签)
|
||||
stack = []
|
||||
void_tags = {'input', 'image', 'img', 'switch', 'br', 'hr'}
|
||||
for m in re.finditer(r'<(/?)([a-zA-Z][\w\-]*)([^>]*?)(/?)>', src):
|
||||
closing, tag, _, selfclose = m.group(1), m.group(2), m.group(3), m.group(4)
|
||||
if tag in ('template', 'script', 'style'):
|
||||
continue
|
||||
if selfclose or tag in void_tags:
|
||||
continue
|
||||
if closing:
|
||||
if stack and stack[-1] == tag:
|
||||
stack.pop()
|
||||
elif tag in stack:
|
||||
while stack and stack.pop() != tag:
|
||||
pass
|
||||
add(f"{os.path.relpath(f, ROOT)}:标签闭合顺序异常 </{tag}>")
|
||||
else:
|
||||
add(f"{os.path.relpath(f, ROOT)}:多余的闭合标签 </{tag}>")
|
||||
else:
|
||||
stack.append(tag)
|
||||
if stack:
|
||||
add(f"{os.path.relpath(f, ROOT)}:未闭合标签 {stack[-5:]}")
|
||||
|
||||
print(f"[5] 跳转/组件/事件/SFC 结构校验完成")
|
||||
|
||||
# ---------------- 输出 ----------------
|
||||
print("=" * 66)
|
||||
if issues:
|
||||
print(f"发现 {len(issues)} 个问题:")
|
||||
for i in issues:
|
||||
print(" ❌ " + i)
|
||||
sys.exit(1)
|
||||
print("✅ 前后端契约静态校验全部通过")
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as sass from 'sass'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
const ROOT = new URL('../../', import.meta.url).pathname
|
||||
const vars = fs.readFileSync(path.join(ROOT, 'uni.scss'), 'utf8')
|
||||
const files = []
|
||||
function walk(dir) {
|
||||
for (const f of fs.readdirSync(dir)) {
|
||||
const p = path.join(dir, f)
|
||||
const st = fs.statSync(p)
|
||||
if (st.isDirectory()) {
|
||||
if (['node_modules', 'server', '.git', 'unpackage'].includes(f)) continue
|
||||
walk(p)
|
||||
} else if (f.endsWith('.vue')) files.push(p)
|
||||
}
|
||||
}
|
||||
walk(ROOT)
|
||||
|
||||
let ok = 0
|
||||
const errors = []
|
||||
for (const file of files) {
|
||||
const rel = path.relative(ROOT, file)
|
||||
const src = fs.readFileSync(file, 'utf8')
|
||||
const m = src.match(/<style[^>]*lang="scss"[^>]*>([\s\S]*?)<\/style>/)
|
||||
if (!m) continue
|
||||
try {
|
||||
sass.compileString(vars + '\n' + m[1], { style: 'expanded', logger: sass.Logger.silent })
|
||||
ok++
|
||||
} catch (e) {
|
||||
errors.push(`${rel}: ${e.message.split('\n').slice(0, 2).join(' ')}`)
|
||||
}
|
||||
}
|
||||
console.log(`SCSS 编译通过 ${ok} 个样式块`)
|
||||
for (const e of errors) console.log(' ❌ ' + e)
|
||||
process.exit(errors.length ? 1 : 0)
|
||||
@@ -0,0 +1,53 @@
|
||||
import { parse, compileTemplate, compileScript } from '@vue/compiler-sfc'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
const ROOT = new URL('../../', import.meta.url).pathname
|
||||
const files = []
|
||||
function walk(dir) {
|
||||
for (const f of fs.readdirSync(dir)) {
|
||||
const p = path.join(dir, f)
|
||||
const st = fs.statSync(p)
|
||||
if (st.isDirectory()) {
|
||||
if (['node_modules', 'server', '.git', 'unpackage'].includes(f)) continue
|
||||
walk(p)
|
||||
} else if (f.endsWith('.vue')) files.push(p)
|
||||
}
|
||||
}
|
||||
walk(ROOT)
|
||||
|
||||
let ok = 0
|
||||
const errors = []
|
||||
for (const file of files) {
|
||||
const rel = path.relative(ROOT, file)
|
||||
const source = fs.readFileSync(file, 'utf8')
|
||||
try {
|
||||
const { descriptor, errors: parseErrors } = parse(source, { filename: file })
|
||||
if (parseErrors.length) {
|
||||
errors.push(`${rel}: SFC parse -> ${parseErrors[0].message}`)
|
||||
continue
|
||||
}
|
||||
if (descriptor.template) {
|
||||
const res = compileTemplate({
|
||||
source: descriptor.template.content,
|
||||
filename: file,
|
||||
id: rel,
|
||||
compilerOptions: { isCustomElement: (tag) => true }
|
||||
})
|
||||
if (res.errors && res.errors.length) {
|
||||
const e = res.errors[0]
|
||||
errors.push(`${rel}: template -> ${typeof e === 'string' ? e : e.message}`)
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (descriptor.script) {
|
||||
compileScript(descriptor, { id: rel })
|
||||
}
|
||||
ok++
|
||||
} catch (e) {
|
||||
errors.push(`${rel}: ${e.message.split('\n')[0]}`)
|
||||
}
|
||||
}
|
||||
console.log(`Vue SFC 编译通过 ${ok}/${files.length}`)
|
||||
for (const e of errors) console.log(' ❌ ' + e)
|
||||
process.exit(errors.length ? 1 : 0)
|
||||
在新工单中引用
屏蔽一个用户