Initial commit

This commit is contained in:
admin
2025-12-08 14:39:07 +08:00
commit 9d4f78656b
782 changed files with 66418 additions and 0 deletions

View File

@@ -0,0 +1,82 @@
/**
* @fileoverview 配置文件
*/
module.exports = {
/**
* @description 需要的插件列表
*/
plugins: [
// 按需打开注释即可
// 'audio', // 音乐播放器
// 'editable', // 内容编辑
// 'emoji', // 小表情
// 'highlight', // 代码高亮
// 'markdown', // 解析 md
// 'latex', // 解析 latex
// 'search', // 关键词搜索
// 'style', // 解析 style 标签
// 'txv-video', // 使用腾讯视频
// 'img-cache' // 图片缓存
// 'card', // 卡片展示
],
/**
* @description 要引入到组件中的外部样式css
* 仅支持标签名和 class 选择器
*/
externStyle: '',
/**
* @description 要引入到模板中的自定义标签ad 等)
* 每个标签为一个 object包含 name标签名必要、attrs属性列表非必要、platforms需要添加的平台非必要
*/
customElements: [
/*
// 需要使用广告标签则打开此注释
{
name: 'ad',
attrs: ['unit-id']
}
*/
],
/**
* @description babel 配置es6 转 es5
* @tutorial https://babeljs.io/docs/usage/options/
*/
babel: {
presets: ['@babel/env']
},
/**
* @description js 压缩配置
* @tutorial https://www.npmjs.com/package/uglify-js#minify-options
*/
uglify: {
mangle: {
toplevel: true
},
output: {
comments: /^!/
}
},
/**
* @description html 压缩配置
* @tutorial https://github.com/kangax/html-minifier#options-quick-reference
*/
htmlmin: {
caseSensitive: true,
collapseWhitespace: true,
removeComments: true,
keepClosingSlash: true
},
/**
* @description css 压缩配置
* @tutorial https://github.com/jakubpawlowicz/clean-css#constructor-options
*/
cleanCss: {
}
}

View File

@@ -0,0 +1,205 @@
/**
* @fileoverview 将微信端的代码转换到各个平台
*/
const through2 = require('through2')
// api 前缀
const prefix = {
weixin: {
wxml: 'wx:',
js: 'wx.'
},
qq: {
wxml: 'qq:',
js: 'qq.'
},
baidu: {
wxml: 's-',
js: 'swan.'
},
alipay: {
wxml: 'a:',
js: 'my.'
},
toutiao: {
wxml: 'tt:',
js: 'tt.'
}
}
// 文件名后缀
const suffix = {
weixin: {
wxml: '.wxml',
wxss: '.wxss'
},
qq: {
wxml: '.qml',
wxss: '.qss'
},
baidu: {
wxml: '.swan',
wxss: '.css'
},
alipay: {
wxml: '.axml',
wxss: '.acss'
},
toutiao: {
wxml: '.ttml',
wxss: '.ttss'
}
}
/**
* @description 取出两个括号之间的内容
* @param {string} content 总内容
* @param {number} i 开始位置
*/
function getSection (content, i) {
let j = i + 1
let num = 1
const start = content[i]
const end = start === '(' ? ')' : '}'
while (num) {
if (content[j] === start) {
num++
} else if (content[j] === end) {
num--
}
j++
}
return content.substring(i, j)
}
/**
* @description 处理不同小程序平台间的差异
* @param {string} platform 使用平台
*/
module.exports = function (platform) {
if (platform !== 'uni-app') {
platform = platform.split('-')[1]
}
return through2.obj(function (file, _, callback) {
if (file.isBuffer()) {
let content = file.contents.toString()
if (platform === 'uni-app') {
if (file.extname === '.js') {
content = content.replace(/\.properties/g, '')
}
} else {
// wxml 文件处理
if (file.extname === '.wxml') {
content = content.replace(/wx:/g, prefix[platform].wxml) // 替换 api 前缀
file.extname = suffix[platform].wxml // 修改后缀名
if (platform === 'qq') {
// wxs 转为 qs
content = content.replace(/<wxs/g, '<qs').replace(/<\/wxs/g, '</qs')
} else if (platform === 'baidu') {
content = content.replace(/s-if=['"]{{(\S+)}}['"]/g, 's-if="$1"') // s-if 和 s-for 后不加 {{}}
.replace(/s-for=['"]{{(\S+)}}['"]/g, 's-for="$1"')
.replace(/data="(.*?)"/g, 'data="{$1}"')
} else if (platform === 'alipay') {
content = content.replace('block-size', 'handle-size')
.replace(/longpress/g, 'longTap')
.replace(/bind([\S])/g, (_, $1) => { // bindevent 转为 onEvent
return 'on' + $1.toUpperCase()
}).replace(/catch([\S])/g, (_, $1) => { // catchevent 转为 catchEvent
return 'catch' + $1.toUpperCase()
})
}
} else if (file.extname === '.js') {
// js 文件处理
// 替换 api 前缀
content = content.replace(/wx\./g, prefix[platform].js)
// 支付宝格式转换
if (platform === 'alipay') {
// 将 aa.triggerEvent('bb', cc) 替换为 aa.props.onBb && aa.props.onBb(cc)
content = content.replace(/([a-zA-Z0-9._]+).triggerEvent\(['"](\S+?)['"],*/g, function (_, $1, $2) {
const method = `${$1}.props.on${$2[0].toUpperCase()}${$2.slice(1)}`
return `${method}&&${method}(`
})
// 转换 showToast
let i = content.indexOf('.showToast')
while (i !== -1) {
i += 10
const section = getSection(content, i)
content = content.substr(0, i) + section.replace('title', 'content') + content.substr(i + section.length)
i = content.indexOf('.showToast', i)
}
// 转换 showActionSheet
i = content.indexOf('.showActionSheet')
while (i !== -1) {
i += 16
const section = getSection(content, i)
content = content.substr(0, i) + section.replace('itemList', 'items') + content.substr(i + section.length)
i = content.indexOf('.showActionSheet', i)
}
// 转换 setClipboardData
i = content.indexOf('.setClipboardData')
while (i !== -1) {
i += 17
const section = getSection(content, i)
content = content.substr(0, i - 4) + section.replace('data', 'text') + content.substr(i + section.length)
i = content.indexOf('.setClipboardData', i)
}
// 组件格式转换
if (content.includes('Component({')) {
// 替换生命周期
content = content.replace('created:', 'didMount:')
.replace('attached:', 'didMount:')
.replace('detached:', 'didUnmount:')
// 将 properties 字段转为 props 格式
i = content.indexOf('{', content.indexOf('properties:'))
let props
let propsStr = '{'
const objStr = getSection(content, i)
// 取出整个 properties 字段
eval('props = ' + objStr) // eslint-disable-line
for (const item in props) {
if (!props[item]) continue
propsStr += item + ':'
if (props[item].value) {
// 设置了默认值
if (typeof props[item].value === 'boolean') {
propsStr += props[item].value ? '!0' : '!1'
} else {
propsStr += props[item].value
}
} else {
// 没有设置默认值
const type = props[item].type || props[item]
if (type === String) {
propsStr += '""'
} else if (type === Boolean) {
propsStr += '!1'
} else if (type === Number) {
propsStr += '0'
} else if (type === Object) {
propsStr += '{}'
} else if (type === Array) {
propsStr += '[]'
}
}
propsStr += ','
}
content = content.substr(0, i) + propsStr.substring(0, propsStr.length - 1) + '}' + content.substr(i + objStr.length)
}
content = content.replace(/properties/g, 'props')
.replace(/\.setNavigationBarTitle/g, '.setNavigationBar')
} else {
content = content.replace(/\.properties/g, '.data')
}
} else if (file.extname === '.wxss') {
// wxss 文件处理
file.extname = suffix[platform].wxss // 修改后缀名
}
}
file.contents = Buffer.from(content)
}
this.push(file)
callback()
})
}

View File

@@ -0,0 +1 @@
App({})

View File

@@ -0,0 +1,13 @@
{
"pages":[
"pages/index/index",
"pages/jump/jump"
],
"window":{
"backgroundTextStyle":"light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "mp-html",
"navigationBarTextStyle":"black"
},
"style": "v2"
}

View File

@@ -0,0 +1,32 @@
const html = require('../../content')
Page({
data: {
html: '',
tagStyle: {
table: 'box-sizing: border-box; border-top: 1px solid #dfe2e5; border-left: 1px solid #dfe2e5;',
th: 'border-right: 1px solid #dfe2e5; border-bottom: 1px solid #dfe2e5;',
td: 'border-right: 1px solid #dfe2e5; border-bottom: 1px solid #dfe2e5;',
li: 'margin: 5px 0;'
}
},
onLoad () {
// 模拟网络请求
setTimeout(() => {
this.setData({
html
})
}, 200)
},
load () {
console.log('dom 树加载完毕')
},
ready (e) {
console.log('ready 事件触发:', e)
},
imgtap (e) {
console.log('imgtap 事件触发:', e)
},
linktap (e) {
console.log('linktap 事件触发:', e)
}
})

View File

@@ -0,0 +1,5 @@
{
"usingComponents": {
"mp-html": "/components/mp-html/index"
}
}

View File

@@ -0,0 +1,3 @@
<mp-html container-style="padding:20px" content="{{html}}" domain="https://mp-html.oss-cn-hangzhou.aliyuncs.com" lazy-load scroll-table selectable use-anchor tag-style="{{tagStyle}}" bindload="load" bindready="ready" bindimgtap="imgtap" bindlinktap="linktap">
加载中...
</mp-html>

View File

@@ -0,0 +1 @@
Page({})

View File

@@ -0,0 +1 @@
{}

View File

@@ -0,0 +1 @@
<view>跳转测试页面</view>

View File

@@ -0,0 +1,13 @@
{
"description": "项目配置文件",
"setting": {
"urlCheck": true,
"es6": true,
"postcss": true,
"minified": true,
"newFeature": true
},
"compileType": "miniprogram",
"appid": "touristappid",
"projectname": "mp-html"
}

View File

@@ -0,0 +1,6 @@
<script>
export default {}
</script>
<style>
</style>

View File

@@ -0,0 +1,194 @@
## 为减小组件包的大小默认组件包中不包含编辑、latex 公式等扩展功能,需要使用扩展功能的请参考下方的 插件扩展 栏的说明
## 功能介绍
- 全端支持(含 `v3、NVUE`
- 支持丰富的标签(包括 `table``video``svg` 等)
- 支持丰富的事件效果(自动预览图片、链接处理等)
- 支持设置占位图(加载中、出错时、预览时)
- 支持锚点跳转、长按复制等丰富功能
- 支持大部分 *html* 实体
- 丰富的插件(关键词搜索、内容编辑、`latex` 公式等)
- 效率高、容错性强且轻量化
查看 [功能介绍](https://jin-yufeng.github.io/mp-html/#/overview/feature) 了解更多
## 使用方法
- `uni_modules` 方式
1. 点击右上角的 `使用 HBuilder X 导入插件` 按钮直接导入项目或点击 `下载插件 ZIP` 按钮下载插件包并解压到项目的 `uni_modules/mp-html` 目录下
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<!-- 不需要引入,可直接使用 -->
<mp-html :content="html" />
```
```javascript
export default {
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
3. 需要更新版本时在 `HBuilder X` 中右键 `uni_modules/mp-html` 目录选择 `从插件市场更新` 即可
- 源码方式
1. 从 [github](https://github.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 或 [gitee](https://gitee.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 下载源码
插件市场的 **非 uni_modules 版本** 无法更新,不建议从插件市场获取
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<mp-html :content="html" />
```
```javascript
import mpHtml from '@/components/mp-html/mp-html'
export default {
// HBuilderX 2.5.5+ 可以通过 easycom 自动引入
components: {
mpHtml
},
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
- npm 方式
1. 在项目根目录下执行
```bash
npm install mp-html
```
2. 在需要使用页面的 `(n)vue` 文件中添加
```html
<mp-html :content="html" />
```
```javascript
import mpHtml from 'mp-html/dist/uni-app/components/mp-html/mp-html'
export default {
// 不可省略
components: {
mpHtml
},
data() {
return {
html: '<div>Hello World!</div>'
}
}
}
```
3. 需要更新版本时执行以下命令即可
```bash
npm update mp-html
```
使用 *cli* 方式运行的项目,通过 *npm* 方式引入时,需要在 *vue.config.js* 中配置 *transpileDependencies*,详情可见 [#330](https://github.com/jin-yufeng/mp-html/issues/330#issuecomment-913617687)
如果在 **nvue** 中使用还要将 `dist/uni-app/static` 目录下的内容拷贝到项目的 `static` 目录下,否则无法运行
查看 [快速开始](https://jin-yufeng.github.io/mp-html/#/overview/quickstart) 了解更多
## 组件属性
| 属性 | 类型 | 默认值 | 说明 |
|:---:|:---:|:---:|---|
| container-style | String | | 容器的样式([2.1.0+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v210) |
| content | String | | 用于渲染的 html 字符串 |
| copy-link | Boolean | true | 是否允许外部链接被点击时自动复制 |
| domain | String | | 主域名(用于链接拼接) |
| error-img | String | | 图片出错时的占位图链接 |
| lazy-load | Boolean | false | 是否开启图片懒加载 |
| loading-img | String | | 图片加载过程中的占位图链接 |
| pause-video | Boolean | true | 是否在播放一个视频时自动暂停其他视频 |
| preview-img | Boolean | true | 是否允许图片被点击时自动预览 |
| scroll-table | Boolean | false | 是否给每个表格添加一个滚动层使其能单独横向滚动 |
| selectable | Boolean | false | 是否开启文本长按复制 |
| set-title | Boolean | true | 是否将 title 标签的内容设置到页面标题 |
| show-img-menu | Boolean | true | 是否允许图片被长按时显示菜单 |
| tag-style | Object | | 设置标签的默认样式 |
| use-anchor | Boolean | false | 是否使用锚点链接 |
查看 [属性](https://jin-yufeng.github.io/mp-html/#/basic/prop) 了解更多
## 组件事件
| 名称 | 触发时机 |
|:---:|---|
| load | dom 树加载完毕时 |
| ready | 图片加载完毕时 |
| error | 发生渲染错误时 |
| imgtap | 图片被点击时 |
| linktap | 链接被点击时 |
| play | 音视频播放时 |
查看 [事件](https://jin-yufeng.github.io/mp-html/#/basic/event) 了解更多
## api
组件实例上提供了一些 `api` 方法可供调用
| 名称 | 作用 |
|:---:|---|
| in | 将锚点跳转的范围限定在一个 scroll-view 内 |
| navigateTo | 锚点跳转 |
| getText | 获取文本内容 |
| getRect | 获取富文本内容的位置和大小 |
| setContent | 设置富文本内容 |
| imgList | 获取所有图片的数组 |
| pauseMedia | 暂停播放音视频([2.2.2+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v222) |
| setPlaybackRate | 设置音视频播放速率([2.4.0+](https://jin-yufeng.github.io/mp-html/#/changelog/changelog#v240) |
查看 [api](https://jin-yufeng.github.io/mp-html/#/advanced/api) 了解更多
## 插件扩展
除基本功能外,本组件还提供了丰富的扩展,可按照需要选用
| 名称 | 作用 |
|:---:|---|
| audio | 音乐播放器 |
| editable | 富文本 **编辑**[示例项目](https://mp-html.oss-cn-hangzhou.aliyuncs.com/editable.zip) |
| emoji | 解析 emoji |
| highlight | 代码块高亮显示 |
| markdown | 渲染 markdown |
| search | 关键词搜索 |
| style | 匹配 style 标签中的样式 |
| txv-video | 使用腾讯视频 |
| img-cache | 图片缓存 by [@PentaTea](https://github.com/PentaTea) |
| latex | 渲染 latex 公式 by [@Zeng-J](https://github.com/Zeng-J) |
从插件市场导入的包中 **不含有** 扩展插件,使用插件需通过微信小程序 `富文本插件` 获取或参考以下方法进行打包:
1. 获取完整组件包
```bash
npm install mp-html
```
2. 编辑 `tools/config.js` 中的 `plugins` 项,选择需要的插件
3. 生成新的组件包
在 `node_modules/mp-html` 目录下执行
```bash
npm install
npm run build:uni-app
```
4. 拷贝 `dist/uni-app` 中的内容到项目根目录
查看 [插件](https://jin-yufeng.github.io/mp-html/#/advanced/plugin) 了解更多
## 关于 nvue
`nvue` 使用原生渲染,不支持部分 `css` 样式,为实现和 `html` 相同的效果,组件内部通过 `web-view` 进行渲染,性能上差于原生,根据 `weex` 官方建议,`web` 标签仅应用在非常规的降级场景。因此,如果通过原生的方式(如 `richtext`)能够满足需要,则不建议使用本组件,如果有较多的富文本内容,则可以直接使用 `vue` 页面
由于渲染方式与其他端不同,有以下限制:
1. 不支持 `lazy-load` 属性
2. 视频不支持全屏播放
3. 如果在 `flex-direction: row` 的容器中使用,需要给组件设置宽度或设置 `flex: 1` 占满剩余宽度
纯 `nvue` 模式下,[此问题](https://ask.dcloud.net.cn/question/119678) 修复前,不支持通过 `uni_modules` 引入,需要本地引入(将 [dist/uni-app](https://github.com/jin-yufeng/mp-html/tree/master/dist/uni-app) 中的内容拷贝到项目根目录下)
## 立即体验
![富文本插件](https://mp-html.oss-cn-hangzhou.aliyuncs.com/qrcode.jpg)
## 问题反馈
遇到问题时,请先查阅 [常见问题](https://jin-yufeng.github.io/mp-html/#/question/faq) 和 [issue](https://github.com/jin-yufeng/mp-html/issues) 中是否已有相同的问题
可通过 [issue](https://github.com/jin-yufeng/mp-html/issues/new/choose) 、插件问答或发送邮件到 [mp_html@126.com](mailto:mp_html@126.com) 提问,不建议在评论区提问(不方便回复)
提问请严格按照 [issue 模板](https://github.com/jin-yufeng/mp-html/issues/new/choose) ,描述清楚使用环境、`html` 内容或可复现的 `demo` 项目以及复现方式,对于 **描述不清**、**无法复现** 或重复的问题将不予回复
欢迎加入 `QQ` 交流群:
群1已满`699734691`
群2已满`778239129`
群3`960265313`
查看 [问题反馈](https://jin-yufeng.github.io/mp-html/#/question/feedback) 了解更多

View File

@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0" />
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>

View File

@@ -0,0 +1,21 @@
import App from './App'
// #ifndef VUE3
import Vue from 'vue' // eslint-disable-line
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue' // eslint-disable-line
export function createApp () {
const app = createSSRApp(App)
return {
app
}
}
// #endif

View File

@@ -0,0 +1,45 @@
{
"name" : "mp-html",
"appid" : "",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
"transformPx" : false,
"app-plus" : {
"usingComponents" : true,
"nvueCompiler" : "uni-app",
"compilerVersion" : 3,
"splashscreen" : {
"alwaysShowBeforeRender" : true,
"waiting" : true,
"autoclose" : true,
"delay" : 0
},
"modules" : {},
"distribute" : {
"android" : {},
"ios" : {},
"sdkConfigs" : {}
}
},
"quickapp" : {},
"mp-weixin" : {
"appid" : "",
"setting" : {
"urlCheck" : false
},
"usingComponents" : true
},
"mp-alipay" : {
"usingComponents" : true
},
"mp-baidu" : {
"usingComponents" : true
},
"mp-toutiao" : {
"usingComponents" : true
},
"uniStatistics": {
"enable": false
}
}

View File

@@ -0,0 +1,16 @@
{
"pages": [
{
"path": "pages/index/index"
},
{
"path": "pages/jump/jump"
}
],
"globalStyle": {
"navigationBarTextStyle": "black",
"navigationBarTitleText": "mp-html",
"navigationBarBackgroundColor": "#F8F8F8",
"backgroundColor": "#F8F8F8"
}
}

View File

@@ -0,0 +1,52 @@
<template>
<view>
<mp-html container-style="padding:20px" :content="html" domain="https://mp-html.oss-cn-hangzhou.aliyuncs.com" lazy-load scroll-table selectable use-anchor :tag-style="tagStyle" @load="load" @ready="ready" @imgtap="imgtap" @linktap="linktap" />
</view>
</template>
<script>
// 需要测试 nvue 时,将本文件后缀改为 .nvue 即可
// 注意:此示例不包含编辑功能
import mpHtml from '@/components/mp-html/mp-html'
import html from '../../content'
export default {
// HBuilderX 2.5.5+ 可以通过 easycom 自动引入
components: {
mpHtml
},
data () {
return {
html: '',
tagStyle: {
table: 'box-sizing: border-box; border-top: 1px solid #dfe2e5; border-left: 1px solid #dfe2e5;',
th: 'border-right: 1px solid #dfe2e5; border-bottom: 1px solid #dfe2e5;',
td: 'border-right: 1px solid #dfe2e5; border-bottom: 1px solid #dfe2e5;',
li: 'margin: 5px 0;'
}
}
},
onLoad () {
// 模拟网络请求
setTimeout(() => {
this.html = html
}, 200)
},
methods: {
load () {
console.log('dom 树加载完毕')
},
ready (e) {
console.log('ready 事件触发:', e)
},
imgtap (e) {
console.log('imgtap 事件触发:', e)
},
linktap (e) {
console.log('linktap 事件触发:', e)
}
}
}
</script>
<style>
</style>

View File

@@ -0,0 +1,12 @@
<template>
<view>
跳转测试页面
</view>
</template>
<script>
export default {}
</script>
<style>
</style>

115
wechat-mini-program/node_modules/mp-html/tools/ifdef.js generated vendored Normal file
View File

@@ -0,0 +1,115 @@
/**
* @fileoverview 条件编译
*/
const through2 = require('through2')
/**
* @description 条件编译
* @param {string} platform 平台
*/
module.exports = function (platform) {
return through2.obj(function (file, _, callback) {
if (file.isBuffer()) {
// 文件夹级别的处理
if (file.relative.includes('miniprogram')) {
if (platform !== 'uni-app') {
// 去掉这一层
file.path = file.path.replace(/(.*)[/\\]miniprogram/, '$1')
} else {
// 不用于本平台的文件
callback()
return
}
} else if (file.relative.includes('uni-app')) {
if (platform === 'uni-app') {
file.path = file.path.replace(/(.*)[/\\]uni-app/, '$1')
} else {
callback()
return
}
}
if (platform === 'uni-app') {
// uni-app 平台 vue3 要求使用 es6 模块
let content = file.contents.toString()
if (file.basename === 'prism.min.js') {
content = content.replace('"undefined"!=typeof module&&module.exports&&(module.exports=Prism),', 'export default Prism;')
} else if (file.extname === '.js' && !file.relative.includes('static')) {
content = content.replace(/module.exports\s*=\s*/, 'export default ')
.replace(/const\s+([^\s=]+)\s*=\s*require\(([^)]+)\)/g, 'import $1 from $2')
}
file.contents = Buffer.from(content)
} else {
// 小程序平台进行进一步处理
let content = file.contents.toString()
/**
* 方式1
* 在注释 #if(n)def xxx 和 #endif 之间的内容会根据是否定义 xxx 决定是否保留
*/
const commentReg = /\/\*[\s\S]*?\*\/|\/\/[^\n]*|<!--[\s\S]*?-->/g // 提取所有注释
const copy = content // 拷贝一个副本用于搜索
let match = commentReg.exec(copy)
const stack = []
while (match) {
if (match[0].includes('#if')) {
stack.push([match[0], match.index])
} else if (match[0].includes('#endif')) {
const item = stack.pop()
if (!item) {
throw Error('条件编译错误:存在多余的 #endifpath:' + file.path + 'content: ' + content.substr(match.index, 100))
}
const def = item[0].match(/MP-[A-Z]+/gi) || [] // 取出定义条件
let hit = false
for (let i = 0; i < def.length; i++) {
if (def[i] && platform === def[i].toLowerCase()) {
hit = true // 命中
break
}
}
// 不匹配
if ((item[0].includes('#ifdef') && !hit) || (item[0].includes('#ifndef') && hit)) {
let fill = ''
// 用空格填充
for (let j = item[1] + item[0].length; j < match.index; j++) {
if (content[j] === '\n') {
fill += '\n'
} else {
fill += ' '
}
}
content = content.substr(0, item[1] + item[0].length) + fill + content.substr(match.index)
}
}
match = commentReg.exec(copy)
}
if (stack.length) {
throw Error('条件编译错误:存在未闭合的 #ifdefpath:' + file.path + 'content: ' + content.substr(stack[0][1], 100))
}
/**
* 方式2
* wxml 中属性前加平台名将仅编译到该平台,如 mp-weixin:attr
*/
if (file.extname === '.wxml') {
content = content.replace(/([^:\s]+:[^=\s]+)\s*=\s*"(.*?)"/g, ($, $1, $2) => {
const platforms = $1.split(':')
let name = platforms.pop()
const last = platforms[platforms.length - 1]
if (last && !last.includes('mp')) {
name = platforms.pop() + ':' + name
}
if (!platforms.length) return $
let i
for (i = platforms.length; i--;) {
if (platform === platforms[i].toLowerCase()) break
}
if (i >= 0) return `${name}="${$2}"`
return ''
})
}
file.contents = Buffer.from(content)
}
}
this.push(file)
callback()
})
}

View File

@@ -0,0 +1,40 @@
const uglify = require('uglify-js')
const through2 = require('through2')
/**
* @description 压缩内联 wxs 脚本
*/
function wxs () {
return through2.obj(function (file, _, callback) {
if (file.isBuffer()) {
file.contents = Buffer.from(file.contents.toString().replace(/<wxs(.*?)>([\s\S]+?)<\/wxs>/, (_, $1, $2) => {
return `<wxs${$1}>${uglify.minify($2, {
fromString: true,
mangle: {
toplevel: true
}
}).code}</wxs>`
}))
}
this.push(file)
callback()
})
}
/**
* @description 压缩 json 文件
*/
function json () {
return through2.obj(function (file, _, callback) {
if (file.isBuffer()) {
file.contents = Buffer.from(JSON.stringify(JSON.parse(file.contents.toString())))
}
this.push(file)
callback()
})
}
module.exports = {
wxs,
json
}

View File

@@ -0,0 +1,248 @@
/**
* @fileoverview 处理插件
*/
const path = require('path')
const through2 = require('through2')
const config = require('./config')
config.plugins.sort((a, b) => {
// editable 置于最后面
if (a === 'editable') return 1
if (b === 'editable') return -1
// markdown 置于最前面
if (a === 'markdown') return -1
if (b === 'markdown') return 1
// 剩余任意顺序
return 0
})
// 提取和替换标签名选择器(组件中仅支持 class 选择器)
const tagSelector = {}
let tagI = 0
if (config.externStyle) {
config.externStyle = config.externStyle.replace(/[^,\s}]+(?=[^}]*{)/g, $ => {
if (!/[a-zA-Z_]/.test($[0])) return $
if (tagSelector[$]) return '.' + tagSelector[$]
tagSelector[$] = '_' + tagI++
return '.' + tagSelector[$]
})
}
module.exports = {
/**
* @description 构建插件
* @param {string} platform 使用平台
*/
build (platform) {
const builds = {} // 构建模块
let pluginImports = '' // 插件引入
let plugins = '' // 插件列表
let voidTags = '' // 增加的自闭合标签
let wxml = '' // 要引入到 node.wxml 中的内容
let js = '' // 要引入到 node.js 中的内容
let wxss = config.externStyle // 要引入到 node.wxss 中的内容
const json = {} // 要引入到 node.json 中的内容
// 收集插件中要写入模板文件的内容
for (let i = 0; i < config.plugins.length; i++) {
const plugin = config.plugins[i]
let build = {}
try {
// 专用 build
if (platform === 'uni-app') {
build = require(`../plugins/${plugin}/uni-app/build.js`)
} else {
build = require(`../plugins/${plugin}/miniprogram/build.js`)
}
} catch (e) { }
try {
// 通用 build
build = Object.assign(require(`../plugins/${plugin}/build.js`), build)
} catch (e) { }
// 可以在当前平台使用
if (!build.platform || build.platform.includes(platform)) {
builds[plugin] = build
if (platform === 'uni-app') {
plugins += plugin.replace(/-([a-z])/g, ($, $1) => $1.toUpperCase()) + ','
pluginImports += `import ${plugin.replace(/-([a-z])/g, ($, $1) => $1.toUpperCase())} from './${plugin}/${build.main ? build.main : 'index.js'}'\n`
} else {
plugins += `require('./${plugin}/${build.main ? build.main : 'index.js'}'),`
}
if (build.template) {
wxml += build.template.replace('wx:if', 'wx:elif').replace('v-if', 'v-else-if')
}
if (build.methods) {
for (const method in build.methods) {
js += build.methods[method].toString() + ','
}
}
if (build.usingComponents) {
Object.assign(json, build.usingComponents)
}
if (build.style) {
wxss += build.style
}
}
}
// 加入其他自定义标签
for (const item of config.customElements) {
if (platform === 'uni-app') {
if (item.platforms) {
wxml += '<!-- #ifdef ' + item.platforms.join(' || ').toUpperCase() + ' -->'
}
voidTags += item.name + ','
wxml += '<' + item.name + ' v-else-if="n.name==\'' + item.name + '\'" :class="n.attrs.class" :style="n.attrs.style"'
if (item.attrs) {
for (const attr of item.attrs) {
wxml += ' :' + attr + '="n.attrs'
if (attr.includes('-')) {
wxml += '[\'' + attr + '\']"'
} else {
wxml += '.' + attr + '"'
}
}
}
wxml += ' />'
if (item.platforms) {
wxml += '<!-- #endif -->'
}
} else if (!item.platforms || item.platforms.join(',').toLowerCase().includes(platform)) {
voidTags += item.name + ','
wxml += '<' + item.name + ' wx:elif="{{n.name==\'' + item.name + '\'}}" class="{{n.attrs.class}}" style="{{n.attrs.style}}"'
if (item.attrs) {
for (const attr of item.attrs) {
wxml += ' ' + attr + '="{{n.attrs'
if (attr.includes('-')) {
wxml += '[\'' + attr + '\']}}"'
} else {
wxml += '.' + attr + '}}"'
}
}
}
wxml += ' />'
}
}
return through2.obj(function (file, _, callback) {
if (file.isBuffer()) {
// src 目录
if (file.base.includes('src')) {
let content = file.contents.toString()
if (file.basename === 'index.js' || file.basename === 'mp-html.vue') {
// 注册插件列表
if (platform === 'uni-app') {
content = content.replace(/const\s*plugins\s*=\s*\[\]/, `${pluginImports}const plugins=[${plugins}]`)
} else {
content = content.replace(/plugins\s*=\s*\[\]/, `plugins=[${plugins}]`)
}
} else if (file.basename === 'parser.js') {
// 设置标签名选择器
content = content.replace(/tagSelector\s*=\s*{}/, `tagSelector=${JSON.stringify(tagSelector)}`)
// 设置自闭合标签
.replace(/voidTags\s*:\s*makeMap\('/, 'voidTags: makeMap(\'' + voidTags)
} else if (file.basename === 'node.wxml') {
// 引入模板
content = content.replace(/<!--\s*insert\s*-->/, wxml)
} else if (file.basename === 'node.js') {
// 引入方法
content = content.replace(/methods\s*:\s*{/, 'methods:{' + js)
} else if (file.basename === 'node.wxss') {
// 引入样式
content = wxss + content
} else if (file.basename === 'node.json') {
// 引入组件声明
const comps = JSON.stringify(json).slice(1, -1)
if (comps) {
content = content.replace(/"usingComponents"\s*:\s*{/, '"usingComponents":{' + comps + ',')
}
} else if (file.basename === 'node.vue') {
// 引入 vue
content = content.replace(/<!--\s*insert\s*-->/, wxml)
.replace(/methods\s*:\s*{/, 'methods:{' + js)
.replace('<style>', '<style>' + wxss.replace(/\.[a-zA-Z_][^)}]*?[{,]/g, '/deep/ $&')).replace(/,url/g, ', url')
let importComp = ''
let comps = ''
for (let item in json) {
const val = json[item]
// 插件无法通过这种方式引入
if (val.includes('plugin://')) continue
item = item.replace(/-([a-z])/g, (_, $1) => $1.toUpperCase())
importComp += 'import ' + item + " from '" + val + "'\n"
comps += item + ',\n'
}
content = content.replace('<script>', '<script>\n' + importComp)
.replace(/components\s*:\s*{/, 'components: {\n' + comps)
} else if (file.basename === 'local.html' && wxss) {
// 引入样式
content = '<style>' + wxss + '</style>' + content
}
file.contents = Buffer.from(content)
for (const item in builds) {
if (builds[item].handler) {
builds[item].handler(file, platform)
}
}
} else {
// plugins 目录
const name = file.relative.split(path.sep)[0]
const build = builds[name]
// 本平台不支持使用
if (!build || file.extname === '.md' || file.basename === 'build.js') {
callback()
return
}
// import
if (build.import) {
if (typeof build.import === 'string') {
if (file.relative.includes(build.import)) {
file.import = true
}
} else {
for (let i = 0; i < build.import.length; i++) {
if (file.relative.includes(build.import[i])) {
file.import = true
break
}
}
}
}
if (build.handler) {
build.handler(file, platform)
}
}
}
this.push(file)
callback()
})
},
/**
* @description 引入样式文件到 node.wxss 中
*/
importCss () {
let css = ''
return through2.obj(function (file, _, callback) {
if (file.isBuffer()) {
let content = file.contents.toString()
// 要被引入的文件
if (file.import) {
css += content
callback()
return
}
// 引入到对应位置
if (file.basename === 'node.wxss') {
content = css + content
} else if (file.basename === 'node.vue') {
content = content.replace('<style>', '<style>' + css.replace(/\.[a-z_][^)}]+?[{,]/g, '/deep/ $&')).replace(/,url/g, ', url')
} else if (file.basename === 'local.html' && css) {
content = '<style>' + css + '</style>' + content
}
file.contents = Buffer.from(content)
}
this.push(file)
callback()
})
}
}