diff --git a/packages/omi-cloudbase/.editorconfig b/packages/omi-cloudbase/.editorconfig new file mode 100644 index 000000000..5760be583 --- /dev/null +++ b/packages/omi-cloudbase/.editorconfig @@ -0,0 +1,12 @@ +# http://editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false diff --git a/packages/omi-cloudbase/.eslintrc b/packages/omi-cloudbase/.eslintrc new file mode 100644 index 000000000..a0b11022b --- /dev/null +++ b/packages/omi-cloudbase/.eslintrc @@ -0,0 +1,8 @@ +{ + "extends": "eslint:recommended", + "rules": { + "no-unused-vars": ["error", { "varsIgnorePattern": "Taro" }], + "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx", ".tsx"] }] + }, + "parser": "babel-eslint" +} diff --git a/packages/omi-cloudbase/.gitignore b/packages/omi-cloudbase/.gitignore new file mode 100644 index 000000000..52efd0902 --- /dev/null +++ b/packages/omi-cloudbase/.gitignore @@ -0,0 +1,6 @@ +dist/miniprogram +dist/cloudfunctions +.temp/ +.rn_temp/ +node_modules/ +.DS_Store diff --git a/packages/omi-cloudbase/LICENSE b/packages/omi-cloudbase/LICENSE new file mode 100644 index 000000000..351e92c5d --- /dev/null +++ b/packages/omi-cloudbase/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Omi Team + +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. diff --git a/packages/omi-cloudbase/README.md b/packages/omi-cloudbase/README.md new file mode 100644 index 000000000..b9cded314 --- /dev/null +++ b/packages/omi-cloudbase/README.md @@ -0,0 +1,451 @@ +# 简介 + +云开发(CloudBase)[https://www.cloudbase.net/](https://www.cloudbase.net/) 是基于Serverless架构构建的一站式后端云服务,涵盖函数、数据库、存储、CDN等服务,免后端运维,支持小程序、Web和APP开发。 +其中,小程序·云开发是微信和腾讯云联合推出的云端一体化解决方案,基于云开发可以免鉴权调用微信所有开放能力,在微信开发者工具中即可开通使用。 + +# Omi Cloud 实战小程序 markdown 内容发布系统 + +开发小程序,但是:没有后端!没有运维!没有 DBA!没有域名!没有证书!没有钱!没有时间!没有精力! + +**没有关系,会 javascript 就可以,小程序•云开发带你起飞!** + +开发者可以使用云开发开发微信小程序、小游戏,无需搭建服务器,即可使用云端能力。云开发为开发者提供完整的云端支持,弱化后端和运维概念,无需搭建服务器,使用平台提供的 API 进行核心业务开发,即可实现快速上线和迭代,同时这一能力,同开发者已经使用的云服务相互兼容,并不互斥。 + +目前提供三大基础能力支持: + +- 云函数:在云端运行的代码,微信私有协议天然鉴权,开发者只需编写自身业务逻辑代码 +- 数据库:一个既可在小程序前端操作,也能在云函数中读写的 JSON 数据库 +- 存储:在小程序前端直接上传/下载云端文件,在云开发控制台可视化管理 + +## 一步一步搭建 + +本文将一步一步教你使用 小程序•云开发 + Omip + Comi 搭建一个支持 markdown 和代码高亮的小程序内容展示和发布系统。 + +预览: + +![](https://github.com/Tencent/omi/raw/master/assets/omi-cloud.jpg) + +### 1.建表 + + + +操作路径: 微信开发者工具→云开发→数据库→添加集合 + +article 集合字段说明: + + +| **字段** | **说明** | +| ------------------------------- | ----------------------------------- | +| _id | 数据的唯一 id,用户写入时系统自动生产 | +| _openid | 用户的唯一标识,用户写入时系统自动生产 | +| createTime | 文章创建时间 | +| md | 文章内容 | +| order | 文章的顺序 | +| title | 文章的标题 | + +很明显,这个表用来存储所有的文章。然后设置表的读写权限: + + + +因为后续可能支持用户发表文章,所有设置成第一个。 + +### 2.初始化项目目录 + +```bash +$ npm i omi-cli -g +$ omi init-cloud my-app +$ cd my-app +$ npm start +``` + + + +这里是使用 omip 作为脚手架,也支持 Omi mps-cloud 创建原生小程序的云开发的脚手架: + +```bash +$ npm i omi-cli -g +$ omi init-mps-cloud my-app +$ cd my-app/miniprogram +$ npm install +$ npm start +``` + +### 3.项目初始化 app.js + +```jsx +import './app.css' +import './pages/list/index' +import { render, WeElement, define } from 'omi' + +define('my-app', class extends WeElement { + + config = { + pages: [ + 'pages/list/index', + 'pages/detail/index', + 'pages/import/index' + ], + window: { + backgroundTextStyle: 'light', + navigationBarBackgroundColor: '#fff', + navigationBarTitleText: 'Omi Cloud', + navigationBarTextStyle: 'black' + } + } + + install() { + if (!wx.cloud) { + console.error('请使用 2.2.3 或以上的基础库以使用云能力') + } else { + wx.cloud.init({ + traceUser: true, + }) + this.globalData.db = wx.cloud.database({ + env: 'test-06eb2e' + }) + } + } + + render() { + return ( + + ) + } +}) + +render(, '#app') +``` + + + +`wx.cloud.database` 代码参数里的 env 可以从上面获取到,一般创建两个环境,一个用户测试环境,一个用于生产环境。 + +- pages/list/index 文章列表首页 +- pages/detail/index 文章详情夜 +- pages/import/index 文章导入页(先简单通过代码导入 markdown,没提供 UI) + +### 导入 markdown 数据 + +```js +import { WeElement, define } from 'omi' +import data from './test.md' + +const app = getApp() + +define('page-import', class extends WeElement { + + installed() { + wx.cloud.callFunction({ + name: 'login', + data: {}, + success: res => { + app.globalData.openid = res.result.openid + app.globalData.db.collection('article').add({ + data: { + md: data.md, + title: 'test', + createTime: app.globalData.db.serverDate() + }, + success: (res) => { + console.log(res) + }, + fail: err => { + console.error('[云函数] [login] 调用失败', err) + } + }) + }, + fail: err => { + console.error('[云函数] [login] 调用失败', err) + } + }) + } + + ... + ... +}) +``` + +注意三点: + +- 通过 `wx.cloud.callFunction` 调用云函数进行登陆,且获取 openid,接着导入数据会自动带上提交该 openid。 +- 通过 `app.globalData.db.serverDate()` 获取服务端时间,客户端时间不可靠 +- 文章导入只由管理员负责 + +注意 `import data from './test.md'`,这里通过修改 omip 里的 scripts 逻辑实现。 + +这里解释下 import markdown 原理: + +```js +let code = fs.readFileSync(item).toString() +if (path.extname(item) === '.md') { + code = `export default { md: \`${code.replace(/`/g, '\\`').replace(/\$/g, '\\$')}\` }` +} +``` + +检测到 md 后缀的文件,把文件里的 markdown 字符串对关键字进行转义然后变成一个 js 模块。 + +这也算是使用中间编译的好处之一吧,如果原生的小程序目前没办法 import markdown 文件,当然原生小程序 API 和周边生态在不断进化,腾讯 Omi 团队开发的 [mps 框架](https://github.com/Tencent/omi/tree/master/packages/mps) 就是让你在原生小程序中使用 jsx 和 less。 + +上面的详细代码可以[点击这里](https://github.com/Tencent/omi/blob/master/packages/omi-cloud/scripts/taro-cli/src/weapp.js#L1968-L1971)查看到。 + + +### 列表页 + + + +请求 list 数据 + +```js + //先展示 loading + wx.showLoading({ + title: '加载中' + }) + //调用云函数获取 openid + wx.cloud.callFunction({ + name: 'login', + data: {}, + success: res => { + app.globalData.openid = res.result.openid + app.globalData.db.collection('article').field({ + title: true, + _id: true, + order: true + }).get().then(res => { + this.data.list = res.data.sort(function (a, b) { + return a.order - b.order + }) + this.update() + wx.hideLoading() + }) + }, + fail: err => { + console.error('[云函数] [login] 调用失败', err) + } + }) +``` + +- 请求 list,通过 field 方法筛选字段,毕竟 list 不需要 md 字段,这样可以减少数据传输,节约带宽 +- 通过 order 字段对 list 进行排序(这样管理员不需要发版本就可以手动调整 order 给 list 排序) + + +完整的代码: + +```jsx +import { WeElement, define } from 'omi' +import './index.css' +import arrowPng from './arrow.png' + +//获取应用实例 +const app = getApp() + +define('page-about', class extends WeElement { + config = { + navigationBarBackgroundColor: '#24292e', + navigationBarTextStyle: 'white', + navigationBarTitleText: 'Omi', + backgroundColor: '#ccc', + backgroundTextStyle: 'light' + } + + data = { + list: [] + } + + installed() { + wx.showLoading({ + title: '加载中' + }) + wx.cloud.callFunction({ + name: 'login', + data: {}, + success: res => { + console.log('[云函数] [login] user openid: ', res.result.openid) + app.globalData.openid = res.result.openid + app.globalData.db.collection('article').field({ + title: true, + _id: true, + order: true + }).get().then(res => { + this.data.list = res.data.sort(function (a, b) { + return a.order - b.order + }) + this.update() + wx.hideLoading() + }) + }, + fail: err => { + console.error('[云函数] [login] 调用失败', err) + + } + }) + } + + gotoDetail = (evt) => { + wx.navigateTo({ + url: '../detail/index?id=' + evt.currentTarget.dataset.id + }) + } + + render() { + return ( + + {list.map(item => ( + + {item.title} + + + ))} + + ) + } +}) +``` + +Omip 可以直接让你使用 jsx 书写 wxml 结构。编译出的 wxml 如下: + +```html + + + {{item.title}} + + + + +``` + +这里需要注意,点击每一项跳转详情也一定要使用 `evt.currentTarget.dataset.id`,而不能使用 `evt.target.dataset.id`。这样点击到文字或者image +上获取不到 id。 + + + +### 文章详情展示 + +这里使用 Comi 进行 markdown 渲染! Comi 读 ['kəʊmɪ],类似中文 科米,是腾讯 Omi 团队开发的小程序代码高亮和 markdown 渲染组件。Comi 是基于下面几个优秀的社区组件进行二次开发而成。 + +* wxParse +* remarkable +* html2json +* htmlparser +* prism + +效果预览: + + + +```js +import { WeElement, define } from 'omi' +import './index.css' +import comi from '../../components/comi/comi' + +//获取应用实例 +const app = getApp() + +define('page-about', class extends WeElement { + config = { + navigationBarBackgroundColor: '#24292e', + navigationBarTextStyle: 'white', + navigationBarTitleText: ' ', + backgroundColor: '#eeeeee', + backgroundTextStyle: 'light' + } + + install(options) { + wx.showLoading({ + title: '加载中' + }) + app.globalData.db.collection('article').doc(options.id).get().then(res=>{ + comi(res.data.md, this.$scope) + wx.hideLoading() + }).catch(err => { + console.error(err) + }) + } + + + render() { + return ( + + + + ) + } +}) +``` + +除了在 omip 中使用,原生小程序也可以使用 Comi: + +先拷贝 [此目录](https://github.com/Tencent/omi/tree/master/packages/comi/mp/comi) 到你的项目。 + +js: + +```js +const comi = require('../../comi/comi.js'); + +Page({ + onLoad: function () { + comi(`你要渲染的 md!`, this) + } +}) +``` + +wxml: + +```html + +``` + +wxss: + +```css +@import "../../comi/comi.wxss"; +``` + +大功告成,简单把! + +### 云函数与调试 + +云函数即在云端(服务器端)运行的函数。在物理设计上,一个云函数可由多个文件组成,占用一定量的 CPU 内存等计算资源;各云函数完全独立;可分别部署在不同的地区。开发者无需购买、搭建服务器,只需编写函数代码并部署到云端即可在小程序端调用,同时云函数之间也可互相调用。 + +一个云函数的写法与一个在本地定义的 JavaScript 方法无异,代码运行在云端 Node.js 中。当云函数被小程序端调用时,定义的代码会被放在 Node.js 运行环境中执行。我们可以如在 Node.js 环境中使用 JavaScript 一样在云函数中进行网络请求等操作,而且我们还可以通过云函数后端 SDK 搭配使用多种服务,比如使用云函数 SDK 中提供的数据库和存储 API 进行数据库和存储的操作,这部分可参考数据库和存储后端 API 文档。 + +云开发的云函数的独特优势在于与微信登录鉴权的无缝整合。当小程序端调用云函数时,云函数的传入参数中会被注入小程序端用户的 openid,开发者无需校验 openid 的正确性因为微信已经完成了这部分鉴权,开发者可以直接使用该 openid。 + +在本文的小程序里有个 todo 的案例,里面的 remove 使用了云函数,用于清空所有已完成的任务。 + + + + +```js +const cloud = require('wx-server-sdk') +cloud.init() + +const db = cloud.database() +const _ = db.command + +exports.main = async (event, context) => { + try { + return await db.collection('todo').where({ + done: true + }).remove() + } catch (e) { + console.error(e) + } +} +``` + + + +不过最新的IED,云函数支持了本地调试功能,感兴趣的可以[点击这里](https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/functions/local-debug.html)了解下。 + +## 相关链接 + +- [源码地址](https://github.com/Tencent/omi/tree/master/packages/omi-cloud) +- [官方教程](https://developers.weixin.qq.com/miniprogram/dev/wxcloud/basis/getting-started.html) +- [小程序端 API 文档](https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-client-api/) +- [服务端 API 文档](https://developers.weixin.qq.com/miniprogram/dev/wxcloud/reference-server-api/) diff --git a/packages/omi-cloudbase/config/dev.js b/packages/omi-cloudbase/config/dev.js new file mode 100644 index 000000000..03776341d --- /dev/null +++ b/packages/omi-cloudbase/config/dev.js @@ -0,0 +1,9 @@ +module.exports = { + env: { + NODE_ENV: '"development"' + }, + defineConstants: { + }, + weapp: {}, + h5: {} +} diff --git a/packages/omi-cloudbase/config/h5.js b/packages/omi-cloudbase/config/h5.js new file mode 100644 index 000000000..83b220300 --- /dev/null +++ b/packages/omi-cloudbase/config/h5.js @@ -0,0 +1,107 @@ +const config = { + projectName: 'my-app', + date: '2019-2-21', + designWidth: 750, + deviceRatio: { + '640': 2.34 / 2, + '750': 1, + '828': 1.81 / 2 + }, + alias: { + 'omi': 'src/libs/omip-h5/omi.esm.js', + '@tarojs': 'src/libs' + }, + sourceRoot: 'src', + outputRoot: 'dist', + plugins: { + babel: { + sourceMap: true, + presets: [ + ['env', { + modules: false + }] + ], + plugins: [ + 'transform-decorators-legacy', + 'transform-class-properties', + 'transform-object-rest-spread', + // ['transform-react-jsx', { pragma: 'global.Omi.h' }] + ] + } + }, + defineConstants: { + }, + copy: { + patterns: [ + ], + options: { + } + }, + weapp: { + module: { + postcss: { + autoprefixer: { + enable: true, + config: { + browsers: [ + 'last 3 versions', + 'Android >= 4.1', + 'ios >= 8' + ] + } + }, + pxtransform: { + enable: false, + config: { + + } + }, + url: { + enable: true, + config: { + limit: 10240 // 设定转换尺寸上限 + } + }, + cssModules: { + enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true + config: { + namingPattern: 'module', // 转换模式,取值为 global/module + generateScopedName: '[name]__[local]___[hash:base64:5]' + } + } + } + } + }, + h5: { + publicPath: '/', + staticDirectory: 'static', + module: { + postcss: { + autoprefixer: { + enable: true, + config: { + browsers: [ + 'last 3 versions', + 'Android >= 4.1', + 'ios >= 8' + ] + } + }, + cssModules: { + enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true + config: { + namingPattern: 'module', // 转换模式,取值为 global/module + generateScopedName: '[name]__[local]___[hash:base64:5]' + } + } + } + } + } +} + +module.exports = function (merge) { + if (process.env.NODE_ENV === 'development') { + return merge({}, config, require('./dev')) + } + return merge({}, config, require('./prod')) +} diff --git a/packages/omi-cloudbase/config/index.js b/packages/omi-cloudbase/config/index.js new file mode 100644 index 000000000..b3b3b82bc --- /dev/null +++ b/packages/omi-cloudbase/config/index.js @@ -0,0 +1,107 @@ +const config = { + projectName: 'my-app', + date: '2019-2-21', + designWidth: 750, + deviceRatio: { + '640': 2.34 / 2, + '750': 1, + '828': 1.81 / 2 + }, + alias: { + 'omi': 'src/libs/omip/index.js', + '@tarojs': 'src/libs' + }, + sourceRoot: 'src', + outputRoot: 'dist/miniprogram', + plugins: { + babel: { + sourceMap: true, + presets: [ + ['env', { + modules: false + }] + ], + plugins: [ + 'transform-decorators-legacy', + 'transform-class-properties', + 'transform-object-rest-spread', + ['transform-react-jsx', { pragma: 'global.Omi.h' }] + ] + } + }, + defineConstants: { + }, + copy: { + patterns: [ + ], + options: { + } + }, + weapp: { + module: { + postcss: { + autoprefixer: { + enable: true, + config: { + browsers: [ + 'last 3 versions', + 'Android >= 4.1', + 'ios >= 8' + ] + } + }, + pxtransform: { + enable: false, + config: { + + } + }, + url: { + enable: true, + config: { + limit: 10240 // 设定转换尺寸上限 + } + }, + cssModules: { + enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true + config: { + namingPattern: 'module', // 转换模式,取值为 global/module + generateScopedName: '[name]__[local]___[hash:base64:5]' + } + } + } + } + }, + h5: { + publicPath: '/', + staticDirectory: 'static', + module: { + postcss: { + autoprefixer: { + enable: true, + config: { + browsers: [ + 'last 3 versions', + 'Android >= 4.1', + 'ios >= 8' + ] + } + }, + cssModules: { + enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true + config: { + namingPattern: 'module', // 转换模式,取值为 global/module + generateScopedName: '[name]__[local]___[hash:base64:5]' + } + } + } + } + } +} + +module.exports = function (merge) { + if (process.env.NODE_ENV === 'development') { + return merge({}, config, require('./dev')) + } + return merge({}, config, require('./prod')) +} diff --git a/packages/omi-cloudbase/config/prod.js b/packages/omi-cloudbase/config/prod.js new file mode 100644 index 000000000..631d4ed8a --- /dev/null +++ b/packages/omi-cloudbase/config/prod.js @@ -0,0 +1,11 @@ +module.exports = { + env: { + NODE_ENV: '"production"' + }, + defineConstants: { + }, + weapp: {}, + h5: { + publicPath: './', + } +} diff --git a/packages/omi-cloudbase/dist/README.md b/packages/omi-cloudbase/dist/README.md new file mode 100644 index 000000000..660f13087 --- /dev/null +++ b/packages/omi-cloudbase/dist/README.md @@ -0,0 +1,2 @@ +* cloudfunctions 目录存放云函数 +* miniprogram 目录存放小程序 diff --git a/packages/omi-cloudbase/dist/project.config.json b/packages/omi-cloudbase/dist/project.config.json new file mode 100644 index 000000000..12e1a7501 --- /dev/null +++ b/packages/omi-cloudbase/dist/project.config.json @@ -0,0 +1,56 @@ +{ + "miniprogramRoot": "miniprogram/", + "cloudfunctionRoot": "cloudfunctions/", + "setting": { + "urlCheck": true, + "es6": true, + "postcss": true, + "minified": true, + "newFeature": true + }, + "appid": "wxdf970566455966b0", + "projectname": "omi-cloud", + "libVersion": "2.6.2", + "condition": { + "search": { + "current": -1, + "list": [] + }, + "conversation": { + "current": -1, + "list": [] + }, + "plugin": { + "current": -1, + "list": [] + }, + "game": { + "list": [] + }, + "miniprogram": { + "current": 2, + "list": [ + { + "id": -1, + "name": "导入数据", + "pathName": "pages/import/index", + "query": "", + "scene": null + }, + { + "id": -1, + "name": "代码高亮", + "pathName": "pages/code/index", + "query": "", + "scene": null + }, + { + "id": -1, + "name": "入口", + "pathName": "pages/list/index", + "scene": null + } + ] + } + } +} \ No newline at end of file diff --git a/packages/omi-cloudbase/package.json b/packages/omi-cloudbase/package.json new file mode 100644 index 000000000..0036f9206 --- /dev/null +++ b/packages/omi-cloudbase/package.json @@ -0,0 +1,123 @@ +{ + "name": "my-app", + "version": "1.0.0", + "private": true, + "description": "", + "scripts": { + "start": "npm run build:weapp -- --watch", + "build:weapp": "node ./scripts/taro-cli/bin/taro build --type weapp", + "build:swan": "node ./scripts/taro-cli/bin/taro build --type swan", + "build:alipay": "node ./scripts/taro-cli/bin/taro build --type alipay", + "build:tt": "node ./scripts/taro-cli/bin/taro build --type tt", + "build:h5": "node ./scripts/taro-cli/bin/taro build --type h5", + "build:rn": "node ./scripts/taro-cli/bin/taro build --type rn", + "dev:swan": "npm run build:swan -- --watch", + "dev:alipay": "npm run build:alipay -- --watch", + "dev:tt": "npm run build:tt -- --watch", + "dev:h5": "npm run build:h5 -- --watch", + "dev:rn": "npm run build:rn -- --watch" + }, + "author": "", + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.0.0-beta.44", + "@fdaciuk/ajax": "^3.0.4", + "@tarojs/components": "1.2.13", + "@tarojs/router": "1.2.13", + "@tarojs/taro": "1.2.13", + "@tarojs/taro-alipay": "1.2.13", + "@tarojs/taro-h5": "1.2.13", + "@tarojs/taro-swan": "1.2.13", + "@tarojs/taro-tt": "1.2.13", + "@tarojs/taro-weapp": "1.2.13", + "@tarojs/taroize": "1.2.13", + "autoprefixer": "^8.4.1", + "babel-core": "^6.26.3", + "babel-eslint": "^8.2.3", + "babel-generator": "^6.26.1", + "babel-helper-evaluate-path": "^0.5.0", + "babel-helper-mark-eval-scopes": "^0.4.3", + "babel-helper-remove-or-void": "^0.4.3", + "babel-plugin-danger-remove-unused-import": "^1.1.1", + "babel-plugin-minify-dead-code": "^0.5.2", + "babel-plugin-remove-dead-code": "^1.3.2", + "babel-plugin-syntax-dynamic-import": "^6.18.0", + "babel-plugin-transform-class-properties": "^6.24.1", + "babel-plugin-transform-decorators-legacy": "^1.3.4", + "babel-plugin-transform-define": "^1.3.0", + "babel-plugin-transform-es2015-template-literals": "^6.22.0", + "babel-plugin-transform-flow-strip-types": "^6.22.0", + "babel-plugin-transform-jsx-to-stylesheet": "1.2.13", + "babel-plugin-transform-react-jsx": "^6.24.1", + "babel-template": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "better-babel-generator": "^6.26.1", + "chalk": "^2.3.2", + "chokidar": "^2.0.3", + "commander": "^2.15.0", + "cross-spawn": "^6.0.5", + "css": "^2.2.4", + "css-to-react-native-transform": "^1.4.0", + "css-what": "^2.1.3", + "ejs": "^2.6.1", + "envinfo": "^6.0.1", + "eslint": "^4.15.0", + "eslint-plugin-taro": "1.2.13", + "fs-extra": "^5.0.0", + "generic-names": "^2.0.1", + "glob": "^7.1.2", + "html": "^1.0.0", + "inquirer": "^5.2.0", + "klaw": "^2.1.1", + "latest-version": "^4.0.0", + "lodash": "^4.17.5", + "mem-fs": "^1.1.3", + "mem-fs-editor": "^4.0.0", + "minimatch": "^3.0.4", + "nerv-devtools": "^1.3.9", + "nervjs": "^1.3.9", + "omi-router": "^2.0.8", + "ora": "^2.0.0", + "postcss": "^6.0.22", + "postcss-modules-extract-imports": "^1.1.0", + "postcss-modules-local-by-default": "^1.2.0", + "postcss-modules-resolve-imports": "^1.3.0", + "postcss-modules-scope": "^1.1.0", + "postcss-modules-values": "^1.3.0", + "postcss-pxtransform": "1.2.13", + "postcss-taro-unit-transform": "1.2.13", + "postcss-url": "^7.3.2", + "prettier": "^1.14.3", + "prop-types": "^15.6.2", + "remarkable": "^1.7.1", + "resolve": "^1.6.0", + "semver": "^5.5.0", + "shelljs": "^0.8.1", + "through2": "^2.0.3", + "typescript": "^3.2.2", + "vinyl": "^2.1.0", + "vinyl-fs": "^3.0.2" + }, + "devDependencies": { + "@types/react": "^16.4.6", + "@types/webpack-env": "^1.13.6", + "@tarojs/plugin-babel": "1.2.13", + "@tarojs/plugin-csso": "1.2.13", + "@tarojs/plugin-uglifyjs": "1.2.13", + "@tarojs/webpack-runner": "1.2.13", + "babel-plugin-transform-class-properties": "^6.24.1", + "babel-plugin-transform-decorators-legacy": "^1.3.4", + "babel-plugin-transform-jsx-stylesheet": "^0.6.5", + "babel-plugin-transform-object-rest-spread": "^6.26.0", + "babel-plugin-transform-react-jsx": "^6.24.1", + "babel-preset-env": "^1.6.1", + "babel-eslint": "^8.2.3", + "eslint": "^4.19.1", + "eslint-config-taro": "1.2.13", + "eslint-plugin-react": "^7.8.2", + "eslint-plugin-import": "^2.12.0", + "eslint-plugin-taro": "1.2.13" + } +} diff --git a/packages/omi-cloudbase/project.config.json b/packages/omi-cloudbase/project.config.json new file mode 100644 index 000000000..a2f9d618b --- /dev/null +++ b/packages/omi-cloudbase/project.config.json @@ -0,0 +1,56 @@ +{ + "miniprogramRoot": "miniprogram/", + "cloudfunctionRoot": "cloudfunctions/", + "setting": { + "urlCheck": true, + "es6": true, + "postcss": true, + "minified": true, + "newFeature": true + }, + "appid": "wxdf970566455966b0", + "projectname": "omi-cloud", + "libVersion": "2.6.2", + "condition": { + "search": { + "current": -1, + "list": [] + }, + "conversation": { + "current": -1, + "list": [] + }, + "plugin": { + "current": -1, + "list": [] + }, + "game": { + "list": [] + }, + "miniprogram": { + "current": 2, + "list": [ + { + "id": -1, + "name": "导入数据", + "pathName": "pages/import/index", + "query": "", + "scene": null + }, + { + "id": -1, + "name": "代码高亮", + "pathName": "pages/code/index", + "query": "", + "scene": null + }, + { + "id": -1, + "name": "入口", + "pathName": "pages/list/index", + "scene": null + } + ] + } + } +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/bin/taro b/packages/omi-cloudbase/scripts/taro-cli/bin/taro new file mode 100644 index 000000000..8fd4125da --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/bin/taro @@ -0,0 +1,24 @@ +#! /usr/bin/env node + +const program = require('commander') +const { getPkgVersion, printPkgVersion } = require('../src/util') + +printPkgVersion() + +const startTime = new Date('2019-1-1 00:00').getTime() +const endTime = new Date('2019-1-2 00:00').getTime() +const nowTime = Date.now() +if (nowTime >= startTime && nowTime <= endTime) { + const yearTxt = String(require('fs-extra').readFileSync(require('path').resolve(__dirname, 'year.txt'))) + console.log(require('chalk').rgb(255, 87, 34)(yearTxt)) +} + +program + .version(getPkgVersion()) + .usage(' [options]') + .command('init [projectName]', 'Init a project with default templete') + .command('build', 'Build a project with options') + .command('update', 'Update packages of taro') + .command('convert', 'Convert weapp to taro') + .command('info', 'Diagnostics Taro env info') + .parse(process.argv) diff --git a/packages/omi-cloudbase/scripts/taro-cli/bin/taro-build b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-build new file mode 100644 index 000000000..fe42b1f74 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-build @@ -0,0 +1,55 @@ +#!/usr/bin/env node +const path = require('path') +const fs = require('fs-extra') +const program = require('commander') +const chalk = require('chalk') +const _ = require('lodash') + +const build = require('../src/build') +const { PROJECT_CONFIG } = require('../src/util') +const projectConfPath = path.join(process.cwd(), PROJECT_CONFIG) + +program + .option('--type [typeName]', 'Build type, weapp/h5/rn/swan/alipay/tt') + .option('--watch', 'Watch mode') + .option('--env [env]', 'Env type') + .option('--ui', 'Build Taro UI library') + .parse(process.argv) + +const args = program.args +const { type, watch, ui } = program +let { env } = program + +env = process.env.NODE_ENV || env + +if (ui) { + console.log(chalk.green(`开始编译 UI 库`)) + build(args, { + type: 'ui', + watch + }) + return +} + +if (!fs.existsSync(projectConfPath)) { + console.log(chalk.red(`找不到项目配置文件${PROJECT_CONFIG},请确定当前目录是Taro项目根目录!`)) + process.exit(1) +} + +if (env) { + process.env.NODE_ENV = env +} else { + if (watch) { + process.env.NODE_ENV = 'development' + } else { + process.env.NODE_ENV = 'production' + } +} + +const projectConf = require(projectConfPath)(_.merge) +console.log(chalk.green(`开始编译项目 ${chalk.bold(projectConf.projectName)}`)) + +build(args, { + type, + watch +}) diff --git a/packages/omi-cloudbase/scripts/taro-cli/bin/taro-convert b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-convert new file mode 100644 index 000000000..28bba8f4f --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-convert @@ -0,0 +1,12 @@ +#!/usr/bin/env node + +const program = require('commander') + +const Convertor = require('../src/convertor') + +program + .parse(process.argv) + +const convertor = new Convertor() + +convertor.run() diff --git a/packages/omi-cloudbase/scripts/taro-cli/bin/taro-info b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-info new file mode 100644 index 000000000..8bc584716 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-info @@ -0,0 +1,53 @@ +#!/usr/bin/env node +const fs = require('fs') +const path = require('path') +const envinfo = require('envinfo') +const {getPkgVersion, UPDATE_PACKAGE_LIST} = require('../src/util') +const process = require('process') +const program = require('commander') + +const npmPackages = UPDATE_PACKAGE_LIST.concat(['react', 'react-native', 'nervjs', 'expo']) + +program.parse(process.argv) + +const args = program.args + +if (args.length === 1) { + switch (args[0]) { + case 'rn': { + rnInfo({ + SDKs: ['iOS SDK', 'Android SDK'] + }) + break + } + default: + info() + } +} else { + info() +} + +function rnInfo (options) { + const appPath = process.cwd() + const tempPath = path.join(appPath, '.rn_temp') + if (fs.lstatSync(tempPath).isDirectory()) { + process.chdir('.rn_temp') + info(options) + } +} + +async function info (options) { + let info = await envinfo.run( + { + System: ['OS', 'Shell'], + Binaries: ['Node', 'Yarn', 'npm'], + npmPackages, + npmGlobalPackages: ['typescript'], + ...options + }, + { + title: `Taro CLI ${getPkgVersion()} environment info` + } + ) + console.log(info) +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/bin/taro-init b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-init new file mode 100644 index 000000000..16af1599e --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-init @@ -0,0 +1,40 @@ +#!/usr/bin/env node + +const program = require('commander') + +const Project = require('../src/project') + +program + .option('--name [name]', '项目名称') + .option('--description [description]', '项目介绍') + .option('--typescript', '使用TypeScript') + .option('--no-typescript', '不使用TypeScript') + .option('--template [template]', '项目模板(default/redux/mobx)') + .option('--css [css]', 'CSS预处理器(sass/less/stylus/none)') + .parse(process.argv) + +const args = program.args +const { template, description, name, css } = program +let typescript = '' + +/** + * 非标准做法 + * 为了兼容不指定typescript参数时,在inquirer中询问是否使用typescript的情况 + */ +if (program.rawArgs.indexOf('--typescript') !== -1) { + typescript = true +} else if (program.rawArgs.indexOf('--no-typescript') !== -1) { + typescript = false +} + +const projectName = args[0] || name + +const project = new Project({ + projectName, + template, + description, + typescript, + css +}) + +project.create() diff --git a/packages/omi-cloudbase/scripts/taro-cli/bin/taro-update b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-update new file mode 100644 index 000000000..157aeb2a8 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/bin/taro-update @@ -0,0 +1,118 @@ +#!/usr/bin/env node +const path = require('path') +const fs = require('fs-extra') +const program = require('commander') +const chalk = require('chalk') +const { getPkgItemByKey } = require('../src/util') +const ora = require('ora') +const exec = require('child_process').exec +const getLatestVersion = require('latest-version') +const { PROJECT_CONFIG, UPDATE_PACKAGE_LIST} = require('../src/util') +const projectConfPath = path.join(process.cwd(), PROJECT_CONFIG) +const pkgPath = path.join(process.cwd(), 'package.json') +const { shouldUseYarn, shouldUseCnpm } = require('../src/util') + +const pkgName = getPkgItemByKey('name') + +// 这里没有使用 command 的形式:taro-update-self +program.parse(process.argv) + +const args = program.args + +if (args.length === 1) { + switch (args[0]) { + case 'self': { + updateSelf() + break + } + case 'project': { + updateProject() + break + } + default: + info() + } +} else { + info() +} + +function info () { + console.log(chalk.red('命令错误:')) + console.log(`${chalk.green('taro update self')} 更新 Taro 开发工具 taro-cli 到最新版本`) + console.log(`${chalk.green('taro update project')} 更新项目所有 Taro 相关依赖到最新版本...`) +} + +function updateSelf () { + let command + if (shouldUseCnpm()) { + command = 'cnpm i -g @tarojs/cli@latest' + } else { + command = 'npm i -g @tarojs/cli@latest' + } + + let child = exec(command) + + const spinner = ora('即将将 Taro 开发工具 taro-cli 更新到最新版本...').start() + + child.stdout.on('data', function (data) { + console.log(data) + spinner.stop() + }) + child.stderr.on('data', function (data) { + console.log(data) + spinner.stop() + }) +} + +async function updateProject () { + if (!fs.existsSync(projectConfPath)) { + console.log(chalk.red(`找不到项目配置文件${PROJECT_CONFIG},请确定当前目录是Taro项目根目录!`)) + process.exit(1) + } + const packageMap = require(pkgPath) + + const version = await getLatestVersion(pkgName) + + // 更新 @tarojs/* 版本 + Object.keys(packageMap.dependencies).forEach((key) => { + if (UPDATE_PACKAGE_LIST.indexOf(key) !== -1) { + packageMap.dependencies[key] = version + } + }) + Object.keys(packageMap.devDependencies).forEach((key) => { + if (UPDATE_PACKAGE_LIST.indexOf(key) !== -1) { + packageMap.devDependencies[key] = version + } + }) + + // 写入package.json + try { + await fs.writeJson(pkgPath, packageMap, {spaces: '\t'}) + console.log(chalk.green('更新项目 package.json 成功!')) + console.log() + } catch (err) { + console.error(err) + } + + let command + if (shouldUseYarn()) { + command = 'yarn' + } else if (shouldUseCnpm()) { + command = 'cnpm install' + } else { + command = 'npm install' + } + + let child = exec(command) + + const spinner = ora('即将将项目所有 Taro 相关依赖更新到最新版本...').start() + + child.stdout.on('data', function (data) { + spinner.stop() + console.log(data) + }) + child.stderr.on('data', function (data) { + spinner.stop() + console.log(data) + }) +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/bin/year.txt b/packages/omi-cloudbase/scripts/taro-cli/bin/year.txt new file mode 100644 index 000000000..dc4740373 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/bin/year.txt @@ -0,0 +1,9 @@ +🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 +🎉 _ _ _ _ _____ _____ __ _____ _ 🎉 +🏮 | | | | | | | / __ | _ / || _ | | | 🏮 +🎉 | |_| | ___| | | ___ `' / /| |/' `| || |_| | | | 🎉 +🏮 | _ |/ _ | | |/ _ \ / / | /| || |\____ | | | 🏮 +🎉 | | | | __| | | (_) | ./ /__\ |_/ _| |.___/ / |_| 🎉 +🏮 \_| |_/\___|_|_|\___/ \_____/\___/\___\____/ (_) 🏮 +🎉 🎉 +🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 🎉 🏮 diff --git a/packages/omi-cloudbase/scripts/taro-cli/package.json b/packages/omi-cloudbase/scripts/taro-cli/package.json new file mode 100644 index 000000000..f20fc1502 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/package.json @@ -0,0 +1,87 @@ +{ + "name": "@tarojs/cli", + "version": "1.2.13", + "description": "cli tool for taro", + "main": "index.js", + "scripts": { + "test": "jest" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "bin": { + "taro": "bin/taro" + }, + "keywords": [ + "taro", + "weapp" + ], + "engines": { + "node": ">=8" + }, + "author": "O2Team", + "license": "MIT", + "dependencies": { + "@tarojs/taroize": "1.2.13", + "autoprefixer": "^8.4.1", + "babel-core": "^6.26.3", + "babel-generator": "^6.26.1", + "babel-plugin-danger-remove-unused-import": "^1.1.1", + "babel-plugin-remove-dead-code": "^1.3.2", + "babel-plugin-transform-decorators-legacy": "^1.3.4", + "babel-plugin-transform-define": "^1.3.0", + "babel-plugin-transform-jsx-to-stylesheet": "1.2.13", + "babel-plugin-transform-react-jsx": "^6.24.1", + "babel-template": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "better-babel-generator": "^6.26.1", + "chalk": "^2.3.2", + "chokidar": "^2.0.3", + "commander": "^2.15.0", + "cross-spawn": "^6.0.5", + "css-to-react-native-transform": "^1.4.0", + "ejs": "^2.6.1", + "envinfo": "^6.0.1", + "fs-extra": "^5.0.0", + "generic-names": "^2.0.1", + "glob": "^7.1.2", + "inquirer": "^5.2.0", + "klaw": "^2.1.1", + "latest-version": "^4.0.0", + "lodash": "^4.17.5", + "mem-fs": "^1.1.3", + "mem-fs-editor": "^4.0.0", + "minimatch": "^3.0.4", + "ora": "^2.0.0", + "postcss": "^6.0.22", + "postcss-modules-extract-imports": "^1.1.0", + "postcss-modules-local-by-default": "^1.2.0", + "postcss-modules-resolve-imports": "^1.3.0", + "postcss-modules-scope": "^1.1.0", + "postcss-modules-values": "^1.3.0", + "postcss-pxtransform": "1.2.13", + "postcss-taro-unit-transform": "1.2.13", + "postcss-url": "^7.3.2", + "prettier": "^1.14.3", + "prop-types": "^15.6.2", + "resolve": "^1.6.0", + "semver": "^5.5.0", + "shelljs": "^0.8.1", + "through2": "^2.0.3", + "vinyl": "^2.1.0", + "vinyl-fs": "^3.0.2" + }, + "devDependencies": { + "babel-jest": "^23.6.0", + "babel-plugin-transform-class-properties": "^6.24.1", + "babel-preset-env": "^1.7.0", + "babel-preset-react": "^6.24.1", + "babel-preset-stage-0": "^6.24.1", + "jest": "^23.6.0", + "jest-react-native": "^18.0.0", + "react-native": "^0.55.4" + } +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/build.js b/packages/omi-cloudbase/scripts/taro-cli/src/build.js new file mode 100644 index 000000000..f2af9fb15 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/build.js @@ -0,0 +1,90 @@ +const fs = require('fs-extra') +const path = require('path') +const chalk = require('chalk') +const _ = require('lodash') + +const Util = require('./util') +const CONFIG = require('./config') + +const appPath = process.cwd() + + +function build (args, buildConfig) { + const { type, watch } = buildConfig + const configDir = require(path.join(appPath, Util.PROJECT_CONFIG))(_.merge) + const outputPath = path.join(appPath, configDir.outputRoot || CONFIG.OUTPUT_DIR) + if (!fs.existsSync(outputPath)) { + fs.mkdirSync(outputPath) + } else { + if (type !== Util.BUILD_TYPES.H5) { + Util.emptyDirectory(outputPath) + } + } + switch (type) { + case Util.BUILD_TYPES.H5: + buildForH5({ watch }) + break + case Util.BUILD_TYPES.WEAPP: + buildForWeapp({ watch }) + break + case Util.BUILD_TYPES.SWAN: + buildForSwan({ watch }) + break + case Util.BUILD_TYPES.ALIPAY: + buildForAlipay({ watch }) + break + case Util.BUILD_TYPES.TT: + buildForTt({ watch }) + break + case Util.BUILD_TYPES.RN: + buildForRN({ watch }) + break + case Util.BUILD_TYPES.UI: + buildForUILibrary({ watch }) + break + default: + console.log(chalk.red('输入类型错误,目前只支持 weapp/h5/rn/swan/alipay/tt 六端类型')) + } +} + +function buildForWeapp ({ watch }) { + require('./weapp').build({ + watch, + adapter: Util.BUILD_TYPES.WEAPP + }) +} + +function buildForSwan ({ watch }) { + require('./weapp').build({ + watch, + adapter: Util.BUILD_TYPES.SWAN + }) +} + +function buildForAlipay ({ watch }) { + require('./weapp').build({ + watch, + adapter: Util.BUILD_TYPES.ALIPAY + }) +} + +function buildForTt ({ watch }) { + require('./weapp').build({ + watch, + adapter: Util.BUILD_TYPES.TT + }) +} + +function buildForH5 (buildConfig) { + require('./h5').build(buildConfig) +} + +function buildForRN ({ watch }) { + require('./rn').build({ watch }) +} + +function buildForUILibrary ({ watch }) { + require('./ui').build({ watch }) +} + +module.exports = build diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/config/babel.js b/packages/omi-cloudbase/scripts/taro-cli/src/config/babel.js new file mode 100644 index 000000000..3b2e56859 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/config/babel.js @@ -0,0 +1,12 @@ +module.exports = { + sourceMap: true, + presets: [ + 'env' + ], + plugins: [ + require('babel-plugin-transform-react-jsx'), + 'transform-decorators-legacy', + 'transform-class-properties', + 'transform-object-rest-spread' + ] +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/config/babylon.js b/packages/omi-cloudbase/scripts/taro-cli/src/config/babylon.js new file mode 100644 index 000000000..015dd1180 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/config/babylon.js @@ -0,0 +1,15 @@ +module.exports = { + sourceType: 'module', + plugins: [ + 'typescript', + 'classProperties', + 'jsx', + 'trailingFunctionCommas', + 'asyncFunctions', + 'exponentiationOperator', + 'asyncGenerators', + 'objectRestSpread', + 'decorators', + 'dynamicImport' + ] +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/config/browser_list.js b/packages/omi-cloudbase/scripts/taro-cli/src/config/browser_list.js new file mode 100644 index 000000000..afdd1afc8 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/config/browser_list.js @@ -0,0 +1,5 @@ +module.exports = [ + 'last 3 versions', + 'Android >= 4.1', + 'ios >= 8' +] diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/config/index.js b/packages/omi-cloudbase/scripts/taro-cli/src/config/index.js new file mode 100644 index 000000000..e341dd8e7 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/config/index.js @@ -0,0 +1,7 @@ +module.exports = { + OUTPUT_DIR: 'dist', + SOURCE_DIR: 'src', + TEMP_DIR: '.temp', + NPM_DIR: 'npm', + ENTRY: 'app' +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/config/tsconfig.json b/packages/omi-cloudbase/scripts/taro-cli/src/config/tsconfig.json new file mode 100644 index 000000000..7ecbfd0cf --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/config/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "baseUrl": ".", + "declaration": false, + "experimentalDecorators": true, + "jsx": "react", + "jsxFactory": "Nerv.createElement", + "module": "commonjs", + "moduleResolution": "node", + "noImplicitAny": false, + "noUnusedLocals": true, + "outDir": "./dist/", + "preserveConstEnums": true, + "removeComments": false, + "rootDir": ".", + "sourceMap": true, + "strictNullChecks": true, + "target": "es6" + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules" + ], + "compileOnSave": false +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/config/uglify.js b/packages/omi-cloudbase/scripts/taro-cli/src/config/uglify.js new file mode 100644 index 000000000..7acaac2b6 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/config/uglify.js @@ -0,0 +1,3 @@ +module.exports = { + +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/convertor.js b/packages/omi-cloudbase/scripts/taro-cli/src/convertor.js new file mode 100644 index 000000000..f60fb4392 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/convertor.js @@ -0,0 +1,720 @@ +const fs = require('fs-extra') +const path = require('path') + +const chalk = require('chalk') +const prettier = require('prettier') +const traverse = require('babel-traverse').default +const t = require('babel-types') +const template = require('babel-template') +const taroize = require('@tarojs/taroize') +const wxTransformer = require('../../taro-transformer-wx/lib/src/index.js').default +const postcss = require('postcss') +const unitTransform = require('postcss-taro-unit-transform') + +const { + BUILD_TYPES, + MINI_APP_FILES, + printLog, + pocessTypeEnum, + promoteRelativePath, + resolveScriptPath, + REG_SCRIPT, + REG_TYPESCRIPT, + processStyleImports, + getPkgVersion, + pascalCase, + emptyDirectory, + REG_URL, + REG_IMAGE +} = require('./util') + +const { generateMinimalEscapeCode } = require('./util/ast_convert') + +const Creator = require('./creator') +const babylonConfig = require('./config/babylon') + +const prettierJSConfig = { + semi: false, + singleQuote: true, + parser: 'babel' +} + +const OUTPUT_STYLE_EXTNAME = '.scss' + +const WX_GLOBAL_FN = ['getApp', 'getCurrentPages', 'requirePlugin'] + +function analyzeImportUrl (sourceFilePath, scriptFiles, source, value) { + const valueExtname = path.extname(value) + if (path.isAbsolute(value)) { + printLog(pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 是绝对路径!`) + return + } + if (value.indexOf('.') === 0) { + if (REG_SCRIPT.test(valueExtname) || REG_TYPESCRIPT.test(valueExtname)) { + const vpath = path.resolve(sourceFilePath, '..', value) + let fPath = value + if (fs.existsSync(vpath)) { + fPath = vpath + } else { + printLog(pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`) + } + scriptFiles.add(fPath) + } else { + let vpath = resolveScriptPath(path.resolve(sourceFilePath, '..', value)) + if (vpath) { + if (!fs.existsSync(vpath)) { + printLog(pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`) + } else { + if (fs.lstatSync(vpath).isDirectory()) { + if (fs.existsSync(path.join(vpath, 'index.js'))) { + vpath = path.join(vpath, 'index.js') + } else { + printLog(pocessTypeEnum.ERROR, '引用目录', `文件 ${sourceFilePath} 中引用了目录 ${value}!`) + return + } + } + let relativePath = path.relative(sourceFilePath, vpath) + const relativePathExtname = path.extname(relativePath) + scriptFiles.add(vpath) + relativePath = promoteRelativePath(relativePath) + if (/\.wxs/.test(relativePathExtname)) { + relativePath += '.js' + } else { + relativePath = relativePath.replace(relativePathExtname, '.js') + } + source.value = relativePath + } + } + } + } +} + +class Convertor { + constructor () { + this.root = process.cwd() + this.convertRoot = path.join(this.root, 'taroConvert') + this.convertDir = path.join(this.convertRoot, 'src') + this.importsDir = path.join(this.convertDir, 'imports') + this.fileTypes = MINI_APP_FILES[BUILD_TYPES.WEAPP] + this.pages = new Set() + this.components = new Set() + this.hadBeenCopyedFiles = new Set() + this.hadBeenBuiltComponents = new Set() + this.hadBeenBuiltImports = new Set() + this.init() + } + + init () { + console.log(chalk.green('开始代码转换...')) + this.initConvert() + this.getApp() + this.getPages() + this.getSubPackages() + } + + initConvert () { + if (fs.existsSync(this.convertRoot)) { + emptyDirectory(this.convertRoot, { excludes: ['node_modules'] }) + } else { + fs.mkdirpSync(this.convertRoot) + } + } + + parseAst ({ ast, sourceFilePath, outputFilePath, importStylePath, depComponents, imports = [], isApp = false }) { + const scriptFiles = new Set() + const self = this + let componentClassName = null + let needInsertImportTaro = false + traverse(ast, { + Program: { + enter (astPath) { + astPath.traverse({ + ClassDeclaration (astPath) { + const node = astPath.node + let isTaroComponent = false + if (node.superClass) { + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: 'render' })) { + astPath.traverse({ + JSXElement () { + isTaroComponent = true + } + }) + } + } + }) + if (isTaroComponent) { + componentClassName = node.id.name + } + } + }, + + ClassExpression (astPath) { + const node = astPath.node + if (node.superClass) { + let isTaroComponent = false + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: 'render' })) { + astPath.traverse({ + JSXElement () { + isTaroComponent = true + } + }) + } + } + }) + if (isTaroComponent) { + if (node.id === null) { + const parentNode = astPath.parentPath.node + if (t.isVariableDeclarator(astPath.parentPath)) { + componentClassName = parentNode.id.name + } + } else { + componentClassName = node.id.name + } + } + } + }, + ExportDefaultDeclaration (astPath) { + const node = astPath.node + const declaration = node.declaration + if ( + declaration && + (declaration.type === 'ClassDeclaration' || declaration.type === 'ClassExpression') + ) { + const superClass = declaration.superClass + if (superClass) { + let isTaroComponent = false + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: 'render' })) { + astPath.traverse({ + JSXElement () { + isTaroComponent = true + } + }) + } + } + }) + if (isTaroComponent) { + componentClassName = declaration.id.name + } + } + } + }, + ImportDeclaration (astPath) { + const node = astPath.node + const source = node.source + const value = source.value + analyzeImportUrl(sourceFilePath, scriptFiles, source, value) + }, + CallExpression (astPath) { + const node = astPath.node + const calleePath = astPath.get('callee') + const callee = calleePath.node + if (callee.type === 'Identifier') { + if (callee.name === 'require') { + const args = node.arguments + const value = args[0].value + analyzeImportUrl(sourceFilePath, scriptFiles, args[0], value) + } else if (WX_GLOBAL_FN.includes(callee.name)) { + calleePath.replaceWith( + t.memberExpression(t.identifier('Taro'), callee) + ) + needInsertImportTaro = true + } + } else if (callee.type === 'MemberExpression') { + const object = callee.object + if (object.name === 'wx') { + calleePath.get('object').replaceWith(t.identifier('Taro')) + needInsertImportTaro = true + } + } + } + }) + }, + exit (astPath) { + const lastImport = astPath.get('body').filter(p => p.isImportDeclaration()).pop() + const hasTaroImport = astPath.get('body').some(p => p.isImportDeclaration() && p.node.source.value === '@tarojs/taro') + if (needInsertImportTaro && !hasTaroImport) { + astPath.node.body.unshift( + t.importDeclaration( + [t.importDefaultSpecifier(t.identifier('Taro'))], + t.stringLiteral('@tarojs/taro') + ) + ) + } + astPath.traverse({ + StringLiteral (astPath) { + const value = astPath.node.value + const extname = path.extname(value) + if (extname && REG_IMAGE.test(extname) && !REG_URL.test(value)) { + let imageRelativePath = null + let sourceImagePath = null + let outputImagePath = null + if (path.isAbsolute(value)) { + sourceImagePath = path.join(self.root, value) + } else { + sourceImagePath = path.resolve(sourceFilePath, '..', value) + } + imageRelativePath = promoteRelativePath(path.relative(sourceFilePath, sourceImagePath)) + outputImagePath = self.getDistFilePath(sourceImagePath) + if (fs.existsSync(sourceImagePath)) { + self.copyFileToTaro(sourceImagePath, outputImagePath) + printLog(pocessTypeEnum.COPY, '图片', self.generateShowPath(outputImagePath)) + } else { + printLog(pocessTypeEnum.ERROR, '图片不存在', self.generateShowPath(sourceImagePath)) + } + if (astPath.parentPath.isVariableDeclarator()) { + astPath.replaceWith(t.callExpression(t.identifier('require'), [t.stringLiteral(imageRelativePath)])) + } else if (astPath.parentPath.isJSXAttribute()) { + astPath.replaceWith(t.jSXExpressionContainer(t.callExpression(t.identifier('require'), [t.stringLiteral(imageRelativePath)]))) + } + } + } + }) + if (lastImport) { + if (importStylePath) { + lastImport.insertAfter(t.importDeclaration([], t.stringLiteral(promoteRelativePath(path.relative(sourceFilePath, importStylePath))))) + } + if (imports && imports.length) { + imports.forEach(({ name, ast }) => { + const importName = pascalCase(name) + if (componentClassName === importName) { + return + } + const importPath = path.join(self.importsDir, importName + '.js') + if (!self.hadBeenBuiltImports.has(importPath)) { + self.hadBeenBuiltImports.add(importPath) + self.writeFileToTaro(importPath, prettier.format(generateMinimalEscapeCode(ast), prettierJSConfig)) + } + lastImport.insertAfter(template(`import ${importName} from '${promoteRelativePath(path.relative(outputFilePath, importPath))}'`, babylonConfig)()) + }) + } + if (depComponents && depComponents.size) { + depComponents.forEach(componentObj => { + const name = pascalCase(componentObj.name) + const component = componentObj.path + lastImport.insertAfter(template(`import ${name} from '${promoteRelativePath(path.relative(sourceFilePath, component))}'`, babylonConfig)()) + }) + } + + if (isApp) { + astPath.node.body.push(template(`Taro.render(, document.getElementById('app'))`, babylonConfig)()) + } + } + } + } + }) + + return { + ast, + scriptFiles + } + } + + getApp () { + this.entryJSPath = path.join(this.root, `app${this.fileTypes.SCRIPT}`) + this.entryJSONPath = path.join(this.root, `app${this.fileTypes.CONFIG}`) + this.entryStylePath = path.join(this.root, `app${this.fileTypes.STYLE}`) + try { + this.entryJSON = JSON.parse(String(fs.readFileSync(this.entryJSONPath))) + printLog(pocessTypeEnum.CONVERT, '入口文件', this.generateShowPath(this.entryJSPath)) + printLog(pocessTypeEnum.CONVERT, '入口配置', this.generateShowPath(this.entryJSONPath)) + if (fs.existsSync(this.entryStylePath)) { + this.entryStyle = String(fs.readFileSync(this.entryStylePath)) + printLog(pocessTypeEnum.CONVERT, '入口样式', this.generateShowPath(this.entryStylePath)) + } + } catch (err) { + this.entryJSON = {} + console.log(chalk.red(`app${this.fileTypes.CONFIG} 读取失败,请检查!`)) + process.exit(1) + } + } + + getPages () { + const pages = this.entryJSON['pages'] + if (!pages || !pages.length) { + console.log(chalk.red(`app${this.fileTypes.CONFIG} 配置有误,缺少页面相关配置`)) + return + } + this.pages = new Set(pages) + } + + getSubPackages () { + const subPackages = this.entryJSON['subpackages'] || this.entryJSON['subPackages'] + if (!subPackages || !subPackages.length) { + return + } + subPackages.forEach(item => { + if (item.pages && item.pages.length) { + const root = item.root + item.pages.forEach(page => { + let pagePath = `${root}/${page}` + pagePath = pagePath.replace(/\/{2,}/g, '/') + this.pages.add(pagePath) + }) + } + }) + } + + generateScriptFiles (files) { + if (!files) { + return + } + if (files.size) { + files.forEach(file => { + if (!fs.existsSync(file) || this.hadBeenCopyedFiles.has(file)) { + return + } + const code = fs.readFileSync(file).toString() + let outputFilePath = file.replace(this.root, this.convertDir) + const extname = path.extname(outputFilePath) + if (/\.wxs/.test(extname)) { + outputFilePath += '.js' + } + const transformResult = wxTransformer({ + code, + sourcePath: file, + outputPath: outputFilePath, + isNormal: true, + isTyped: REG_TYPESCRIPT.test(file) + }) + const { ast, scriptFiles } = this.parseAst({ + ast: transformResult.ast, + outputFilePath, + sourceFilePath: file + }) + const jsCode = generateMinimalEscapeCode(ast) + this.writeFileToTaro(outputFilePath, prettier.format(jsCode, prettierJSConfig)) + printLog(pocessTypeEnum.COPY, 'JS 文件', this.generateShowPath(outputFilePath)) + this.hadBeenCopyedFiles.add(file) + this.generateScriptFiles(scriptFiles) + }) + } + } + + writeFileToTaro (dist, code) { + fs.ensureDirSync(path.dirname(dist)) + fs.writeFileSync(dist, code) + } + + copyFileToTaro (from, to, options) { + const filename = path.basename(from) + if (fs.statSync(from).isFile() && !path.extname(to)) { + fs.ensureDir(to) + return fs.copySync(from, path.join(to, filename), options) + } + fs.ensureDir(path.dirname(to)) + return fs.copySync(from, to, options) + } + + getDistFilePath (src, extname) { + if (!extname) return src.replace(this.root, this.convertDir) + return src.replace(this.root, this.convertDir).replace(path.extname(src), extname) + } + + generateShowPath (filePath) { + return filePath.replace(path.join(this.root, '/'), '').split(path.sep).join('/') + } + + generateEntry () { + try { + const entryJS = String(fs.readFileSync(this.entryJSPath)) + const entryJSON = JSON.stringify(this.entryJSON) + const entryDistJSPath = this.getDistFilePath(this.entryJSPath) + const taroizeResult = taroize({ + json: entryJSON, + script: entryJS, + path: path.dirname(entryJS) + }) + const { ast, scriptFiles } = this.parseAst({ + ast: taroizeResult.ast, + sourceFilePath: this.entryJSPath, + outputFilePath: entryDistJSPath, + importStylePath: this.entryStyle ? this.entryStylePath.replace(path.extname(this.entryStylePath), OUTPUT_STYLE_EXTNAME) : null, + isApp: true + }) + const jsCode = generateMinimalEscapeCode(ast) + this.writeFileToTaro(entryDistJSPath, prettier.format(jsCode, prettierJSConfig)) + printLog(pocessTypeEnum.GENERATE, '入口文件', this.generateShowPath(entryDistJSPath)) + if (this.entryStyle) { + this.traverseStyle(this.entryStylePath, this.entryStyle) + } + this.generateScriptFiles(scriptFiles) + if (this.entryJSON.tabBar) { + this.generateTabBarIcon(this.entryJSON.tabBar) + } + } catch (err) { + console.log(err) + } + } + + generateTabBarIcon (tabBar) { + const { list = [] } = tabBar + const icons = new Set() + if (Array.isArray(list) && list.length) { + list.forEach(item => { + if (typeof item.iconPath === 'string') icons.add(item.iconPath) + if (typeof item.selectedIconPath === 'string') icons.add(item.selectedIconPath) + }) + if (icons.size > 0) { + Array.from(icons) + .map(icon => path.join(this.root, icon)) + .forEach(iconPath => { + const iconDistPath = this.getDistFilePath(iconPath) + this.copyFileToTaro(iconPath, iconDistPath) + printLog(pocessTypeEnum.COPY, 'TabBar 图标', this.generateShowPath(iconDistPath)) + }) + } + } + } + + traversePages () { + this.pages.forEach(page => { + const pagePath = path.join(this.root, page) + const pageJSPath = pagePath + this.fileTypes.SCRIPT + const pageDistJSPath = this.getDistFilePath(pageJSPath) + const pageConfigPath = pagePath + this.fileTypes.CONFIG + const pageStylePath = pagePath + this.fileTypes.STYLE + const pageTemplPath = pagePath + this.fileTypes.TEMPL + + try { + const param = {} + const depComponents = new Set() + if (!fs.existsSync(pageJSPath)) { + throw new Error(`页面 ${page} 没有 JS 文件!`) + } + printLog(pocessTypeEnum.CONVERT, '页面文件', this.generateShowPath(pageJSPath)) + + if (fs.existsSync(pageConfigPath)) { + printLog(pocessTypeEnum.CONVERT, '页面配置', this.generateShowPath(pageConfigPath)) + const pageConfigStr = String(fs.readFileSync(pageConfigPath)) + const pageConfig = JSON.parse(pageConfigStr) + const pageUsingComponnets = pageConfig.usingComponents + if (pageUsingComponnets) { + // 页面依赖组件 + Object.keys(pageUsingComponnets).forEach(component => { + let componentPath = path.resolve(pageConfigPath, '..', pageUsingComponnets[component]) + if (!fs.existsSync(resolveScriptPath(componentPath))) { + componentPath = path.join(this.root, pageUsingComponnets[component]) + } + depComponents.add({ + name: component, + path: componentPath + }) + }) + delete pageConfig.usingComponents + } + param.json = JSON.stringify(pageConfig) + } + param.script = String(fs.readFileSync(pageJSPath)) + if (fs.existsSync(pageTemplPath)) { + printLog(pocessTypeEnum.CONVERT, '页面模板', this.generateShowPath(pageTemplPath)) + param.wxml = String(fs.readFileSync(pageTemplPath)) + } + let pageStyle = null + if (fs.existsSync(pageStylePath)) { + printLog(pocessTypeEnum.CONVERT, '页面样式', this.generateShowPath(pageStylePath)) + pageStyle = String(fs.readFileSync(pageStylePath)) + } + param.path = path.dirname(pageJSPath) + const taroizeResult = taroize(param) + const { ast, scriptFiles } = this.parseAst({ + ast: taroizeResult.ast, + sourceFilePath: pageJSPath, + outputFilePath: pageDistJSPath, + importStylePath: pageStyle ? pageStylePath.replace(path.extname(pageStylePath), OUTPUT_STYLE_EXTNAME) : null, + depComponents, + imports: taroizeResult.imports + }) + const jsCode = generateMinimalEscapeCode(ast) + this.writeFileToTaro(pageDistJSPath, prettier.format(jsCode, prettierJSConfig)) + printLog(pocessTypeEnum.GENERATE, '页面文件', this.generateShowPath(pageDistJSPath)) + if (pageStyle) { + this.traverseStyle(pageStylePath, pageStyle) + } + this.generateScriptFiles(scriptFiles) + this.traverseComponents(depComponents) + } catch (err) { + printLog(pocessTypeEnum.ERROR, '页面转换', this.generateShowPath(pageJSPath)) + console.log(err) + } + }) + } + + traverseComponents (components) { + if (!components || !components.size) { + return + } + components.forEach(componentObj => { + const component = componentObj.path + if (this.hadBeenBuiltComponents.has(component)) return + this.hadBeenBuiltComponents.add(component) + + const componentJSPath = component + this.fileTypes.SCRIPT + const componentDistJSPath = this.getDistFilePath(componentJSPath) + const componentConfigPath = component + this.fileTypes.CONFIG + const componentStylePath = component + this.fileTypes.STYLE + const componentTemplPath = component + this.fileTypes.TEMPL + + try { + const param = {} + const depComponents = new Set() + if (!fs.existsSync(componentJSPath)) { + throw new Error(`组件 ${component} 没有 JS 文件!`) + } + printLog(pocessTypeEnum.CONVERT, '组件文件', this.generateShowPath(componentJSPath)) + if (fs.existsSync(componentConfigPath)) { + printLog(pocessTypeEnum.CONVERT, '组件配置', this.generateShowPath(componentConfigPath)) + const componentConfigStr = String(fs.readFileSync(componentConfigPath)) + const componentConfig = JSON.parse(componentConfigStr) + const componentUsingComponnets = componentConfig.usingComponents + if (componentUsingComponnets) { + // 页面依赖组件 + Object.keys(componentUsingComponnets).forEach(component => { + let componentPath = path.resolve(componentConfigPath, '..', componentUsingComponnets[component]) + if (!fs.existsSync(resolveScriptPath(componentPath))) { + componentPath = path.join(this.root, componentUsingComponnets[component]) + } + depComponents.add({ + name: component, + path: componentPath + }) + }) + delete componentConfig.usingComponents + } + param.json = JSON.stringify(componentConfig) + } + param.script = String(fs.readFileSync(componentJSPath)) + if (fs.existsSync(componentTemplPath)) { + printLog(pocessTypeEnum.CONVERT, '组件模板', this.generateShowPath(componentTemplPath)) + param.wxml = String(fs.readFileSync(componentTemplPath)) + } + let componentStyle = null + if (fs.existsSync(componentStylePath)) { + printLog(pocessTypeEnum.CONVERT, '组件样式', this.generateShowPath(componentStylePath)) + componentStyle = String(fs.readFileSync(componentStylePath)) + } + param.path = path.dirname(componentJSPath) + const taroizeResult = taroize(param) + const { ast, scriptFiles } = this.parseAst({ + ast: taroizeResult.ast, + sourceFilePath: componentJSPath, + outputFilePath: componentDistJSPath, + importStylePath: componentStyle ? componentStylePath.replace(path.extname(componentStylePath), OUTPUT_STYLE_EXTNAME) : null, + depComponents, + imports: taroizeResult.imports + }) + const jsCode = generateMinimalEscapeCode(ast) + this.writeFileToTaro(componentDistJSPath, prettier.format(jsCode, prettierJSConfig)) + printLog(pocessTypeEnum.GENERATE, '组件文件', this.generateShowPath(componentDistJSPath)) + if (componentStyle) { + this.traverseStyle(componentStylePath, componentStyle) + } + this.generateScriptFiles(scriptFiles) + this.traverseComponents(depComponents) + } catch (err) { + printLog(pocessTypeEnum.ERROR, '组件转换', this.generateShowPath(componentJSPath)) + console.log(err) + } + }) + } + + async styleUnitTransform (filePath, content) { + const postcssResult = await postcss([ + unitTransform() + ]).process(content, { + from: filePath + }) + return postcssResult + } + + async traverseStyle (filePath, style) { + const { imports, content } = processStyleImports(style, BUILD_TYPES.WEAPP, (str, stylePath) => { + let relativePath = stylePath + if (path.isAbsolute(relativePath)) { + relativePath = promoteRelativePath(path.relative(filePath, path.join(this.root, stylePath))) + } + return str.replace(stylePath, relativePath) + .replace(MINI_APP_FILES[BUILD_TYPES.WEAPP].STYLE, OUTPUT_STYLE_EXTNAME) + }) + const styleDist = this.getDistFilePath(filePath, OUTPUT_STYLE_EXTNAME) + const { css } = await this.styleUnitTransform(filePath, content) + this.writeFileToTaro(styleDist, css) + printLog(pocessTypeEnum.GENERATE, '样式文件', this.generateShowPath(styleDist)) + if (imports && imports.length) { + imports.forEach(importItem => { + const importPath = path.isAbsolute(importItem) + ? path.join(this.root, importItem) + : path.resolve(path.dirname(filePath), importItem) + if (fs.existsSync(importPath)) { + const styleText = fs.readFileSync(importPath).toString() + this.traverseStyle(importPath, styleText) + } + }) + } + } + + generateConfigFiles () { + const creator = new Creator() + const templateName = 'default' + const configDir = path.join(this.convertRoot, 'config') + const pkgPath = path.join(this.convertRoot, 'package.json') + const projectName = 'taroConvert' + const description = '' + const version = getPkgVersion() + const dateObj = new Date() + const date = `${dateObj.getFullYear()}-${(dateObj.getMonth() + 1)}-${dateObj.getDate()}` + creator.template(templateName, 'pkg', pkgPath, { + description, + projectName, + version, + css: 'sass', + typescript: false + }) + creator.template(templateName, path.join('config', 'index'), path.join(configDir, 'index.js'), { + date, + projectName + }) + creator.template(templateName, path.join('config', 'dev'), path.join(configDir, 'dev.js')) + creator.template(templateName, path.join('config', 'prod'), path.join(configDir, 'prod.js')) + creator.template(templateName, 'project', path.join(this.convertRoot, 'project.config.json'), { + description, + projectName + }) + creator.template(templateName, 'gitignore', path.join(this.convertRoot, '.gitignore')) + creator.template(templateName, 'editorconfig', path.join(this.convertRoot, '.editorconfig')) + creator.template(templateName, 'eslintrc', path.join(this.convertRoot, '.eslintrc'), { + typescript: false + }) + creator.template(templateName, 'indexhtml', path.join(this.convertDir, 'index.html')) + creator.fs.commit(() => { + const pkgObj = JSON.parse(fs.readFileSync(pkgPath).toString()) + pkgObj.dependencies['@tarojs/with-weapp'] = `^${version}` + fs.writeJSONSync(pkgPath, pkgObj, { + spaces: 2, + EOL: '\n' + }) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(configDir, 'index.js'))) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(configDir, 'dev.js'))) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(configDir, 'prod.js'))) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(pkgPath)) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, 'project.config.json'))) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, '.gitignore'))) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, '.editorconfig'))) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertRoot, '.eslintrc'))) + printLog(pocessTypeEnum.GENERATE, '文件', this.generateShowPath(path.join(this.convertDir, 'index.html'))) + }) + } + + run () { + this.generateEntry() + this.traversePages() + this.generateConfigFiles() + } +} + +module.exports = Convertor diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/creator.js b/packages/omi-cloudbase/scripts/taro-cli/src/creator.js new file mode 100644 index 000000000..86e8b846b --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/creator.js @@ -0,0 +1,86 @@ +const path = require('path') +const fs = require('fs-extra') +const memFs = require('mem-fs') +const editor = require('mem-fs-editor') + +const { + getRootPath +} = require('./util') + +class Creator { + constructor () { + const store = memFs.create() + this.fs = editor.create(store) + this.sourceRoot(path.join(getRootPath())) + this.init() + } + + init () {} + + sourceRoot (rootPath) { + if (typeof rootPath === 'string') { + this._rootPath = path.resolve(rootPath) + } + if (!fs.existsSync(this._rootPath)) { + fs.ensureDirSync(this._rootPath) + } + return this._rootPath + } + + templatePath () { + let filepath = path.join.apply(path, arguments) + if (!path.isAbsolute(filepath)) { + filepath = path.join(this._rootPath, 'templates', filepath) + } + return filepath + } + + destinationRoot (rootPath) { + if (typeof rootPath === 'string') { + this._destinationRoot = path.resolve(rootPath) + if (!fs.existsSync(rootPath)) { + fs.ensureDirSync(rootPath) + } + process.chdir(rootPath) + } + return this._destinationRoot || process.cwd() + } + + destinationPath () { + let filepath = path.join.apply(path, arguments) + if (!path.isAbsolute(filepath)) { + filepath = path.join(this.destinationRoot(), filepath) + } + return filepath + } + + template (template, source, dest, data, options) { + if (typeof dest !== 'string') { + options = data + data = dest + dest = source + } + this.fs.copyTpl( + this.templatePath(template, source), + this.destinationPath(dest), + Object.assign({}, this, data), + options + ) + return this + } + + copy (template, type, source, dest) { + dest = dest || source + this.template(template, type, source, dest) + return this + } + + writeGitKeepFile (dirname) { + dirname = path.resolve(dirname) + fs.writeFileSync(path.join(dirname, '.gitkeep'), 'Place hold file', 'utf8') + } + + write () {} +} + +module.exports = Creator diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/css/css-stringify.js b/packages/omi-cloudbase/scripts/taro-cli/src/css/css-stringify.js new file mode 100644 index 000000000..33883f09b --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/css/css-stringify.js @@ -0,0 +1,58 @@ + +var actionTypes = { + "equals": "", + "element": "~", + "start": "^", + "end": "$", + "any": "*", + "not": "!", + "hyphen": "|" +}; + +var simpleSelectors = { + __proto__: null, + child: " > ", + parent: " < ", + sibling: " ~ ", + adjacent: " + ", + descendant: " ", + universal: "*" +}; + + + +function stringify(token){ + return token.map(stringifySubselector).join(", "); +} + +function stringifySubselector(token){ + return token.map(stringifyToken).join(""); +} + +function stringifyToken(token){ + if(token.type in simpleSelectors) return simpleSelectors[token.type]; + + if(token.type === "tag") return escapeName(token.name); + + if(token.type === "attribute"){ + if(token.action === "exists") return "[" + escapeName(token.name) + "]"; + if(token.name === "id" && token.action === "equals" && !token.ignoreCase) return "#" + escapeName(token.value); + if(token.name === "class" && token.action === "element" && !token.ignoreCase) return "." + escapeName(token.value); + return "[" + + escapeName(token.name) + actionTypes[token.action] + "='" + + escapeName(token.value) + "'" + (token.ignoreCase ? "i" : "") + "]"; + } + + if(token.type === "pseudo"){ + if(token.data === null) return ":" + escapeName(token.name); + if(typeof token.data === "string") return ":" + escapeName(token.name) + "(" + token.data + ")"; + return ":" + escapeName(token.name) + "(" + stringify(token.data) + ")"; + } +} + +function escapeName(str){ + //TODO + return str; +} + +module.exports = stringify diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/css/index.js b/packages/omi-cloudbase/scripts/taro-cli/src/css/index.js new file mode 100644 index 000000000..242136d56 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/css/index.js @@ -0,0 +1,28 @@ + +let map = require('./tag-mapping') +let css = require('css') +let cssWhat = require('css-what') +let cssStringify = require('./css-stringify') + +function compileWxss(str) { + let obj = css.parse(str) + obj.stylesheet.rules.forEach(rule => { + rule.selectors && rule.selectors.forEach((selector, index) => { + let sltObjs = cssWhat(selector) + sltObjs.forEach(sltObj => { + sltObj.forEach(item => { + if (item.type == 'tag') { + item.name = map(item.name) + + } + }) + + }) + + rule.selectors[index] = cssStringify(sltObjs) + }) + }) + return css.stringify(obj) +} + +module.exports = compileWxss diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/css/tag-mapping.js b/packages/omi-cloudbase/scripts/taro-cli/src/css/tag-mapping.js new file mode 100644 index 000000000..1578e68e0 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/css/tag-mapping.js @@ -0,0 +1,19 @@ +let tagMapping = { + view: 'div', + text: 'span', + image: 'img', + picker: 'select', + navigator: 'a', +} + +function map(key) { + if (key.indexOf('-') !== -1) { + return key + } + if(tagMapping[key]){ + return tagMapping[key] + } + return key +} + +module.exports = map diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/extra/util_wxs b/packages/omi-cloudbase/scripts/taro-cli/src/extra/util_wxs new file mode 100644 index 000000000..e6e011c2e --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/extra/util_wxs @@ -0,0 +1,11 @@ +var assign = function (s, d) { + if (typeof s !== 'object') { + return d + } + s = s || {} + d = d || {} + return JSON.parse((JSON.stringify(s) + JSON.stringify(d)).replace('}{', ',')) +} +module.exports = { + assign: assign +}; diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/h5.js b/packages/omi-cloudbase/scripts/taro-cli/src/h5.js new file mode 100644 index 000000000..592210a25 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/h5.js @@ -0,0 +1,1032 @@ +const fs = require('fs-extra') +const path = require('path') +const chokidar = require('chokidar') +const wxTransformer = require('../../taro-transformer-wx/lib/src/index.js').default +const klaw = require('klaw') +const traverse = require('babel-traverse').default +const t = require('babel-types') +const babel = require('babel-core') +const generate = require('better-babel-generator').default +const _ = require('lodash') +const rimraf = require('rimraf') +const { promisify } = require('util') +const minimatch = require('minimatch') + +const Util = require('./util') +const npmProcess = require('./util/npm') +const CONFIG = require('./config') +const { source: toAst, getObjKey } = require('./util/ast_convert') +const compileWxss = require('./css/index') +const appPath = process.cwd() +//@fix +const projectConfig = require(path.join(appPath, Util.PROJECT_CONFIG_H5))(_.merge) + +const h5Config = projectConfig.h5 || {} +const routerConfig = h5Config.router || {} +const routerMode = routerConfig.mode === 'browser' ? 'browser' : 'hash' +const customRoutes = routerConfig.customRoutes || {} +const routerBasename = routerConfig.basename || '/' +const sourceDir = projectConfig.sourceRoot || CONFIG.SOURCE_DIR +const sourcePath = path.join(appPath, sourceDir) +const outputDir = projectConfig.outputRoot || CONFIG.OUTPUT_DIR +const outputPath = path.join(appPath, outputDir) +const tempDir = CONFIG.TEMP_DIR +const tempPath = path.join(appPath, tempDir) +const entryFilePath = Util.resolveScriptPath(path.join(sourcePath, CONFIG.ENTRY)) +const entryFileName = path.basename(entryFilePath) +let pxTransformConfig = { designWidth: projectConfig.designWidth || 750 } +const pathAlias = projectConfig.alias || {} + +const PACKAGES = { + '@tarojs/taro': '@tarojs/taro', + '@tarojs/taro-h5': '@tarojs/taro-h5', + '@tarojs/redux': '@tarojs/redux', + '@tarojs/redux-h5': '@tarojs/redux-h5', + '@tarojs/mobx': '@tarojs/mobx', + '@tarojs/mobx-h5': '@tarojs/mobx-h5', + '@tarojs/router': `@tarojs/router`, + '@tarojs/components': '@tarojs/components', + 'nervjs': 'nervjs', + 'nerv-redux': 'nerv-redux' +} + +const taroApis = [ + 'Component', + 'getEnv', + 'ENV_TYPE', + 'eventCenter', + 'Events', + 'internal_safe_get', + 'internal_dynamic_recursive' +] +const nervJsImportDefaultName = 'Nerv' +const tabBarComponentName = 'Tabbar' +const tabBarContainerComponentName = 'TabbarContainer' +const tabBarPanelComponentName = 'TabbarPanel' +const providerComponentName = 'Provider' +const setStoreFuncName = 'setStore' +const tabBarConfigName = '__tabs' +const DEVICE_RATIO = 'deviceRatio' + +if (projectConfig.hasOwnProperty(DEVICE_RATIO)) { + pxTransformConfig[DEVICE_RATIO] = projectConfig.deviceRatio +} +//@fix +if (!String.prototype.endsWith) { + String.prototype.endsWith = function(search, this_len) { + if (this_len === undefined || this_len > this.length) { + this_len = this.length; + } + return this.substring(this_len - search.length, this_len) === search; + }; +} + +let pages = [] +let tabBar +let tabbarPos +//@fix +let appCSS = '' + +const FILE_TYPE = { + ENTRY: 'ENTRY', + PAGE: 'PAGE', + COMPONENT: 'COMPONENT', + NORMAL: 'NORMAL' +} + +const addLeadingSlash = path => path.charAt(0) === '/' ? path : '/' + path +const stripTrailingSlash = path => path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path + +const isUnderSubPackages = (parentPath) => (parentPath.isObjectProperty() && /subPackages|subpackages/i.test(getObjKey(parentPath.node.key))) + +const publicPath = h5Config.publicPath + ? stripTrailingSlash(addLeadingSlash(h5Config.publicPath || '')) + : '' + +function createRoute ({ absPagename, relPagename, isIndex, chunkName = '' }) { + const chunkNameComment = chunkName ? `/* webpackChunkName: "${chunkName}" */` : '' + return `{ + path: '${absPagename}', + componentLoader: () => import(${chunkNameComment}'${relPagename}'), + isIndex: ${isIndex} + }` +} + +function processEntry (code, filePath) { + let ast = wxTransformer({ + code, + sourcePath: filePath, + isNormal: true, + isTyped: Util.REG_TYPESCRIPT.test(filePath), + adapter: 'h5' + }).ast + let taroImportDefaultName + let providorImportName + let storeName + let renderCallCode + + let hasAddNervJsImportDefaultName = false + let hasConstructor = false + let hasComponentWillMount = false + let hasComponentDidMount = false + let hasComponentDidShow = false + let hasComponentDidHide = false + let hasComponentWillUnmount = false + let hasJSX = false + let hasState = false + + const initPxTransformNode = toAst(`Taro.initPxTransform(${JSON.stringify(pxTransformConfig)})`) + const additionalConstructorNode = toAst(`Taro._set$app(this)`) + + ast = babel.transformFromAst(ast, '', { + plugins: [ + [require('babel-plugin-danger-remove-unused-import'), { ignore: ['@tarojs/taro', 'react', 'nervjs'] }] + ] + }).ast + + const ClassDeclarationOrExpression = { + enter (astPath) { + const node = astPath.node + if (!node.superClass) return + if ( + node.superClass.type === 'MemberExpression' && + node.superClass.object.name === taroImportDefaultName + ) { + node.superClass.object.name = taroImportDefaultName + if (node.id === null) { + const renameComponentClassName = '_TaroComponentClass' + astPath.replaceWith( + t.classExpression( + t.identifier(renameComponentClassName), + node.superClass, + node.body, + node.decorators || [] + ) + ) + } + } else if (node.superClass.name === 'Component') { + resetTSClassProperty(node.body.body) + if (node.id === null) { + const renameComponentClassName = '_TaroComponentClass' + astPath.replaceWith( + t.classExpression( + t.identifier(renameComponentClassName), + node.superClass, + node.body, + node.decorators || [] + ) + ) + } + } + } + } + + /** + * ProgramExit使用的visitor + * 负责修改render函数的内容,在componentDidMount中增加componentDidShow调用,在componentWillUnmount中增加componentDidHide调用。 + */ + const programExitVisitor = { + ClassMethod: { + exit (astPath) { + const node = astPath.node + const key = node.key + const keyName = getObjKey(key) + let funcBody + + const isRender = keyName === 'render' + const isComponentWillMount = keyName === 'componentWillMount' + const isComponentDidMount = keyName === 'componentDidMount' + const isComponentWillUnmount = keyName === 'componentWillUnmount' + const isConstructor = keyName === 'constructor' + const basename = JSON.stringify(addLeadingSlash(stripTrailingSlash(routerBasename))) + + if (isRender) { + const routes = pages.map((v, k) => { + const absPagename = addLeadingSlash(v) + const relPagename = `.${absPagename}` + const chunkName = relPagename.split('/').filter(v => !/^(pages|\.)$/i.test(v)).join('_') + return createRoute({ + absPagename, + relPagename, + chunkName, + isIndex: k === 0 + }) + }) + //@fix + funcBody = `` + + /* 插入Tabbar */ + if (tabBar) { + const homePage = pages[0] || '' + if (tabbarPos === 'top') { + funcBody = ` + <${tabBarContainerComponentName}> + <${tabBarComponentName} conf={${tabBarConfigName}} homePage="${homePage}" router={${taroImportDefaultName}}/> + <${tabBarPanelComponentName}> + ${funcBody} + + ` + } else { + funcBody = ` + <${tabBarContainerComponentName}> + + <${tabBarPanelComponentName}> + ${funcBody} + + + <${tabBarComponentName} + mode={${JSON.stringify(routerMode)}} + conf={this.state.${tabBarConfigName}} + homePage="${homePage}" + router={${taroImportDefaultName}} + basename={${basename}} /> + + ` + } + } + + /* 插入 */ + if (providerComponentName && storeName) { + // 使用redux 或 mobx + funcBody = ` + <${providorImportName} store={${storeName}}> + ${funcBody} + ` + } + + /* 插入 */ + node.body = toAst(`{return (${funcBody});}`, { preserveComments: true }) + } + + if (tabBar && isComponentWillMount) { + const initTabBarApisCallNode = toAst(`Taro.initTabBarApis(this, Taro)`) + astPath.get('body').pushContainer('body', initTabBarApisCallNode) + } + + if (hasConstructor && isConstructor) { + astPath.get('body').pushContainer('body', additionalConstructorNode) + } + + if (hasComponentDidShow && isComponentDidMount) { + const componentDidShowCallNode = toAst(`this.componentDidShow()`) + astPath.get('body').pushContainer('body', componentDidShowCallNode) + } + + if (hasComponentDidHide && isComponentWillUnmount) { + const componentDidHideCallNode = toAst(`this.componentDidHide()`) + astPath.get('body').unshiftContainer('body', componentDidHideCallNode) + } + } + }, + ClassProperty: { + exit (astPath) { + const node = astPath.node + const key = node.key + const value = node.value + if (key.name !== 'state' || !t.isObjectExpression(value)) return + astPath.node.value.properties.push(t.objectProperty( + t.identifier(tabBarConfigName), + tabBar + )) + } + }, + ClassBody: { + exit (astPath) { + if (hasComponentDidShow && !hasComponentDidMount) { + astPath.pushContainer('body', t.classMethod( + 'method', t.identifier('componentDidMount'), [], + t.blockStatement([]), false, false)) + } + if (hasComponentDidHide && !hasComponentWillUnmount) { + astPath.pushContainer('body', t.classMethod( + 'method', t.identifier('componentWillUnmount'), [], + t.blockStatement([]), false, false)) + } + //@fix + // if (!hasConstructor) { + // astPath.pushContainer('body', t.classMethod( + // 'method', t.identifier('constructor'), [t.identifier('props'), t.identifier('context')], + // t.blockStatement([toAst('super(props, context)'), additionalConstructorNode]), false, false)) + // } + if (tabBar) { + if (!hasComponentWillMount) { + astPath.pushContainer('body', t.classMethod( + 'method', t.identifier('componentWillMount'), [], + t.blockStatement([]), false, false)) + } + if (!hasState) { + astPath.unshiftContainer('body', t.classProperty( + t.identifier('state'), + t.objectExpression([]) + )) + } + } + } + } + } + + /** + * ClassProperty使用的visitor + * 负责收集config中的pages,收集tabbar的position,替换icon。 + */ + const classPropertyVisitor = { + ObjectProperty (astPath) { + const node = astPath.node + const key = node.key + const value = node.value + const keyName = getObjKey(key) + if (keyName === 'pages' && t.isArrayExpression(value)) { + const subPackageParent = astPath.findParent(isUnderSubPackages) + let root = '' + if (subPackageParent) { + /* 在subPackages属性下,说明是分包页面,需要处理root属性 */ + const rootNode = astPath.parent.properties.find(v => { + return getObjKey(v.key) === 'root' + }) + root = rootNode ? rootNode.value.value : '' + } + value.elements.forEach(v => { + const pagePath = `${root}/${v.value}`.replace(/\/{2,}/g, '/') + pages.push(pagePath.replace(/^\//, '')) + }) + } else if (keyName === 'tabBar' && t.isObjectExpression(value)) { + // tabBar + tabBar = value + value.properties.forEach(node => { + if (node.keyName === 'position') tabbarPos = node.value.value + }) + } else if ((keyName === 'iconPath' || keyName === 'selectedIconPath') && t.isStringLiteral(value)) { + astPath.replaceWith( + t.objectProperty(t.stringLiteral(keyName), t.callExpression(t.identifier('require'), [t.stringLiteral(`./${value.value}`)])) + ) + } + } + } + + traverse(ast, { + ClassExpression: ClassDeclarationOrExpression, + ClassDeclaration: ClassDeclarationOrExpression, + ClassProperty: { + enter (astPath) { + const node = astPath.node + const key = node.key + const value = node.value + const keyName = getObjKey(key) + + if (keyName === 'state') hasState = true + if (keyName !== 'config' || !t.isObjectExpression(value)) return + astPath.traverse(classPropertyVisitor) + } + }, + ImportDeclaration: { + enter (astPath) { + const node = astPath.node + const source = node.source + const specifiers = node.specifiers + let value = source.value + //@fix + if(value.endsWith('.css')){ + appCSS = fs.readFileSync(filePath.replace('.js','.css'), 'utf-8').replace(/\/\*[^*]*\*+([^/][^*]*\*+)*\//g, '') + // astPath.replaceWith(t.variableDeclaration('const',[t.variableDeclarator(t.identifier(`___css`),t.stringLiteral(appCSS))])) + astPath.remove() + return + } + if (Util.isAliasPath(value, pathAlias)) { + source.value = value = Util.replaceAliasPath(filePath, value, pathAlias) + } + if (!Util.isNpmPkg(value)) { + if (value.indexOf('.') === 0) { + const pathArr = value.split('/') + if (pathArr.indexOf('pages') >= 0) { + astPath.remove() + } else if (Util.REG_SCRIPTS.test(value)) { + const realPath = path.resolve(filePath, '..', value) + const dirname = path.dirname(realPath) + const extname = path.extname(realPath) + const removeExtPath = path.join(dirname, path.basename(realPath, extname)) + node.source = t.stringLiteral(Util.promoteRelativePath(path.relative(filePath, removeExtPath)).replace(/\\/g, '/')) + } + } + return + } + if (value === PACKAGES['@tarojs/taro']) { + let specifier = specifiers.find(item => item.type === 'ImportDefaultSpecifier') + if (specifier) { + hasAddNervJsImportDefaultName = true + taroImportDefaultName = specifier.local.name + specifier.local.name = nervJsImportDefaultName + } else if (!hasAddNervJsImportDefaultName) { + hasAddNervJsImportDefaultName = true + //@fix + // node.specifiers.unshift( + // t.importDefaultSpecifier(t.identifier(nervJsImportDefaultName)) + // ) + } + const taroApisSpecifiers = [] + const deletedIdx = [] + specifiers.forEach((item, index) => { + if (item.imported && taroApis.indexOf(item.imported.name) >= 0) { + taroApisSpecifiers.push(t.importSpecifier(t.identifier(item.local.name), t.identifier(item.imported.name))) + deletedIdx.push(index) + } + }) + _.pullAt(specifiers, deletedIdx) + source.value = PACKAGES['nervjs'] + + if (taroApisSpecifiers.length) { + astPath.insertBefore(t.importDeclaration(taroApisSpecifiers, t.stringLiteral(PACKAGES['@tarojs/taro-h5']))) + } + if (!specifiers.length) { + astPath.remove() + } + } else if (value === PACKAGES['@tarojs/redux']) { + const specifier = specifiers.find(item => { + return t.isImportSpecifier(item) && item.imported.name === providerComponentName + }) + if (specifier) { + providorImportName = specifier.local.name + } else { + providorImportName = providerComponentName + specifiers.push(t.importSpecifier(t.identifier(providerComponentName), t.identifier(providerComponentName))) + } + source.value = PACKAGES['@tarojs/redux-h5'] + } else if (value === PACKAGES['@tarojs/mobx']) { + const specifier = specifiers.find(item => { + return t.isImportSpecifier(item) && item.imported.name === providerComponentName + }) + if (specifier) { + providorImportName = specifier.local.name + } else { + providorImportName = providerComponentName + specifiers.push(t.importSpecifier(t.identifier(providerComponentName), t.identifier(providerComponentName))) + } + source.value = PACKAGES['@tarojs/mobx-h5'] + } + } + }, + CallExpression: { + enter (astPath) { + const node = astPath.node + const callee = node.callee + const calleeName = callee.name + const parentPath = astPath.parentPath + + if (t.isMemberExpression(callee)) { + if (callee.object.name === taroImportDefaultName && callee.property.name === 'render') { + callee.object.name = nervJsImportDefaultName + renderCallCode = generate(astPath.node).code + astPath.remove() + } + } else { + if (calleeName === setStoreFuncName) { + if (parentPath.isAssignmentExpression() || + parentPath.isExpressionStatement() || + parentPath.isVariableDeclarator()) { + parentPath.remove() + } + } + } + } + }, + ClassMethod: { + exit (astPath) { + const node = astPath.node + const key = node.key + const keyName = getObjKey(key) + if (keyName === 'constructor') { + hasConstructor = true + } else if (keyName === 'componentWillMount') { + hasComponentWillMount = true + } else if (keyName === 'componentDidMount') { + hasComponentDidMount = true + } else if (keyName === 'componentDidShow') { + hasComponentDidShow = true + } else if (keyName === 'componentDidHide') { + hasComponentDidHide = true + } else if (keyName === 'componentWillUnmount') { + hasComponentWillUnmount = true + } + } + }, + JSXElement: { + enter (astPath) { + hasJSX = true + } + }, + JSXOpeningElement: { + enter (astPath) { + if (astPath.node.name.name === 'Provider') { + for (let v of astPath.node.attributes) { + if (v.name.name !== 'store') continue + storeName = v.value.expression.name + break + } + } + } + }, + Program: { + exit (astPath) { + const importNervjsNode = t.importDefaultSpecifier(t.identifier(nervJsImportDefaultName)) + const importRouterNode = toAst(`import { Router } from '${PACKAGES['@tarojs/router']}'`) + //@fix + const importMpNode = toAst(`import './libs/mp'`) + const importTaroH5Node = toAst(`import ${taroImportDefaultName} from '${PACKAGES['@tarojs/taro-h5']}'`) + const importComponentNode = toAst(`import { View, ${tabBarComponentName}, ${tabBarContainerComponentName}, ${tabBarPanelComponentName}} from '${PACKAGES['@tarojs/components']}'`) + const lastImportIndex = _.findLastIndex(astPath.node.body, t.isImportDeclaration) + const lastImportNode = astPath.get(`body.${lastImportIndex > -1 ? lastImportIndex : 0}`) + const extraNodes = [ + //@fix + //importTaroH5Node, + importMpNode, + importRouterNode, + //@fix + //initPxTransformNode + ] + + astPath.traverse(programExitVisitor) + + if (hasJSX && !hasAddNervJsImportDefaultName) { + //@fix + //extraNodes.unshift(importNervjsNode) + } + if (tabBar) { + extraNodes.unshift(importComponentNode) + } + + lastImportNode.insertAfter(extraNodes) + if (renderCallCode) { + const renderCallNode = toAst(renderCallCode) + astPath.pushContainer('body', renderCallNode) + } + } + } + }) + const generateCode = generate(ast, { + jsescOption: { + minimal: true + } + }).code + return { + code: generateCode, + ast + } +} + +function processOthers (code, filePath, fileType) { + let ast = wxTransformer({ + code, + sourcePath: filePath, + isNormal: true, + isTyped: Util.REG_TYPESCRIPT.test(filePath), + adapter: 'h5' + }).ast + let taroImportDefaultName + let hasAddNervJsImportDefaultName = false + let hasJSX = false + let isPage = fileType === FILE_TYPE.PAGE + let hasComponentDidMount = false + let hasComponentDidShow = false + + ast = babel.transformFromAst(ast, '', { + plugins: [ + [require('babel-plugin-danger-remove-unused-import'), { ignore: ['@tarojs/taro', 'react', 'nervjs'] }] + ] + }).ast + + const ClassDeclarationOrExpression = { + enter (astPath) { + const node = astPath.node + if (!node.superClass) return + if ( + node.superClass.type === 'MemberExpression' && + node.superClass.object.name === taroImportDefaultName + ) { + node.superClass.object.name = taroImportDefaultName + if (node.id === null) { + const renameComponentClassName = '_TaroComponentClass' + astPath.replaceWith( + t.classExpression( + t.identifier(renameComponentClassName), + node.superClass, + node.body, + node.decorators || [] + ) + ) + } + } else if (node.superClass.name === 'Component') { + resetTSClassProperty(node.body.body) + if (node.id === null) { + const renameComponentClassName = '_TaroComponentClass' + astPath.replaceWith( + t.classExpression( + t.identifier(renameComponentClassName), + node.superClass, + node.body, + node.decorators || [] + ) + ) + } + } + } + } + + const programExitVisitor = { + ClassBody: { + exit (astPath) { + if (!hasComponentDidMount) { + astPath.pushContainer('body', t.classMethod( + 'method', t.identifier('componentDidMount'), [], + t.blockStatement([]), false, false)) + } + if (!hasComponentDidShow) { + astPath.pushContainer('body', t.classMethod( + 'method', t.identifier('componentDidShow'), [], + t.blockStatement([]), false, false)) + } + //@fix + astPath.unshiftContainer('body', t.classProperty( + t.identifier('static css'), + t.identifier('___css') + )) + } + } + } + + traverse(ast, { + ClassExpression: ClassDeclarationOrExpression, + ClassDeclaration: ClassDeclarationOrExpression, + ClassMethod: isPage ? { + exit (astPath) { + const node = astPath.node + const key = node.key + const keyName = getObjKey(key) + if (keyName === 'componentDidMount') { + hasComponentDidMount = true + } else if (keyName === 'componentDidShow') { + hasComponentDidShow = true + } + } + } : {}, + //@fix + ClassBody:{ + enter (astPath) { + astPath.unshiftContainer('body', t.classProperty( + t.identifier('static css'), + t.identifier('___css') + )) + } + }, + ImportDeclaration: { + enter (astPath) { + const node = astPath.node + const source = node.source + let value = source.value + const specifiers = node.specifiers + //@fix + if(value.endsWith('.css')){ + let css = fs.readFileSync(filePath.replace('.js','.css'), 'utf-8').replace(/\/\*[^*]*\*+([^/][^*]*\*+)*\//g, '') + //page里需要注入 appcss + if(filePath.indexOf('/src/pages/')!==-1||filePath.indexOf('\\src\\pages\\')!==-1){ + css = appCSS + css + } + astPath.replaceWith(t.variableDeclaration('const',[t.variableDeclarator(t.identifier(`___css`),t.callExpression(t.identifier('Omi.rpx'),[t.stringLiteral(compileWxss(css))]),)])) + return + } + if (Util.isAliasPath(value, pathAlias)) { + source.value = value = Util.replaceAliasPath(filePath, value, pathAlias) + } + if (!Util.isNpmPkg(value)) { + if (Util.REG_SCRIPTS.test(value)) { + const realPath = path.resolve(filePath, '..', value) + const dirname = path.dirname(realPath) + const extname = path.extname(realPath) + const removeExtPath = path.join(dirname, path.basename(realPath, extname)) + node.source = t.stringLiteral(Util.promoteRelativePath(path.relative(filePath, removeExtPath)).replace(/\\/g, '/')) + } + } else if (value === PACKAGES['@tarojs/taro']) { + let specifier = specifiers.find(item => item.type === 'ImportDefaultSpecifier') + if (specifier) { + hasAddNervJsImportDefaultName = true + taroImportDefaultName = specifier.local.name + specifier.local.name = nervJsImportDefaultName + } else if (!hasAddNervJsImportDefaultName) { + //@fix + //hasAddNervJsImportDefaultName = true + // node.specifiers.unshift( + // t.importDefaultSpecifier(t.identifier(nervJsImportDefaultName)) + // ) + } + const taroApisSpecifiers = [] + const deletedIdx = [] + specifiers.forEach((item, index) => { + if (item.imported && taroApis.indexOf(item.imported.name) >= 0) { + taroApisSpecifiers.push(t.importSpecifier(t.identifier(item.local.name), t.identifier(item.imported.name))) + deletedIdx.push(index) + } + }) + _.pullAt(specifiers, deletedIdx) + source.value = PACKAGES['nervjs'] + + if (taroApisSpecifiers.length) { + astPath.insertBefore(t.importDeclaration(taroApisSpecifiers, t.stringLiteral(PACKAGES['@tarojs/taro-h5']))) + } + if (!specifiers.length) { + astPath.remove() + } + } else if (value === PACKAGES['@tarojs/redux']) { + source.value = PACKAGES['@tarojs/redux-h5'] + } else if (value === PACKAGES['@tarojs/mobx']) { + source.value = PACKAGES['@tarojs/mobx-h5'] + } + } + }, + JSXElement: { + enter (astPath) { + hasJSX = true + } + }, + Program: { + exit (astPath) { + if (isPage) { + astPath.traverse(programExitVisitor) + } + const node = astPath.node + if (hasJSX && !hasAddNervJsImportDefaultName) { + //@fix + // node.body.unshift( + // t.importDeclaration([ + // t.importDefaultSpecifier(t.identifier(nervJsImportDefaultName)) + // ], t.stringLiteral(PACKAGES['nervjs'])) + // ) + } + if (taroImportDefaultName) { + const importTaro = toAst(`import ${taroImportDefaultName} from '${PACKAGES['@tarojs/taro-h5']}'`) + node.body.unshift(importTaro) + } + } + } + }) + const generateCode = generate(ast, { + jsescOption: { + minimal: true + } + }).code + return { + code: generateCode, + ast + } +} + +/** + * TS 编译器会把 class property 移到构造器, + * 而小程序要求 `config` 和所有函数在初始化(after new Class)之后就收集到所有的函数和 config 信息, + * 所以当如构造器里有 this.func = () => {...} 的形式,就给他转换成普通的 classProperty function + * 如果有 config 就给他还原 + */ +function resetTSClassProperty (body) { + for (const method of body) { + if (t.isClassMethod(method) && method.kind === 'constructor') { + for (const statement of _.cloneDeep(method.body.body)) { + if (t.isExpressionStatement(statement) && t.isAssignmentExpression(statement.expression)) { + const expr = statement.expression + const { left, right } = expr + if ( + t.isMemberExpression(left) && + t.isThisExpression(left.object) && + t.isIdentifier(left.property) + ) { + if ( + (t.isArrowFunctionExpression(right) || t.isFunctionExpression(right)) || + (left.property.name === 'config' && t.isObjectExpression(right)) + ) { + body.push( + t.classProperty(left.property, right) + ) + _.remove(method.body.body, statement) + } + } + } + } + } + } +} + +function classifyFiles (filename) { + const relPath = path.normalize( + path.relative(appPath, filename) + ) + if (path.relative(filename, entryFilePath) === '') return FILE_TYPE.ENTRY + + let relSrcPath = path.relative('src', relPath) + relSrcPath = path.format({ + dir: path.dirname(relSrcPath), + base: path.basename(relSrcPath, path.extname(relSrcPath)) + }) + + const isPage = pages.some(page => { + const relPage = path.normalize( + path.relative(appPath, page) + ) + if (path.relative(relPage, relSrcPath) === '') return true + }) + + if (isPage) { + return FILE_TYPE.PAGE + } else { + return FILE_TYPE.NORMAL + } +} + +function getDist (filename, isScriptFile) { + const dirname = path.dirname(filename) + const distDirname = dirname.replace(sourcePath, tempDir) + return isScriptFile + ? path.format({ + dir: distDirname, + ext: '.js', + name: path.basename(filename, path.extname(filename)) + }) + : path.format({ + dir: distDirname, + base: path.basename(filename) + }) +} + +function processFiles (filePath) { + const file = fs.readFileSync(filePath) + const dirname = path.dirname(filePath) + const extname = path.extname(filePath) + const distDirname = dirname.replace(sourcePath, tempDir) + const isScriptFile = Util.REG_SCRIPTS.test(extname) + const distPath = getDist(filePath, isScriptFile) + + try { + if (isScriptFile) { + // 脚本文件 处理一下 + const fileType = classifyFiles(filePath) + const content = file.toString() + const transformResult = fileType === FILE_TYPE.ENTRY + ? processEntry(content, filePath) + : processOthers(content, filePath, fileType) + const jsCode = transformResult.code + fs.ensureDirSync(distDirname) + fs.writeFileSync(distPath, Buffer.from(jsCode)) + } else { + // 其他 直接复制 + fs.ensureDirSync(distDirname) + fs.copySync(filePath, distPath) + } + } catch (e) { + console.log(e) + } +} + +function watchFiles () { + const watcher = chokidar.watch(path.join(sourcePath), { + ignored: /(^|[/\\])\../, + persistent: true, + ignoreInitial: true + }) + watcher + .on('add', filePath => { + pages = [] + const relativePath = path.relative(appPath, filePath) + Util.printLog(Util.pocessTypeEnum.CREATE, '添加文件', relativePath) + processFiles(filePath) + }) + .on('change', filePath => { + pages = [] + const relativePath = path.relative(appPath, filePath) + Util.printLog(Util.pocessTypeEnum.MODIFY, '文件变动', relativePath) + processFiles(filePath) + }) + .on('unlink', filePath => { + const relativePath = path.relative(appPath, filePath) + const extname = path.extname(relativePath) + const isScriptFile = Util.REG_SCRIPTS.test(extname) + const dist = getDist(filePath, isScriptFile) + Util.printLog(Util.pocessTypeEnum.UNLINK, '删除文件', relativePath) + fs.unlinkSync(dist) + }) +} + +function buildTemp () { + fs.ensureDirSync(tempPath) + return new Promise((resolve, reject) => { + klaw(sourcePath) + .on('data', file => { + const relativePath = path.relative(appPath, file.path) + if (!file.stats.isDirectory()) { + Util.printLog(Util.pocessTypeEnum.CREATE, '发现文件', relativePath) + processFiles(file.path) + } + }) + .on('end', () => { + resolve() + }) + }) +} + +async function buildDist (buildConfig) { + const { watch } = buildConfig + const entryFile = path.basename(entryFileName, path.extname(entryFileName)) + '.js' + const sourceRoot = projectConfig.sourceRoot || CONFIG.SOURCE_DIR + h5Config.env = projectConfig.env + Object.assign(h5Config.env, { + TARO_ENV: JSON.stringify(Util.BUILD_TYPES.H5) + }) + h5Config.defineConstants = projectConfig.defineConstants + h5Config.plugins = projectConfig.plugins + h5Config.designWidth = projectConfig.designWidth + if (projectConfig.deviceRatio) { + h5Config.deviceRatio = projectConfig.deviceRatio + } + h5Config.sourceRoot = sourceRoot + h5Config.outputRoot = outputDir + h5Config.entry = Object.assign({ + app: [path.join(tempPath, entryFile)] + }, h5Config.entry) + if (watch) { + h5Config.isWatch = true + } + const webpackRunner = await npmProcess.getNpmPkg('@tarojs/webpack-runner') + webpackRunner(h5Config) +} + +const pRimraf = promisify(rimraf) + +async function clean () { + try { + await pRimraf(tempPath) + await pRimraf(outputPath) + } catch (e) { + console.log(e) + } +} + +function copyFileSync (from, to, options) { + const filename = path.basename(from) + if (fs.statSync(from).isFile() && !path.extname(to)) { + fs.ensureDir(to) + return fs.copySync(from, path.join(to, filename), options) + } + fs.ensureDir(path.dirname(to)) + return fs.copySync(from, to, options) +} + +function copyFiles () { + const copyConfig = projectConfig.copy || { patterns: [], options: {} } + if (copyConfig.patterns && copyConfig.patterns.length) { + copyConfig.options = copyConfig.options || {} + const globalIgnore = copyConfig.options.ignore + const projectDir = appPath + copyConfig.patterns.forEach(pattern => { + if (typeof pattern === 'object' && pattern.from && pattern.to) { + const from = path.join(projectDir, pattern.from) + const to = path.join(projectDir, pattern.to) + let ignore = pattern.ignore || globalIgnore + if (fs.existsSync(from)) { + const copyOptions = {} + if (ignore) { + ignore = Array.isArray(ignore) ? ignore : [ignore] + copyOptions.filter = src => { + let isMatch = false + ignore.forEach(iPa => { + if (minimatch(path.basename(src), iPa)) { + isMatch = true + } + }) + return !isMatch + } + } + copyFileSync(from, to, copyOptions) + } else { + Util.printLog(Util.pocessTypeEnum.ERROR, '拷贝失败', `${pattern.from} 文件不存在!`) + } + } + }) + } +} + +async function build (buildConfig) { + process.env.TARO_ENV = Util.BUILD_TYPES.H5 + await clean() + copyFiles() + await buildTemp(buildConfig) + await buildDist(buildConfig) + if (buildConfig.watch) { + watchFiles() + } +} + +module.exports = { + build, + buildTemp, + processFiles +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/project.js b/packages/omi-cloudbase/scripts/taro-cli/src/project.js new file mode 100644 index 000000000..1a3ebcc33 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/project.js @@ -0,0 +1,173 @@ +const path = require('path') +const fs = require('fs-extra') +const chalk = require('chalk') +const inquirer = require('inquirer') +const semver = require('semver') + +const Creator = require('./creator') + +const { + shouldUseYarn, + shouldUseCnpm, + getPkgVersion +} = require('./util') +const { SOURCE_DIR } = require('./config') + +class Project extends Creator { + constructor (options) { + super() + const unSupportedVer = semver.lt(process.version, 'v7.6.0') + if (unSupportedVer) { + throw new Error('Node.js 版本过低,推荐升级 Node.js 至 v8.0.0+') + } + this.rootPath = this._rootPath + + this.conf = Object.assign({ + projectName: null, + template: null, + description: '' + }, options) + } + + init () { + console.log(chalk.green(`Taro即将创建一个新项目!`)) + console.log('Need help? Go and open issue: https://github.com/NervJS/taro/issues/new') + console.log() + } + + create () { + this.ask() + .then(answers => { + const date = new Date() + this.conf = Object.assign(this.conf, answers) + this.conf.date = `${date.getFullYear()}-${(date.getMonth() + 1)}-${date.getDate()}` + this.write() + }) + } + + ask () { + const prompts = [] + const conf = this.conf + if (typeof conf.projectName !== 'string') { + prompts.push({ + type: 'input', + name: 'projectName', + message: '请输入项目名称!', + validate (input) { + if (!input) { + return '项目名不能为空!' + } + if (fs.existsSync(input)) { + return '当前目录已经存在同名项目,请换一个项目名!' + } + return true + } + }) + } else if (fs.existsSync(conf.projectName)) { + prompts.push({ + type: 'input', + name: 'projectName', + message: '当前目录已经存在同名项目,请换一个项目名!', + validate (input) { + if (!input) { + return '项目名不能为空!' + } + if (fs.existsSync(input)) { + return '项目名依然重复!' + } + return true + } + }) + } + + if (typeof conf.description !== 'string') { + prompts.push({ + type: 'input', + name: 'description', + message: '请输入项目介绍!' + }) + } + + if (typeof conf.typescript !== 'boolean') { + prompts.push({ + type: 'confirm', + name: 'typescript', + message: '是否需要使用 TypeScript ?' + }) + } + + const cssChoices = [{ + name: 'Sass', + value: 'sass' + }, { + name: 'Less', + value: 'less' + }, { + name: 'Stylus', + value: 'stylus' + }, { + name: '无', + value: 'none' + }] + + if (typeof conf.css !== 'string') { + prompts.push({ + type: 'list', + name: 'css', + message: '请选择 CSS 预处理器(Sass/Less/Stylus)', + choices: cssChoices + }) + } + + const templateChoices = [{ + name: '默认模板', + value: 'default' + }, { + name: 'Redux 模板', + value: 'redux' + }, { + name: 'Mobx 模板', + value: 'mobx' + }] + + if (typeof conf.template !== 'string') { + prompts.push({ + type: 'list', + name: 'template', + message: '请选择模板', + choices: templateChoices + }) + } else { + let isTemplateExist = false + templateChoices.forEach(item => { + if (item.value === conf.template) { + isTemplateExist = true + } + }) + if (!isTemplateExist) { + console.log(chalk.red('你选择的模板不存在!')) + console.log(chalk.red('目前提供了以下模板以供使用:')) + console.log() + templateChoices.forEach(item => { + console.log(chalk.green(`- ${item.name}`)) + }) + process.exit(1) + } + } + + return inquirer.prompt(prompts) + } + + write (cb) { + const { template } = this.conf + this.conf.src = SOURCE_DIR + const templateCreate = require(path.join(this.templatePath(), template, 'index.js')) + templateCreate(this, this.conf, { + shouldUseYarn, + shouldUseCnpm, + getPkgVersion + }, cb) + } +} + +module.exports = Project diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn.js new file mode 100644 index 000000000..ac7a69944 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn.js @@ -0,0 +1,249 @@ +const fs = require('fs-extra') +const path = require('path') +const {performance} = require('perf_hooks') +const chokidar = require('chokidar') +const chalk = require('chalk') +const ejs = require('ejs') +const _ = require('lodash') +const shelljs = require('shelljs') +const klaw = require('klaw') + +const Util = require('./util') +const npmProcess = require('./util/npm') +const CONFIG = require('./config') +const {getPkgVersion} = require('./util') +const StyleProcess = require('./rn/styleProcess') +const {transformJSCode} = require('./rn/transformJS') + +const appPath = process.cwd() +const projectConfig = require(path.join(appPath, Util.PROJECT_CONFIG))(_.merge) +const sourceDirName = projectConfig.sourceRoot || CONFIG.SOURCE_DIR +const sourceDir = path.join(appPath, sourceDirName) +const tempDir = '.rn_temp' +const tempPath = path.join(appPath, tempDir) +const entryFilePath = Util.resolveScriptPath(path.join(sourceDir, CONFIG.ENTRY)) +const entryFileName = path.basename(entryFilePath) +const pluginsConfig = projectConfig.plugins || {} + +const pkgPath = path.join(__dirname, './rn/pkg') + +let depTree = {} + +let isBuildingStyles = {} +const styleDenpendencyTree = {} + +function isEntryFile (filePath) { + return path.basename(filePath) === entryFileName +} + +function compileDepStyles (filePath, styleFiles) { + if (isBuildingStyles[filePath] || styleFiles.length === 0) { + return Promise.resolve({}) + } + isBuildingStyles[filePath] = true + return Promise.all(styleFiles.map(async p => { // to css string + const filePath = path.join(p) + const fileExt = path.extname(filePath) + Util.printLog(Util.pocessTypeEnum.COMPILE, _.camelCase(fileExt).toUpperCase(), filePath) + return StyleProcess.loadStyle({filePath, pluginsConfig}) + })).then(resList => { // postcss + return Promise.all(resList.map(item => { + return StyleProcess.postCSS({...item, projectConfig}) + })) + }).then(resList => { + let styleObjectEntire = {} + resList.forEach(item => { + let styleObject = StyleProcess.getStyleObject({css: item.css, filePath: item.filePath}) + // validate styleObject + StyleProcess.validateStyle({styleObject, filePath: item.filePath}) + + Object.assign(styleObjectEntire, styleObject) + if (filePath !== entryFilePath) { // 非入口文件,合并全局样式 + Object.assign(styleObjectEntire, _.get(styleDenpendencyTree, [entryFilePath, 'styleObjectEntire'], {})) + } + styleDenpendencyTree[filePath] = { + styleFiles, + styleObjectEntire + } + }) + return JSON.stringify(styleObjectEntire, null, 2) + }).then(css => { + let tempFilePath = filePath.replace(sourceDir, tempPath) + const basename = path.basename(tempFilePath, path.extname(tempFilePath)) + tempFilePath = path.join(path.dirname(tempFilePath), `${basename}_styles.js`) + + StyleProcess.writeStyleFile({css, tempFilePath}) + }).catch((e) => { + throw new Error(e) + }) +} + +function initProjectFile () { + // generator app.json + const appJsonObject = Object.assign({}, { + expo: { + sdkVersion: '27.0.0' + } + }, projectConfig.rn && projectConfig.rn.appJson) + // generator .${tempPath}/package.json TODO JSON.parse 这种写法可能会有隐患 + const pkgTempObj = JSON.parse( + ejs.render( + fs.readFileSync(pkgPath, 'utf-8'), { + projectName: projectConfig.projectName, + version: getPkgVersion() + } + ).replace(/(\r\n|\n|\r|\s+)/gm, '') + ) + const dependencies = require(path.join(process.cwd(), 'package.json')).dependencies + pkgTempObj.dependencies = Object.assign({}, pkgTempObj.dependencies, dependencies) + // Copy bin/crna-entry.js ? + const crnaEntryPath = path.join(path.dirname(npmProcess.resolveNpmSync('@tarojs/rn-runner')), 'src/bin/crna-entry.js') + + fs.writeFileSync(path.join(tempDir, 'app.json'), JSON.stringify(appJsonObject, null, 2)) + Util.printLog(Util.pocessTypeEnum.GENERATE, 'app.json', path.join(tempPath, 'app.json')) + fs.writeFileSync(path.join(tempDir, 'package.json'), JSON.stringify(pkgTempObj, null, 2)) + Util.printLog(Util.pocessTypeEnum.GENERATE, 'package.json', path.join(tempPath, 'package.json')) + fs.copySync(crnaEntryPath, path.join(tempDir, 'bin/crna-entry.js')) + Util.printLog(Util.pocessTypeEnum.COPY, 'crna-entry.js', path.join(tempPath, 'bin/crna-entry.js')) +} + +async function processFile (filePath) { + if (!fs.existsSync(filePath)) { + return + } + const dirname = path.dirname(filePath) + const distDirname = dirname.replace(sourceDir, tempDir) + let distPath = path.format({dir: distDirname, base: path.basename(filePath)}) + const code = fs.readFileSync(filePath, 'utf-8') + if (Util.REG_STYLE.test(filePath)) { + // do something + } else if (Util.REG_SCRIPTS.test(filePath)) { + if (Util.REG_TYPESCRIPT.test(filePath)) { + distPath = distPath.replace(/\.(tsx|ts)(\?.*)?$/, '.js') + } + Util.printLog(Util.pocessTypeEnum.COMPILE, _.camelCase(path.extname(filePath)).toUpperCase(), filePath) + // transformJSCode + let transformResult = transformJSCode({code, filePath, isEntryFile: isEntryFile(filePath), projectConfig}) + const jsCode = transformResult.code + fs.ensureDirSync(distDirname) + fs.writeFileSync(distPath, Buffer.from(jsCode)) + // compileDepStyles + const styleFiles = transformResult.styleFiles + depTree[filePath] = styleFiles + await compileDepStyles(filePath, styleFiles) + } else { + fs.ensureDirSync(distDirname) + fs.copySync(filePath, distPath) + Util.printLog(Util.pocessTypeEnum.COPY, _.camelCase(path.extname(filePath)).toUpperCase(), filePath) + } +} + +function buildTemp () { + fs.ensureDirSync(path.join(tempPath, 'bin')) + return new Promise((resolve, reject) => { + klaw(sourceDir) + .on('data', file => { + if (!file.stats.isDirectory()) { + processFile(file.path) + } + }) + .on('end', () => { + initProjectFile() + if (!fs.existsSync(path.join(tempPath, 'node_modules'))) { + console.log() + console.log(chalk.yellow('开始安装依赖~')) + process.chdir(tempPath) + let command + if (Util.shouldUseYarn()) { + command = 'yarn' + } else if (Util.shouldUseCnpm()) { + command = 'cnpm install' + } else { + command = 'npm install' + } + shelljs.exec(command, {silent: false}) + } + resolve() + }) + }) +} + +async function buildDist ({watch}) { + const entry = { + app: path.join(tempPath, entryFileName) + } + const rnConfig = projectConfig.rn || {} + rnConfig.env = projectConfig.env + rnConfig.defineConstants = projectConfig.defineConstants + rnConfig.designWidth = projectConfig.designWidth + rnConfig.entry = entry + if (watch) { + rnConfig.isWatch = true + } + rnConfig.projectDir = tempPath + const rnRunner = await npmProcess.getNpmPkg('@tarojs/rn-runner') + rnRunner(rnConfig) +} + +async function perfWrap (callback, args) { + isBuildingStyles = {} // 清空 + // 后期可以优化,不编译全部 + let t0 = performance.now() + await callback(args) + let t1 = performance.now() + Util.printLog(Util.pocessTypeEnum.COMPILE, `编译完成,花费${Math.round(t1 - t0)} ms`) +} + +function watchFiles () { + const watcher = chokidar.watch(path.join(sourceDir), { + ignored: /(^|[/\\])\../, + persistent: true, + ignoreInitial: true + }) + + watcher + .on('ready', () => { + console.log() + console.log(chalk.gray('初始化完毕,监听文件修改中...')) + console.log() + }) + .on('add', filePath => { + const relativePath = path.relative(appPath, filePath) + Util.printLog(Util.pocessTypeEnum.CREATE, '添加文件', relativePath) + perfWrap(buildTemp) + }) + .on('change', filePath => { + const relativePath = path.relative(appPath, filePath) + Util.printLog(Util.pocessTypeEnum.MODIFY, '文件变动', relativePath) + if (Util.REG_SCRIPTS.test(filePath)) { + perfWrap(processFile, filePath) + } + if (Util.REG_STYLE.test(filePath)) { + _.forIn(depTree, (styleFiles, jsFilePath) => { + if (styleFiles.indexOf(filePath) > -1) { + perfWrap(processFile, jsFilePath) + } + }) + } + }) + .on('unlink', filePath => { + const relativePath = path.relative(appPath, filePath) + Util.printLog(Util.pocessTypeEnum.UNLINK, '删除文件', relativePath) + perfWrap(buildTemp) + }) + .on('error', error => console.log(`Watcher error: ${error}`)) +} + +async function build ({watch}) { + fs.ensureDirSync(tempPath) + let t0 = performance.now() + await buildTemp() + let t1 = performance.now() + Util.printLog(Util.pocessTypeEnum.COMPILE, `编译完成,花费${Math.round(t1 - t0)} ms`) + await buildDist({watch}) + if (watch) { + watchFiles() + } +} + +module.exports = {build} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ColorPropType.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ColorPropType.js new file mode 100644 index 000000000..3fecbc400 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ColorPropType.js @@ -0,0 +1,76 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +'use strict' + +const normalizeColor = require('./normalizeColor') + +const colorPropType = function ( + isRequired, + props, + propName, + componentName, + location, + propFullName +) { + const color = props[propName] + if (color === undefined || color === null) { + if (isRequired) { + return new Error( + 'Required ' + + location + + ' `' + + (propFullName || propName) + + '` was not specified in `' + + componentName + + '`.' + ) + } + return + } + + if (typeof color === 'number') { + // Developers should not use a number, but we are using the prop type + // both for user provided colors and for transformed ones. This isn't ideal + // and should be fixed but will do for now... + return + } + + if (normalizeColor(color) === null) { + return new Error( + 'Invalid ' + + location + + ' `' + + (propFullName || propName) + + '` supplied to `' + + componentName + + '`: ' + + color + + '\n' + + `Valid color formats are + - '#f0f' (#rgb) + - '#f0fc' (#rgba) + - '#ff00ff' (#rrggbb) + - '#ff00ff00' (#rrggbbaa) + - 'rgb(255, 255, 255)' + - 'rgba(255, 255, 255, 1.0)' + - 'hsl(360, 100%, 100%)' + - 'hsla(360, 100%, 100%, 1.0)' + - 'transparent' + - 'red' + - 0xff00ff00 (0xrrggbbaa) +` + ) + } +} + +const ColorPropType = colorPropType.bind(null, false /* isRequired */) +ColorPropType.isRequired = colorPropType.bind(null, true /* isRequired */) + +module.exports = ColorPropType diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ImageResizeMode.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ImageResizeMode.js new file mode 100644 index 000000000..50111bcd0 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ImageResizeMode.js @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + * @format + */ +'use strict' + +/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error + * found when Flow v0.54 was deployed. To see the error delete this comment and + * run Flow. */ +const keyMirror = require('fbjs/lib/keyMirror') + +/** + * ImageResizeMode - Enum for different image resizing modes, set via + * `resizeMode` style property on `` components. + */ +const ImageResizeMode = keyMirror({ + /** + * contain - The image will be resized such that it will be completely + * visible, contained within the frame of the View. + */ + contain: null, + /** + * cover - The image will be resized such that the entire area of the view + * is covered by the image, potentially clipping parts of the image. + */ + cover: null, + /** + * stretch - The image will be stretched to fill the entire frame of the + * view without clipping. This may change the aspect ratio of the image, + * distorting it. + */ + stretch: null, + /** + * center - The image will be scaled down such that it is completely visible, + * if bigger than the area of the view. + * The image will not be scaled up. + */ + center: null, + + /** + * repeat - The image will be repeated to cover the frame of the View. The + * image will keep it's size and aspect ratio. + */ + repeat: null +}) + +module.exports = ImageResizeMode diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ImageStylePropTypes.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ImageStylePropTypes.js new file mode 100644 index 000000000..4f687539c --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ImageStylePropTypes.js @@ -0,0 +1,62 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + * @format + */ +'use strict' + +const ColorPropType = require('./ColorPropType') +const ImageResizeMode = require('./ImageResizeMode') +const LayoutPropTypes = require('./LayoutPropTypes') +const ReactPropTypes = require('prop-types') +const ShadowPropTypesIOS = require('./ShadowPropTypesIOS') +const TransformPropTypes = require('./TransformPropTypes') + +const ImageStylePropTypes = { + ...LayoutPropTypes, + ...ShadowPropTypesIOS, + ...TransformPropTypes, + resizeMode: ReactPropTypes.oneOf(Object.keys(ImageResizeMode)), + backfaceVisibility: ReactPropTypes.oneOf(['visible', 'hidden']), + backgroundColor: ColorPropType, + borderColor: ColorPropType, + borderWidth: ReactPropTypes.number, + borderRadius: ReactPropTypes.number, + overflow: ReactPropTypes.oneOf(['visible', 'hidden']), + + /** + * Changes the color of all the non-transparent pixels to the tintColor. + */ + tintColor: ColorPropType, + opacity: ReactPropTypes.number, + /** + * When the image has rounded corners, specifying an overlayColor will + * cause the remaining space in the corners to be filled with a solid color. + * This is useful in cases which are not supported by the Android + * implementation of rounded corners: + * - Certain resize modes, such as 'contain' + * - Animated GIFs + * + * A typical way to use this prop is with images displayed on a solid + * background and setting the `overlayColor` to the same color + * as the background. + * + * For details of how this works under the hood, see + * http://frescolib.org/docs/rounded-corners-and-circles.html + * + * @platform android + */ + overlayColor: ReactPropTypes.string, + + // Android-Specific styles + borderTopLeftRadius: ReactPropTypes.number, + borderTopRightRadius: ReactPropTypes.number, + borderBottomLeftRadius: ReactPropTypes.number, + borderBottomRightRadius: ReactPropTypes.number +} + +module.exports = ImageStylePropTypes diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/LayoutPropTypes.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/LayoutPropTypes.js new file mode 100644 index 000000000..c6192548f --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/LayoutPropTypes.js @@ -0,0 +1,561 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * strict + */ + +'use strict' + +const ReactPropTypes = require('prop-types') + +/** + * React Native's layout system is based on Flexbox and is powered both + * on iOS and Android by an open source project called `Yoga`: + * https://github.com/facebook/yoga + * + * The implementation in Yoga is slightly different from what the + * Flexbox spec defines - for example, we chose more sensible default + * values. Since our layout docs are generated from the comments in this + * file, please keep a brief comment describing each prop type. + * + * These properties are a subset of our styles that are consumed by the layout + * algorithm and affect the positioning and sizing of views. + */ +const LayoutPropTypes = { + /** `display` sets the display type of this component. + * + * It works similarly to `display` in CSS, but only support 'flex' and 'none'. + * 'flex' is the default. + */ + display: ReactPropTypes.oneOf(['none', 'flex']), + + /** `width` sets the width of this component. + * + * It works similarly to `width` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/width for more details. + */ + width: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `height` sets the height of this component. + * + * It works similarly to `height` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/height for more details. + */ + height: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** + * When the direction is `ltr`, `start` is equivalent to `left`. + * When the direction is `rtl`, `start` is equivalent to `right`. + * + * This style takes precedence over the `left`, `right`, and `end` styles. + */ + start: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** + * When the direction is `ltr`, `end` is equivalent to `right`. + * When the direction is `rtl`, `end` is equivalent to `left`. + * + * This style takes precedence over the `left` and `right` styles. + */ + end: ReactPropTypes.oneOfType([ReactPropTypes.number, ReactPropTypes.string]), + + /** `top` is the number of logical pixels to offset the top edge of + * this component. + * + * It works similarly to `top` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/top + * for more details of how `top` affects layout. + */ + top: ReactPropTypes.oneOfType([ReactPropTypes.number, ReactPropTypes.string]), + + /** `left` is the number of logical pixels to offset the left edge of + * this component. + * + * It works similarly to `left` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/left + * for more details of how `left` affects layout. + */ + left: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `right` is the number of logical pixels to offset the right edge of + * this component. + * + * It works similarly to `right` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/right + * for more details of how `right` affects layout. + */ + right: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `bottom` is the number of logical pixels to offset the bottom edge of + * this component. + * + * It works similarly to `bottom` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/bottom + * for more details of how `bottom` affects layout. + */ + bottom: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `minWidth` is the minimum width for this component, in logical pixels. + * + * It works similarly to `min-width` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/min-width + * for more details. + */ + minWidth: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `maxWidth` is the maximum width for this component, in logical pixels. + * + * It works similarly to `max-width` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/max-width + * for more details. + */ + maxWidth: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `minHeight` is the minimum height for this component, in logical pixels. + * + * It works similarly to `min-height` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/min-height + * for more details. + */ + minHeight: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `maxHeight` is the maximum height for this component, in logical pixels. + * + * It works similarly to `max-height` in CSS, but in React Native you + * must use points or percentages. Ems and other units are not supported. + * + * See https://developer.mozilla.org/en-US/docs/Web/CSS/max-height + * for more details. + */ + maxHeight: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** Setting `margin` has the same effect as setting each of + * `marginTop`, `marginLeft`, `marginBottom`, and `marginRight`. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/margin + * for more details. + */ + margin: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** Setting `marginVertical` has the same effect as setting both + * `marginTop` and `marginBottom`. + */ + marginVertical: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** Setting `marginHorizontal` has the same effect as setting + * both `marginLeft` and `marginRight`. + */ + marginHorizontal: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `marginTop` works like `margin-top` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top + * for more details. + */ + marginTop: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `marginBottom` works like `margin-bottom` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom + * for more details. + */ + marginBottom: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `marginLeft` works like `margin-left` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left + * for more details. + */ + marginLeft: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `marginRight` works like `margin-right` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right + * for more details. + */ + marginRight: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** + * When direction is `ltr`, `marginStart` is equivalent to `marginLeft`. + * When direction is `rtl`, `marginStart` is equivalent to `marginRight`. + */ + marginStart: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** + * When direction is `ltr`, `marginEnd` is equivalent to `marginRight`. + * When direction is `rtl`, `marginEnd` is equivalent to `marginLeft`. + */ + marginEnd: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** Setting `padding` has the same effect as setting each of + * `paddingTop`, `paddingBottom`, `paddingLeft`, and `paddingRight`. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/padding + * for more details. + */ + padding: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** Setting `paddingVertical` is like setting both of + * `paddingTop` and `paddingBottom`. + */ + paddingVertical: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** Setting `paddingHorizontal` is like setting both of + * `paddingLeft` and `paddingRight`. + */ + paddingHorizontal: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `paddingTop` works like `padding-top` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top + * for more details. + */ + paddingTop: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `paddingBottom` works like `padding-bottom` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-bottom + * for more details. + */ + paddingBottom: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `paddingLeft` works like `padding-left` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-left + * for more details. + */ + paddingLeft: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `paddingRight` works like `padding-right` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/padding-right + * for more details. + */ + paddingRight: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** + * When direction is `ltr`, `paddingStart` is equivalent to `paddingLeft`. + * When direction is `rtl`, `paddingStart` is equivalent to `paddingRight`. + */ + paddingStart: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** + * When direction is `ltr`, `paddingEnd` is equivalent to `paddingRight`. + * When direction is `rtl`, `paddingEnd` is equivalent to `paddingLeft`. + */ + paddingEnd: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** `borderWidth` works like `border-width` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/border-width + * for more details. + */ + borderWidth: ReactPropTypes.number, + + /** `borderTopWidth` works like `border-top-width` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width + * for more details. + */ + borderTopWidth: ReactPropTypes.number, + + /** + * When direction is `ltr`, `borderStartWidth` is equivalent to `borderLeftWidth`. + * When direction is `rtl`, `borderStartWidth` is equivalent to `borderRightWidth`. + */ + borderStartWidth: ReactPropTypes.number, + + /** + * When direction is `ltr`, `borderEndWidth` is equivalent to `borderRightWidth`. + * When direction is `rtl`, `borderEndWidth` is equivalent to `borderLeftWidth`. + */ + borderEndWidth: ReactPropTypes.number, + + /** `borderRightWidth` works like `border-right-width` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-width + * for more details. + */ + borderRightWidth: ReactPropTypes.number, + + /** `borderBottomWidth` works like `border-bottom-width` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-width + * for more details. + */ + borderBottomWidth: ReactPropTypes.number, + + /** `borderLeftWidth` works like `border-left-width` in CSS. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width + * for more details. + */ + borderLeftWidth: ReactPropTypes.number, + + /** `position` in React Native is similar to regular CSS, but + * everything is set to `relative` by default, so `absolute` + * positioning is always just relative to the parent. + * + * If you want to position a child using specific numbers of logical + * pixels relative to its parent, set the child to have `absolute` + * position. + * + * If you want to position a child relative to something + * that is not its parent, just don't use styles for that. Use the + * component tree. + * + * See https://github.com/facebook/yoga + * for more details on how `position` differs between React Native + * and CSS. + */ + position: ReactPropTypes.oneOf(['absolute', 'relative']), + + /** `flexDirection` controls which directions children of a container go. + * `row` goes left to right, `column` goes top to bottom, and you may + * be able to guess what the other two do. It works like `flex-direction` + * in CSS, except the default is `column`. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction + * for more details. + */ + flexDirection: ReactPropTypes.oneOf([ + 'row', + 'row-reverse', + 'column', + 'column-reverse' + ]), + + /** `flexWrap` controls whether children can wrap around after they + * hit the end of a flex container. + * It works like `flex-wrap` in CSS (default: nowrap). + * See https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap + * for more details. + */ + flexWrap: ReactPropTypes.oneOf(['wrap', 'nowrap', 'wrap-reverse']), + + /** `justifyContent` aligns children in the main direction. + * For example, if children are flowing vertically, `justifyContent` + * controls how they align vertically. + * It works like `justify-content` in CSS (default: flex-start). + * See https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content + * for more details. + */ + justifyContent: ReactPropTypes.oneOf([ + 'flex-start', + 'flex-end', + 'center', + 'space-between', + 'space-around', + 'space-evenly' + ]), + + /** `alignItems` aligns children in the cross direction. + * For example, if children are flowing vertically, `alignItems` + * controls how they align horizontally. + * It works like `align-items` in CSS (default: stretch). + * See https://developer.mozilla.org/en-US/docs/Web/CSS/align-items + * for more details. + */ + alignItems: ReactPropTypes.oneOf([ + 'flex-start', + 'flex-end', + 'center', + 'stretch', + 'baseline' + ]), + + /** `alignSelf` controls how a child aligns in the cross direction, + * overriding the `alignItems` of the parent. It works like `align-self` + * in CSS (default: auto). + * See https://developer.mozilla.org/en-US/docs/Web/CSS/align-self + * for more details. + */ + alignSelf: ReactPropTypes.oneOf([ + 'auto', + 'flex-start', + 'flex-end', + 'center', + 'stretch', + 'baseline' + ]), + + /** `alignContent` controls how rows align in the cross direction, + * overriding the `alignContent` of the parent. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/align-content + * for more details. + */ + alignContent: ReactPropTypes.oneOf([ + 'flex-start', + 'flex-end', + 'center', + 'stretch', + 'space-between', + 'space-around' + ]), + + /** `overflow` controls how children are measured and displayed. + * `overflow: hidden` causes views to be clipped while `overflow: scroll` + * causes views to be measured independently of their parents main axis. + * It works like `overflow` in CSS (default: visible). + * See https://developer.mozilla.org/en/docs/Web/CSS/overflow + * for more details. + * `overflow: visible` only works on iOS. On Android, all views will clip + * their children. + */ + overflow: ReactPropTypes.oneOf(['visible', 'hidden', 'scroll']), + + /** In React Native `flex` does not work the same way that it does in CSS. + * `flex` is a number rather than a string, and it works + * according to the `Yoga` library + * at https://github.com/facebook/yoga + * + * When `flex` is a positive number, it makes the component flexible + * and it will be sized proportional to its flex value. So a + * component with `flex` set to 2 will take twice the space as a + * component with `flex` set to 1. + * + * When `flex` is 0, the component is sized according to `width` + * and `height` and it is inflexible. + * + * When `flex` is -1, the component is normally sized according + * `width` and `height`. However, if there's not enough space, + * the component will shrink to its `minWidth` and `minHeight`. + * + * flexGrow, flexShrink, and flexBasis work the same as in CSS. + */ + flex: ReactPropTypes.number, + flexGrow: ReactPropTypes.number, + flexShrink: ReactPropTypes.number, + flexBasis: ReactPropTypes.oneOfType([ + ReactPropTypes.number, + ReactPropTypes.string + ]), + + /** + * Aspect ratio control the size of the undefined dimension of a node. Aspect ratio is a + * non-standard property only available in react native and not CSS. + * + * - On a node with a set width/height aspect ratio control the size of the unset dimension + * - On a node with a set flex basis aspect ratio controls the size of the node in the cross axis + * if unset + * - On a node with a measure function aspect ratio works as though the measure function measures + * the flex basis + * - On a node with flex grow/shrink aspect ratio controls the size of the node in the cross axis + * if unset + * - Aspect ratio takes min/max dimensions into account + */ + aspectRatio: ReactPropTypes.number, + + /** `zIndex` controls which components display on top of others. + * Normally, you don't use `zIndex`. Components render according to + * their order in the document tree, so later components draw over + * earlier ones. `zIndex` may be useful if you have animations or custom + * modal interfaces where you don't want this behavior. + * + * It works like the CSS `z-index` property - components with a larger + * `zIndex` will render on top. Think of the z-direction like it's + * pointing from the phone into your eyeball. + * See https://developer.mozilla.org/en-US/docs/Web/CSS/z-index for + * more details. + */ + zIndex: ReactPropTypes.number, + + /** `direction` specifies the directional flow of the user interface. + * The default is `inherit`, except for root node which will have + * value based on the current locale. + * See https://facebook.github.io/yoga/docs/rtl/ + * for more details. + * @platform ios + */ + direction: ReactPropTypes.oneOf(['inherit', 'ltr', 'rtl']) +} + +module.exports = LayoutPropTypes diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ShadowPropTypesIOS.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ShadowPropTypesIOS.js new file mode 100644 index 000000000..538e2c5f6 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ShadowPropTypesIOS.js @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * + * @format + */ +'use strict' + +const ColorPropType = require('./ColorPropType') +const ReactPropTypes = require('prop-types') + +/** + * These props can be used to dynamically generate shadows on views, images, text, etc. + * + * Because they are dynamically generated, they may cause performance regressions. Static + * shadow image asset may be a better way to go for optimal performance. + * + * These properties are iOS only - for similar functionality on Android, use the [`elevation` + * property](docs/viewstyleproptypes.html#elevation). + */ +const ShadowPropTypesIOS = { + /** + * Sets the drop shadow color + * @platform ios + */ + shadowColor: ColorPropType, + /** + * Sets the drop shadow offset + * @platform ios + */ + shadowOffset: ReactPropTypes.shape({ + width: ReactPropTypes.number, + height: ReactPropTypes.number + }), + /** + * Sets the drop shadow opacity (multiplied by the color's alpha component) + * @platform ios + */ + shadowOpacity: ReactPropTypes.number, + /** + * Sets the drop shadow blur radius + * @platform ios + */ + shadowRadius: ReactPropTypes.number +} + +module.exports = ShadowPropTypesIOS diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/StyleSheetValidation.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/StyleSheetValidation.js new file mode 100644 index 000000000..5e3856341 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/StyleSheetValidation.js @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * + */ + +'use strict' + +const ImageStylePropTypes = require('./ImageStylePropTypes') +const TextStylePropTypes = require('./TextStylePropTypes') +const ViewStylePropTypes = require('./ViewStylePropTypes') + +const invariant = require('fbjs/lib/invariant') + +// Hardcoded because this is a legit case but we don't want to load it from +// a private API. We might likely want to unify style sheet creation with how it +// is done in the DOM so this might move into React. I know what I'm doing so +// plz don't fire me. +const ReactPropTypesSecret = 'SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED' + +class StyleSheetValidation { + static validateStyleProp (prop, style, caller) { + if (allStylePropTypes[prop] === undefined) { + const message1 = '"' + prop + '" is not a valid style property.' + const message2 = + '\nValid style props: ' + + JSON.stringify(Object.keys(allStylePropTypes).sort(), null, ' ') + styleError(message1, style, caller, message2) + } + const error = allStylePropTypes[prop]( + style, + prop, + caller, + 'prop', + null, + ReactPropTypesSecret + ) + if (error) { + styleError(error.message, style, caller) + } + } + + static validateStyle (name, styles) { + for (const prop in styles[name]) { + StyleSheetValidation.validateStyleProp( + prop, + styles[name], + 'StyleSheet ' + name + ) + } + } + + static addValidStylePropTypes (stylePropTypes) { + for (const key in stylePropTypes) { + allStylePropTypes[key] = stylePropTypes[key] + } + } +} + +const styleError = function (message1, style, caller, message2) { + invariant( + false, + message1 + + '\n' + + (caller || '<>') + + ': ' + + JSON.stringify(style, null, ' ') + + (message2 || '') + ) +} + +const allStylePropTypes = {} + +StyleSheetValidation.addValidStylePropTypes(ImageStylePropTypes) +StyleSheetValidation.addValidStylePropTypes(TextStylePropTypes) +StyleSheetValidation.addValidStylePropTypes(ViewStylePropTypes) + +module.exports = StyleSheetValidation diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/TextStylePropTypes.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/TextStylePropTypes.js new file mode 100644 index 000000000..1935170cf --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/TextStylePropTypes.js @@ -0,0 +1,123 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * + */ + +'use strict' + +const ColorPropType = require('./ColorPropType') +const ReactPropTypes = require('prop-types') +const ViewStylePropTypes = require('./ViewStylePropTypes') + +const TextStylePropTypes = { + ...ViewStylePropTypes, + + color: ColorPropType, + fontFamily: ReactPropTypes.string, + fontSize: ReactPropTypes.number, + fontStyle: ReactPropTypes.oneOf(['normal', 'italic']), + /** + * Specifies font weight. The values 'normal' and 'bold' are supported for + * most fonts. Not all fonts have a variant for each of the numeric values, + * in that case the closest one is chosen. + */ + fontWeight: ReactPropTypes.oneOf([ + 'normal' /* default */, + 'bold', + '100', + '200', + '300', + '400', + '500', + '600', + '700', + '800', + '900' + ]), + /** + * @platform ios + */ + fontVariant: ReactPropTypes.arrayOf( + ReactPropTypes.oneOf([ + 'small-caps', + 'oldstyle-nums', + 'lining-nums', + 'tabular-nums', + 'proportional-nums' + ]) + ), + textShadowOffset: ReactPropTypes.shape({ + width: ReactPropTypes.number, + height: ReactPropTypes.number + }), + textShadowRadius: ReactPropTypes.number, + textShadowColor: ColorPropType, + /** + * @platform ios + */ + letterSpacing: ReactPropTypes.number, + lineHeight: ReactPropTypes.number, + /** + * Specifies text alignment. The value 'justify' is only supported on iOS and + * fallbacks to `left` on Android. + */ + textAlign: ReactPropTypes.oneOf([ + 'auto' /* default */, + 'left', + 'right', + 'center', + 'justify' + ]), + /** + * @platform android + */ + textAlignVertical: ReactPropTypes.oneOf([ + 'auto' /* default */, + 'top', + 'bottom', + 'center' + ]), + /** + * Set to `false` to remove extra font padding intended to make space for certain ascenders / descenders. + * With some fonts, this padding can make text look slightly misaligned when centered vertically. + * For best results also set `textAlignVertical` to `center`. Default is true. + * @platform android + */ + includeFontPadding: ReactPropTypes.bool, + textDecorationLine: ReactPropTypes.oneOf([ + 'none' /* default */, + 'underline', + 'line-through', + 'underline line-through' + ]), + /** + * @platform ios + */ + textDecorationStyle: ReactPropTypes.oneOf([ + 'solid' /* default */, + 'double', + 'dotted', + 'dashed' + ]), + /** + * @platform ios + */ + textDecorationColor: ColorPropType, + textTransform: ReactPropTypes.oneOf([ + 'none' /* default */, + 'capitalize', + 'uppercase', + 'lowercase' + ]), + /** + * @platform ios + */ + writingDirection: ReactPropTypes.oneOf(['auto' /* default */, 'ltr', 'rtl']) +} + +module.exports = TextStylePropTypes diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/TransformPropTypes.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/TransformPropTypes.js new file mode 100644 index 000000000..21f612aef --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/TransformPropTypes.js @@ -0,0 +1,109 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * + */ + +'use strict' + +const ReactPropTypes = require('prop-types') + +const deprecatedPropType = require('./deprecatedPropType') + +const TransformMatrixPropType = function ( + props, + propName, + componentName +) { + if (props[propName]) { + return new Error( + 'The transformMatrix style property is deprecated. ' + + 'Use `transform: [{ matrix: ... }]` instead.' + ) + } +} + +const DecomposedMatrixPropType = function ( + props, + propName, + componentName +) { + if (props[propName]) { + return new Error( + 'The decomposedMatrix style property is deprecated. ' + + 'Use `transform: [...]` instead.' + ) + } +} + +const TransformPropTypes = { + /** + * `transform` accepts an array of transformation objects. Each object specifies + * the property that will be transformed as the key, and the value to use in the + * transformation. Objects should not be combined. Use a single key/value pair + * per object. + * + * The rotate transformations require a string so that the transform may be + * expressed in degrees (deg) or radians (rad). For example: + * + * `transform([{ rotateX: '45deg' }, { rotateZ: '0.785398rad' }])` + * + * The skew transformations require a string so that the transform may be + * expressed in degrees (deg). For example: + * + * `transform([{ skewX: '45deg' }])` + */ + transform: ReactPropTypes.arrayOf( + ReactPropTypes.oneOfType([ + ReactPropTypes.shape({perspective: ReactPropTypes.number}), + ReactPropTypes.shape({rotate: ReactPropTypes.string}), + ReactPropTypes.shape({rotateX: ReactPropTypes.string}), + ReactPropTypes.shape({rotateY: ReactPropTypes.string}), + ReactPropTypes.shape({rotateZ: ReactPropTypes.string}), + ReactPropTypes.shape({scale: ReactPropTypes.number}), + ReactPropTypes.shape({scaleX: ReactPropTypes.number}), + ReactPropTypes.shape({scaleY: ReactPropTypes.number}), + ReactPropTypes.shape({translateX: ReactPropTypes.number}), + ReactPropTypes.shape({translateY: ReactPropTypes.number}), + ReactPropTypes.shape({skewX: ReactPropTypes.string}), + ReactPropTypes.shape({skewY: ReactPropTypes.string}) + ]) + ), + + /** + * Deprecated. Use the transform prop instead. + */ + transformMatrix: TransformMatrixPropType, + /** + * Deprecated. Use the transform prop instead. + */ + decomposedMatrix: DecomposedMatrixPropType, + + /* Deprecated transform props used on Android only */ + scaleX: deprecatedPropType( + ReactPropTypes.number, + 'Use the transform prop instead.' + ), + scaleY: deprecatedPropType( + ReactPropTypes.number, + 'Use the transform prop instead.' + ), + rotation: deprecatedPropType( + ReactPropTypes.number, + 'Use the transform prop instead.' + ), + translateX: deprecatedPropType( + ReactPropTypes.number, + 'Use the transform prop instead.' + ), + translateY: deprecatedPropType( + ReactPropTypes.number, + 'Use the transform prop instead.' + ) +} + +module.exports = TransformPropTypes diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ViewStylePropTypes.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ViewStylePropTypes.js new file mode 100644 index 000000000..889c50740 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/ViewStylePropTypes.js @@ -0,0 +1,61 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * + */ + +'use strict' + +const ColorPropType = require('./ColorPropType') +const LayoutPropTypes = require('./LayoutPropTypes') +const ReactPropTypes = require('prop-types') +const ShadowPropTypesIOS = require('./ShadowPropTypesIOS') +const TransformPropTypes = require('./TransformPropTypes') + +/** + * Warning: Some of these properties may not be supported in all releases. + */ +const ViewStylePropTypes = { + ...LayoutPropTypes, + ...ShadowPropTypesIOS, + ...TransformPropTypes, + backfaceVisibility: ReactPropTypes.oneOf(['visible', 'hidden']), + backgroundColor: ColorPropType, + borderColor: ColorPropType, + borderTopColor: ColorPropType, + borderRightColor: ColorPropType, + borderBottomColor: ColorPropType, + borderLeftColor: ColorPropType, + borderStartColor: ColorPropType, + borderEndColor: ColorPropType, + borderRadius: ReactPropTypes.number, + borderTopLeftRadius: ReactPropTypes.number, + borderTopRightRadius: ReactPropTypes.number, + borderTopStartRadius: ReactPropTypes.number, + borderTopEndRadius: ReactPropTypes.number, + borderBottomLeftRadius: ReactPropTypes.number, + borderBottomRightRadius: ReactPropTypes.number, + borderBottomStartRadius: ReactPropTypes.number, + borderBottomEndRadius: ReactPropTypes.number, + borderStyle: ReactPropTypes.oneOf(['solid', 'dotted', 'dashed']), + borderWidth: ReactPropTypes.number, + borderTopWidth: ReactPropTypes.number, + borderRightWidth: ReactPropTypes.number, + borderBottomWidth: ReactPropTypes.number, + borderLeftWidth: ReactPropTypes.number, + opacity: ReactPropTypes.number, + /** + * (Android-only) Sets the elevation of a view, using Android's underlying + * [elevation API](https://developer.android.com/training/material/shadows-clipping.html#Elevation). + * This adds a drop shadow to the item and affects z-order for overlapping views. + * Only supported on Android 5.0+, has no effect on earlier versions. + * @platform android + */ + elevation: ReactPropTypes.number +} + +module.exports = ViewStylePropTypes diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/deprecatedPropType.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/deprecatedPropType.js new file mode 100644 index 000000000..3a62f2d5c --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/deprecatedPropType.js @@ -0,0 +1,35 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * strict-local + */ + +'use strict' + +// const UIManager = require('UIManager') + +/** + * Adds a deprecation warning when the prop is used. + */ +function deprecatedPropType ( + propType, + explanation +) { + return function validate (props, propName, componentName, ...rest) { + // Don't warn for native components. + // if (!UIManager[componentName] && props[propName] !== undefined) { + if (props[propName] !== undefined) { + console.warn( + `\`${propName}\` supplied to \`${componentName}\` has been deprecated. ${explanation}` + ) + } + + return propType(props, propName, componentName, ...rest) + } +} + +module.exports = deprecatedPropType diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/index.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/index.js new file mode 100644 index 000000000..325863b24 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/index.js @@ -0,0 +1,3 @@ +const StyleSheetValidation = require('./StyleSheetValidation') + +module.exports = {StyleSheetValidation} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/normalizeColor.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/normalizeColor.js new file mode 100644 index 000000000..b4a117a04 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/StyleSheet/normalizeColor.js @@ -0,0 +1,372 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + * + */ + +/* eslint no-bitwise: 0 */ +'use strict' + +function normalizeColor (color) { + const matchers = getMatchers() + let match + + if (typeof color === 'number') { + if (color >>> 0 === color && color >= 0 && color <= 0xffffffff) { + return color + } + return null + } + + // Ordered based on occurrences on Facebook codebase + if ((match = matchers.hex6.exec(color))) { + return parseInt(match[1] + 'ff', 16) >>> 0 + } + + if (names.hasOwnProperty(color)) { + return names[color] + } + + if ((match = matchers.rgb.exec(color))) { + return ( + // b + ((parse255(match[1]) << 24) | // r + (parse255(match[2]) << 16) | // g + (parse255(match[3]) << 8) | + 0x000000ff) >>> // a + 0 + ) + } + + if ((match = matchers.rgba.exec(color))) { + return ( + // b + ((parse255(match[1]) << 24) | // r + (parse255(match[2]) << 16) | // g + (parse255(match[3]) << 8) | + parse1(match[4])) >>> // a + 0 + ) + } + + if ((match = matchers.hex3.exec(color))) { + return ( + parseInt( + match[1] + + match[1] + // r + match[2] + + match[2] + // g + match[3] + + match[3] + // b + 'ff', // a + 16 + ) >>> 0 + ) + } + + // https://drafts.csswg.org/css-color-4/#hex-notation + if ((match = matchers.hex8.exec(color))) { + return parseInt(match[1], 16) >>> 0 + } + + if ((match = matchers.hex4.exec(color))) { + return ( + parseInt( + match[1] + + match[1] + // r + match[2] + + match[2] + // g + match[3] + + match[3] + // b + match[4] + + match[4], // a + 16 + ) >>> 0 + ) + } + + if ((match = matchers.hsl.exec(color))) { + return ( + (hslToRgb( + parse360(match[1]), // h + parsePercentage(match[2]), // s + parsePercentage(match[3]) // l + ) | + 0x000000ff) >>> // a + 0 + ) + } + + if ((match = matchers.hsla.exec(color))) { + return ( + (hslToRgb( + parse360(match[1]), // h + parsePercentage(match[2]), // s + parsePercentage(match[3]) // l + ) | + parse1(match[4])) >>> // a + 0 + ) + } + + return null +} + +function hue2rgb (p, q, t) { + if (t < 0) { + t += 1 + } + if (t > 1) { + t -= 1 + } + if (t < 1 / 6) { + return p + (q - p) * 6 * t + } + if (t < 1 / 2) { + return q + } + if (t < 2 / 3) { + return p + (q - p) * (2 / 3 - t) * 6 + } + return p +} + +function hslToRgb (h, s, l) { + const q = l < 0.5 ? l * (1 + s) : l + s - l * s + const p = 2 * l - q + const r = hue2rgb(p, q, h + 1 / 3) + const g = hue2rgb(p, q, h) + const b = hue2rgb(p, q, h - 1 / 3) + + return ( + (Math.round(r * 255) << 24) | + (Math.round(g * 255) << 16) | + (Math.round(b * 255) << 8) + ) +} + +// var INTEGER = '[-+]?\\d+'; +const NUMBER = '[-+]?\\d*\\.?\\d+' +const PERCENTAGE = NUMBER + '%' + +function call (...args) { + return '\\(\\s*(' + args.join(')\\s*,\\s*(') + ')\\s*\\)' +} + +let cachedMatchers + +function getMatchers () { + if (cachedMatchers === undefined) { + cachedMatchers = { + rgb: new RegExp('rgb' + call(NUMBER, NUMBER, NUMBER)), + rgba: new RegExp('rgba' + call(NUMBER, NUMBER, NUMBER, NUMBER)), + hsl: new RegExp('hsl' + call(NUMBER, PERCENTAGE, PERCENTAGE)), + hsla: new RegExp('hsla' + call(NUMBER, PERCENTAGE, PERCENTAGE, NUMBER)), + hex3: /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex4: /^#([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#([0-9a-fA-F]{6})$/, + hex8: /^#([0-9a-fA-F]{8})$/ + } + } + return cachedMatchers +} + +function parse255 (str) { + const int = parseInt(str, 10) + if (int < 0) { + return 0 + } + if (int > 255) { + return 255 + } + return int +} + +function parse360 (str) { + const int = parseFloat(str) + return (((int % 360) + 360) % 360) / 360 +} + +function parse1 (str) { + const num = parseFloat(str) + if (num < 0) { + return 0 + } + if (num > 1) { + return 255 + } + return Math.round(num * 255) +} + +function parsePercentage (str) { + // parseFloat conveniently ignores the final % + const int = parseFloat(str) + if (int < 0) { + return 0 + } + if (int > 100) { + return 1 + } + return int / 100 +} + +const names = { + transparent: 0x00000000, + + // http://www.w3.org/TR/css3-color/#svg-color + aliceblue: 0xf0f8ffff, + antiquewhite: 0xfaebd7ff, + aqua: 0x00ffffff, + aquamarine: 0x7fffd4ff, + azure: 0xf0ffffff, + beige: 0xf5f5dcff, + bisque: 0xffe4c4ff, + black: 0x000000ff, + blanchedalmond: 0xffebcdff, + blue: 0x0000ffff, + blueviolet: 0x8a2be2ff, + brown: 0xa52a2aff, + burlywood: 0xdeb887ff, + burntsienna: 0xea7e5dff, + cadetblue: 0x5f9ea0ff, + chartreuse: 0x7fff00ff, + chocolate: 0xd2691eff, + coral: 0xff7f50ff, + cornflowerblue: 0x6495edff, + cornsilk: 0xfff8dcff, + crimson: 0xdc143cff, + cyan: 0x00ffffff, + darkblue: 0x00008bff, + darkcyan: 0x008b8bff, + darkgoldenrod: 0xb8860bff, + darkgray: 0xa9a9a9ff, + darkgreen: 0x006400ff, + darkgrey: 0xa9a9a9ff, + darkkhaki: 0xbdb76bff, + darkmagenta: 0x8b008bff, + darkolivegreen: 0x556b2fff, + darkorange: 0xff8c00ff, + darkorchid: 0x9932ccff, + darkred: 0x8b0000ff, + darksalmon: 0xe9967aff, + darkseagreen: 0x8fbc8fff, + darkslateblue: 0x483d8bff, + darkslategray: 0x2f4f4fff, + darkslategrey: 0x2f4f4fff, + darkturquoise: 0x00ced1ff, + darkviolet: 0x9400d3ff, + deeppink: 0xff1493ff, + deepskyblue: 0x00bfffff, + dimgray: 0x696969ff, + dimgrey: 0x696969ff, + dodgerblue: 0x1e90ffff, + firebrick: 0xb22222ff, + floralwhite: 0xfffaf0ff, + forestgreen: 0x228b22ff, + fuchsia: 0xff00ffff, + gainsboro: 0xdcdcdcff, + ghostwhite: 0xf8f8ffff, + gold: 0xffd700ff, + goldenrod: 0xdaa520ff, + gray: 0x808080ff, + green: 0x008000ff, + greenyellow: 0xadff2fff, + grey: 0x808080ff, + honeydew: 0xf0fff0ff, + hotpink: 0xff69b4ff, + indianred: 0xcd5c5cff, + indigo: 0x4b0082ff, + ivory: 0xfffff0ff, + khaki: 0xf0e68cff, + lavender: 0xe6e6faff, + lavenderblush: 0xfff0f5ff, + lawngreen: 0x7cfc00ff, + lemonchiffon: 0xfffacdff, + lightblue: 0xadd8e6ff, + lightcoral: 0xf08080ff, + lightcyan: 0xe0ffffff, + lightgoldenrodyellow: 0xfafad2ff, + lightgray: 0xd3d3d3ff, + lightgreen: 0x90ee90ff, + lightgrey: 0xd3d3d3ff, + lightpink: 0xffb6c1ff, + lightsalmon: 0xffa07aff, + lightseagreen: 0x20b2aaff, + lightskyblue: 0x87cefaff, + lightslategray: 0x778899ff, + lightslategrey: 0x778899ff, + lightsteelblue: 0xb0c4deff, + lightyellow: 0xffffe0ff, + lime: 0x00ff00ff, + limegreen: 0x32cd32ff, + linen: 0xfaf0e6ff, + magenta: 0xff00ffff, + maroon: 0x800000ff, + mediumaquamarine: 0x66cdaaff, + mediumblue: 0x0000cdff, + mediumorchid: 0xba55d3ff, + mediumpurple: 0x9370dbff, + mediumseagreen: 0x3cb371ff, + mediumslateblue: 0x7b68eeff, + mediumspringgreen: 0x00fa9aff, + mediumturquoise: 0x48d1ccff, + mediumvioletred: 0xc71585ff, + midnightblue: 0x191970ff, + mintcream: 0xf5fffaff, + mistyrose: 0xffe4e1ff, + moccasin: 0xffe4b5ff, + navajowhite: 0xffdeadff, + navy: 0x000080ff, + oldlace: 0xfdf5e6ff, + olive: 0x808000ff, + olivedrab: 0x6b8e23ff, + orange: 0xffa500ff, + orangered: 0xff4500ff, + orchid: 0xda70d6ff, + palegoldenrod: 0xeee8aaff, + palegreen: 0x98fb98ff, + paleturquoise: 0xafeeeeff, + palevioletred: 0xdb7093ff, + papayawhip: 0xffefd5ff, + peachpuff: 0xffdab9ff, + peru: 0xcd853fff, + pink: 0xffc0cbff, + plum: 0xdda0ddff, + powderblue: 0xb0e0e6ff, + purple: 0x800080ff, + rebeccapurple: 0x663399ff, + red: 0xff0000ff, + rosybrown: 0xbc8f8fff, + royalblue: 0x4169e1ff, + saddlebrown: 0x8b4513ff, + salmon: 0xfa8072ff, + sandybrown: 0xf4a460ff, + seagreen: 0x2e8b57ff, + seashell: 0xfff5eeff, + sienna: 0xa0522dff, + silver: 0xc0c0c0ff, + skyblue: 0x87ceebff, + slateblue: 0x6a5acdff, + slategray: 0x708090ff, + slategrey: 0x708090ff, + snow: 0xfffafaff, + springgreen: 0x00ff7fff, + steelblue: 0x4682b4ff, + tan: 0xd2b48cff, + teal: 0x008080ff, + thistle: 0xd8bfd8ff, + tomato: 0xff6347ff, + turquoise: 0x40e0d0ff, + violet: 0xee82eeff, + wheat: 0xf5deb3ff, + white: 0xffffffff, + whitesmoke: 0xf5f5f5ff, + yellow: 0xffff00ff, + yellowgreen: 0x9acd32ff +} + +module.exports = normalizeColor diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/pkg b/packages/omi-cloudbase/scripts/taro-cli/src/rn/pkg new file mode 100644 index 000000000..fe952466b --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/pkg @@ -0,0 +1,15 @@ +{ + "name":"<%= projectName %>", + "main": "./bin/crna-entry.js", + "dependencies": { + "@tarojs/components-rn": "^<%= version %>", + "@tarojs/taro-rn": "^<%= version %>", + "@tarojs/taro-router-rn": "^<%= version %>", + "@tarojs/taro-redux-rn": "^<%= version %>", + "expo": "27.0.1", + "react": "16.3.1", + "react-native": "0.55.2", + "redux": "^4.0.0", + "tslib": "^1.8.0" + } +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/styleProcess.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/styleProcess.js new file mode 100644 index 000000000..6539e880e --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/styleProcess.js @@ -0,0 +1,109 @@ +const path = require('path') +const fs = require('fs-extra') +const postcss = require('postcss') +const chalk = require('chalk') +const pxtransform = require('postcss-pxtransform') +const transformCSS = require('css-to-react-native-transform').default +const {StyleSheetValidation} = require('./StyleSheet/index') +const Util = require('../util') +const npmProcess = require('../util/npm') + +const DEVICE_RATIO = 'deviceRatio' + +/** + * @description 读取 css/scss/less 文件,预处理后,返回 css string + * @param {string}filePath + * @param {object} pluginsConfig + * @returns {*} + */ +function loadStyle ({filePath, pluginsConfig}) { + const fileExt = path.extname(filePath) + const pluginName = Util.FILE_PROCESSOR_MAP[fileExt] + if (pluginName) { + return npmProcess.callPlugin(pluginName, null, filePath, pluginsConfig[pluginName] || {}) + .then((item) => { + return { + css: item.css.toString(), + filePath + } + }).catch((e) => { + Util.printLog(Util.pocessTypeEnum.ERROR, '样式预处理', filePath) + console.log(e.stack) + }) + } + return new Promise((resolve, reject) => { + fs.readFile(filePath, 'utf-8', (err, content) => { + if (err) { + return reject(err) + } + resolve({ + css: content, + filePath + }) + }) + }) +} + +/** + * @description 传入 css string ,返回 postCSS 处理后的 css string + * @param {string} css + * @param {string} filePath + * @param {object} projectConfig + * @returns {Function | any} + */ +function postCSS ({css, filePath, projectConfig}) { + let pxTransformConfig = { + designWidth: projectConfig.designWidth || 750 + } + if (projectConfig.hasOwnProperty(DEVICE_RATIO)) { + pxTransformConfig[DEVICE_RATIO] = projectConfig.deviceRatio + } + return postcss(pxtransform({ + platform: 'rn', + ...pxTransformConfig + })) + .process(css, {from: filePath}) + .then((result) => { + return { + css: result.css, + filePath + } + }) +} + +function getStyleObject ({css, filePath}) { + var styleObject = {} + try { + styleObject = transformCSS(css) + } catch (err) { + Util.printLog(Util.pocessTypeEnum.WARNING, 'css-to-react-native 报错', filePath) + console.log(chalk.red(err.stack)) + } + return styleObject +} + +function validateStyle ({styleObject, filePath}) { + for (let name in styleObject) { + try { + StyleSheetValidation.validateStyle(name, styleObject) + } catch (err) { + Util.printLog(Util.pocessTypeEnum.WARNING, '样式不支持', filePath) + console.log(chalk.red(err.message)) + } + } +} + +function writeStyleFile ({css, tempFilePath}) { + const fileContent = `import { StyleSheet } from 'react-native'\n\nexport default StyleSheet.create(${css})` + fs.ensureDirSync(path.dirname(tempFilePath)) + fs.writeFileSync(tempFilePath, fileContent) + Util.printLog(Util.pocessTypeEnum.GENERATE, '生成文件', tempFilePath) +} + +module.exports = { + loadStyle, + postCSS, + getStyleObject, + validateStyle, + writeStyleFile +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/rn/transformJS.js b/packages/omi-cloudbase/scripts/taro-cli/src/rn/transformJS.js new file mode 100644 index 000000000..7d9c91475 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/rn/transformJS.js @@ -0,0 +1,489 @@ +const path = require('path') +const babel = require('babel-core') +const traverse = require('babel-traverse').default +const t = require('babel-types') +const _ = require('lodash') +const generate = require('babel-generator').default +const template = require('babel-template') +const wxTransformer = require('../../../taro-transformer-wx/lib/src/index.js').default +const Util = require('../util') +const babylonConfig = require('../config/babylon') +const {source: toAst} = require('../util/ast_convert') + +const reactImportDefaultName = 'React' +let taroImportDefaultName // import default from @tarojs/taro +let componentClassName // get app.js class name +const providerComponentName = 'Provider' +const setStoreFuncName = 'setStore' +const routerImportDefaultName = 'TaroRouter' +const DEVICE_RATIO = 'deviceRatio' + +const taroApis = [ + 'getEnv', + 'ENV_TYPE', + 'eventCenter', + 'Events', + 'internal_safe_get', + 'internal_dynamic_recursive' +] + +const PACKAGES = { + '@tarojs/taro': '@tarojs/taro', + '@tarojs/taro-rn': '@tarojs/taro-rn', + '@tarojs/taro-router-rn': '@tarojs/taro-router-rn', + '@tarojs/redux': '@tarojs/redux', + '@tarojs/components': '@tarojs/components', + '@tarojs/components-rn': '@tarojs/components-rn', + 'react': 'react', + 'react-native': 'react-native', + 'react-redux-rn': '@tarojs/taro-redux-rn', + '@tarojs/mobx': '@tarojs/mobx', + '@tarojs/mobx-rn': '@tarojs/mobx-rn' +} + +function getInitPxTransformNode (projectConfig) { + let pxTransformConfig = {designWidth: projectConfig.designWidth || 750} + + if (projectConfig.hasOwnProperty(DEVICE_RATIO)) { + pxTransformConfig[DEVICE_RATIO] = projectConfig.deviceRatio + } + const initPxTransformNode = toAst(`Taro.initPxTransform(${JSON.stringify(pxTransformConfig)})`) + return initPxTransformNode +} + +function getClassPropertyVisitor ({filePath, pages, iconPaths, isEntryFile}) { + return (astPath) => { + const node = astPath.node + const key = node.key + const value = node.value + if (key.name !== 'config' || !t.isObjectExpression(value)) return + // 入口文件的 config ,与页面的分开处理 + if (isEntryFile) { + // 读取 config 配置 + astPath.traverse({ + ObjectProperty (astPath) { + const node = astPath.node + const key = node.key + const value = node.value + // if (key.name !== 'pages' || !t.isArrayExpression(value)) return + if (key.name === 'pages' && t.isArrayExpression(value)) { + // 分包 + let root = '' + const rootNode = astPath.parent.properties.find(v => { + return v.key.name === 'root' + }) + root = rootNode ? rootNode.value.value : '' + + value.elements.forEach(v => { + const pagePath = `${root}/${v.value}`.replace(/\/{2,}/g, '/') + pages.push(pagePath.replace(/^\//, '')) + }) + astPath.remove() + } + // window + if (key.name === 'window' && t.isObjectExpression(value)) { + return + } + if (key.name === 'tabBar' && t.isObjectExpression(value)) { + astPath.traverse({ + ObjectProperty (astPath) { + let node = astPath.node + let value = node.value.value + if (node.key.name === 'iconPath' || + node.key.value === 'iconPath' || + node.key.name === 'selectedIconPath' || + node.key.value === 'selectedIconPath' + ) { + if (typeof value !== 'string') return + let iconName = _.camelCase(value.split('/')) + if (iconPaths.indexOf(value) === -1) { + iconPaths.push(value) + } + astPath.insertAfter(t.objectProperty( + t.identifier(node.key.name || node.key.value), + t.identifier(iconName) + )) + astPath.remove() + } + } + }) + } + } + }) + } + astPath.node.static = 'true' + } +} + +function getJSAst (code, filePath) { + return wxTransformer({ + code, + sourcePath: filePath, + isNormal: true, + isTyped: Util.REG_TYPESCRIPT.test(filePath), + adapter: 'rn' + }).ast +} + +/** + * TS 编译器会把 class property 移到构造器, + * 而小程序要求 `config` 和所有函数在初始化(after new Class)之后就收集到所有的函数和 config 信息, + * 所以当如构造器里有 this.func = () => {...} 的形式,就给他转换成普通的 classProperty function + * 如果有 config 就给他还原 + */ +function resetTSClassProperty (body) { + for (const method of body) { + if (t.isClassMethod(method) && method.kind === 'constructor') { + for (const statement of _.cloneDeep(method.body.body)) { + if (t.isExpressionStatement(statement) && t.isAssignmentExpression(statement.expression)) { + const expr = statement.expression + const {left, right} = expr + if ( + t.isMemberExpression(left) && + t.isThisExpression(left.object) && + t.isIdentifier(left.property) + ) { + if ( + (t.isArrowFunctionExpression(right) || t.isFunctionExpression(right)) || + (left.property.name === 'config' && t.isObjectExpression(right)) + ) { + body.push( + t.classProperty(left.property, right) + ) + _.remove(method.body.body, statement) + } + } + } + } + } + } +} + +const ClassDeclarationOrExpression = { + enter (astPath) { + const node = astPath.node + if (!node.superClass) return + if ( + node.superClass.type === 'MemberExpression' && + node.superClass.object.name === taroImportDefaultName + ) { + node.superClass.object.name = taroImportDefaultName + if (node.id === null) { + const renameComponentClassName = '_TaroComponentClass' + componentClassName = renameComponentClassName + astPath.replaceWith( + t.classDeclaration( + t.identifier(renameComponentClassName), + node.superClass, + node.body, + node.decorators || [] + ) + ) + } else { + componentClassName = node.id.name + } + } else if (node.superClass.name === 'Component') { + resetTSClassProperty(node.body.body) + if (node.id === null) { + const renameComponentClassName = '_TaroComponentClass' + componentClassName = renameComponentClassName + astPath.replaceWith( + t.classDeclaration( + t.identifier(renameComponentClassName), + node.superClass, + node.body, + node.decorators || [] + ) + ) + } else { + componentClassName = node.id.name + } + } + } +} + +function parseJSCode ({code, filePath, isEntryFile, projectConfig}) { + let ast + try { + ast = getJSAst(code, filePath) + } catch (e) { + throw e + } + const styleFiles = [] + let pages = [] // app.js 里面的config 配置里面的 pages + let iconPaths = [] // app.js 里面的config 配置里面的需要引入的 iconPath + let hasAddReactImportDefaultName = false + let providorImportName + let storeName + let hasAppExportDefault + let classRenderReturnJSX + + traverse(ast, { + ClassExpression: ClassDeclarationOrExpression, + ClassDeclaration: ClassDeclarationOrExpression, + ImportDeclaration (astPath) { + const node = astPath.node + const source = node.source + let value = source.value + const valueExtname = path.extname(value) + const specifiers = node.specifiers + const pathAlias = projectConfig.alias || {} + if (Util.isAliasPath(value, pathAlias)) { + source.value = value = Util.replaceAliasPath(filePath, value, pathAlias) + } + // 引入的包为 npm 包 + if (!Util.isNpmPkg(value)) { + // import 样式处理 + if (Util.REG_STYLE.test(valueExtname)) { + const stylePath = path.resolve(path.dirname(filePath), value) + if (styleFiles.indexOf(stylePath) < 0) { + styleFiles.push(stylePath) + } + } + return + } + if (value === PACKAGES['@tarojs/taro']) { + let specifier = specifiers.find(item => item.type === 'ImportDefaultSpecifier') + if (specifier) { + hasAddReactImportDefaultName = true + taroImportDefaultName = specifier.local.name + specifier.local.name = reactImportDefaultName + } else if (!hasAddReactImportDefaultName) { + hasAddReactImportDefaultName = true + node.specifiers.unshift( + t.importDefaultSpecifier(t.identifier(reactImportDefaultName)) + ) + } + // 删除从@tarojs/taro引入的 React + specifiers.forEach((item, index) => { + if (item.type === 'ImportDefaultSpecifier') { + specifiers.splice(index, 1) + } + }) + const taroApisSpecifiers = [] + specifiers.forEach((item, index) => { + if (item.imported && taroApis.indexOf(item.imported.name) >= 0) { + taroApisSpecifiers.push(t.importSpecifier(t.identifier(item.local.name), t.identifier(item.imported.name))) + specifiers.splice(index, 1) + } + }) + source.value = PACKAGES['@tarojs/taro-rn'] + // insert React + astPath.insertBefore(template(`import React from 'react'`, babylonConfig)()) + + if (taroApisSpecifiers.length) { + astPath.insertBefore(t.importDeclaration(taroApisSpecifiers, t.stringLiteral(PACKAGES['@tarojs/taro-rn']))) + } + if (!specifiers.length) { + astPath.remove() + } + } else if (value === PACKAGES['@tarojs/redux']) { + const specifier = specifiers.find(item => { + return t.isImportSpecifier(item) && item.imported.name === providerComponentName + }) + if (specifier) { + providorImportName = specifier.local.name + } else { + providorImportName = providerComponentName + specifiers.push(t.importSpecifier(t.identifier(providerComponentName), t.identifier(providerComponentName))) + } + source.value = PACKAGES['react-redux-rn'] + } else if (value === PACKAGES['@tarojs/mobx']) { + const specifier = specifiers.find(item => { + return t.isImportSpecifier(item) && item.imported.name === providerComponentName + }) + if (specifier) { + providorImportName = specifier.local.name + } else { + providorImportName = providerComponentName + specifiers.push(t.importSpecifier(t.identifier(providerComponentName), t.identifier(providerComponentName))) + } + source.value = PACKAGES['@tarojs/mobx-rn'] + } else if (value === PACKAGES['@tarojs/components']) { + source.value = PACKAGES['@tarojs/components-rn'] + } + }, + ClassProperty: getClassPropertyVisitor({filePath, pages, iconPaths, isEntryFile}), + // 获取 classRenderReturnJSX + ClassMethod (astPath) { + let node = astPath.node + const key = node.key + if (key.name !== 'render' || !isEntryFile) return + astPath.traverse({ + BlockStatement (astPath) { + if (astPath.parent === node) { + node = astPath.node + astPath.traverse({ + ReturnStatement (astPath) { + if (astPath.parent === node) { + astPath.traverse({ + JSXElement (astPath) { + classRenderReturnJSX = generate(astPath.node).code + } + }) + } + } + }) + } + } + }) + }, + + ExportDefaultDeclaration () { + if (isEntryFile) { + hasAppExportDefault = true + } + }, + JSXOpeningElement: { + enter (astPath) { + if (astPath.node.name.name === 'Provider') { + for (let v of astPath.node.attributes) { + if (v.name.name !== 'store') continue + storeName = v.value.expression.name + break + } + } + } + }, + Program: { + exit (astPath) { + const node = astPath.node + astPath.traverse({ + ClassMethod (astPath) { + const node = astPath.node + const key = node.key + if (key.name !== 'render' || !isEntryFile) return + let funcBody = classRenderReturnJSX + if (pages.length > 0) { + funcBody = `` + } + if (providerComponentName && storeName) { + // 使用redux 或 mobx + funcBody = ` + <${providorImportName} store={${storeName}}> + ${funcBody} + ` + } + node.body = template(`{return (${funcBody});}`, babylonConfig)() + }, + + CallExpression (astPath) { + const node = astPath.node + const callee = node.callee + const calleeName = callee.name + const parentPath = astPath.parentPath + + if (t.isMemberExpression(callee)) { + if (callee.object.name === taroImportDefaultName && callee.property.name === 'render') { + astPath.remove() + } + } else { + if (calleeName === setStoreFuncName) { + if (parentPath.isAssignmentExpression() || + parentPath.isExpressionStatement() || + parentPath.isVariableDeclarator()) { + parentPath.remove() + } + } + } + } + }) + // import Taro from @tarojs/taro-rn + if (taroImportDefaultName) { + const importTaro = template( + `import ${taroImportDefaultName} from '${PACKAGES['@tarojs/taro-rn']}'`, + babylonConfig + )() + node.body.unshift(importTaro) + } + + if (isEntryFile) { + // 注入 import page from 'XXX' + pages.forEach(item => { + const pagePath = item.startsWith('/') ? item : `/${item}` + const screenName = _.camelCase(pagePath.split('/'), {pascalCase: true}) + const importScreen = template( + `import ${screenName} from '.${pagePath}'`, + babylonConfig + )() + node.body.unshift(importScreen) + }) + iconPaths.forEach(item => { + const iconPath = item.startsWith('/') ? item : `/${item}` + const iconName = _.camelCase(iconPath.split('/')) + const importIcon = template( + `import ${iconName} from '.${iconPath}'`, + babylonConfig + )() + node.body.unshift(importIcon) + }) + // Taro.initRouter 生成 RootStack + const routerPages = pages + .map(item => { + const pagePath = item.startsWith('/') ? item : `/${item}` + const screenName = _.camelCase(pagePath.split('/'), {pascalCase: true}) + return `['${item}',${screenName}]` + }) + .join(',') + node.body.push(template( + `const RootStack = ${routerImportDefaultName}.initRouter( + [${routerPages}], + ${taroImportDefaultName}, + App.config + )`, + babylonConfig + )()) + // initNativeApi + const initNativeApi = template( + `${taroImportDefaultName}.initNativeApi(${taroImportDefaultName})`, + babylonConfig + )() + node.body.push(initNativeApi) + + // import @tarojs/taro-router-rn + const importTaroRouter = template( + `import TaroRouter from '${PACKAGES['@tarojs/taro-router-rn']}'`, + babylonConfig + )() + node.body.unshift(importTaroRouter) + + // Taro.initPxTransform + node.body.push(getInitPxTransformNode(projectConfig)) + + // export default App + if (!hasAppExportDefault) { + const appExportDefault = template( + `export default ${componentClassName}`, + babylonConfig + )() + node.body.push(appExportDefault) + } + } + } + } + }) + try { + const constantsReplaceList = Object.assign({ + 'process.env.TARO_ENV': Util.BUILD_TYPES.RN + }, Util.generateEnvList(projectConfig.env || {}), Util.generateConstantsList(projectConfig.defineConstants || {})) + // TODO 使用 babel-plugin-transform-jsx-to-stylesheet 处理 JSX 里面样式的处理,删除无效的样式引入待优化 + ast = babel.transformFromAst(ast, code, { + plugins: [ + [require('babel-plugin-transform-jsx-to-stylesheet'), {filePath}], + require('babel-plugin-transform-decorators-legacy').default, + require('babel-plugin-transform-class-properties'), + [require('babel-plugin-danger-remove-unused-import'), {ignore: ['@tarojs/taro', 'react', 'react-native', 'nervjs']}], + [require('babel-plugin-transform-define').default, constantsReplaceList] + ] + }).ast + } catch (e) { + throw e + } + + return { + code: unescape(generate(ast).code.replace(/\\u/g, '%u')), + styleFiles + } +} + +module.exports = {transformJSCode: parseJSCode} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/ui.js b/packages/omi-cloudbase/scripts/taro-cli/src/ui.js new file mode 100644 index 000000000..98ab86138 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/ui.js @@ -0,0 +1,431 @@ +const fs = require('fs-extra') +const path = require('path') +const chokidar = require('chokidar') +const chalk = require('chalk') +const wxTransformer = require('../../taro-transformer-wx/lib/src/index.js').default +const traverse = require('babel-traverse').default +const t = require('babel-types') +const generate = require('babel-generator').default +const _ = require('lodash') + +const { processFiles } = require('./h5') +const npmProcess = require('./util/npm') + +const CONFIG = require('./config') +const { + resolveScriptPath, + resolveStylePath, + printLog, + pocessTypeEnum, + PROJECT_CONFIG, + BUILD_TYPES, + REG_STYLE, + REG_TYPESCRIPT, + cssImports +} = require('./util') + +const appPath = process.cwd() +const configDir = path.join(appPath, PROJECT_CONFIG) +const projectConfig = require(configDir)(_.merge) +const sourceDirName = projectConfig.sourceRoot || CONFIG.SOURCE_DIR +let outputDirName = projectConfig.outputRoot || CONFIG.OUTPUT_DIR +const sourceDir = path.join(appPath, sourceDirName) +const entryFilePath = resolveScriptPath(path.join(sourceDir, 'index')) +const entryFileName = path.basename(entryFilePath) +const tempDir = '.temp' +const tempPath = path.join(appPath, tempDir) + +const weappOutputName = 'weapp' +const h5OutputName = 'h5' + +async function buildH5Script () { + const h5Config = projectConfig.h5 || {} + const entryFile = path.basename(entryFileName, path.extname(entryFileName)) + '.js' + outputDirName = `${outputDirName}/${h5OutputName}` + h5Config.env = projectConfig.env + h5Config.defineConstants = projectConfig.defineConstants + h5Config.plugins = projectConfig.plugins + h5Config.designWidth = projectConfig.designWidth + if (projectConfig.deviceRatio) { + h5Config.deviceRatio = projectConfig.deviceRatio + } + h5Config.sourceRoot = sourceDirName + h5Config.outputRoot = outputDirName + h5Config.entry = Object.assign({ + app: [path.join(tempPath, entryFile)] + }, h5Config.entry) + h5Config.isWatch = false + const webpackRunner = await npmProcess.getNpmPkg('@tarojs/webpack-runner') + webpackRunner(h5Config) +} + +async function buildH5Lib () { + try { + const outputDir = path.join(appPath, outputDirName, h5OutputName) + const tempEntryFilePath = resolveScriptPath(path.join(tempPath, 'index')) + const outputEntryFilePath = path.join(outputDir, path.basename(tempEntryFilePath)) + const code = fs.readFileSync(tempEntryFilePath).toString() + const transformResult = wxTransformer({ + code, + sourcePath: tempEntryFilePath, + outputPath: outputEntryFilePath, + isNormal: true, + isTyped: REG_TYPESCRIPT.test(tempEntryFilePath) + }) + const { styleFiles, components, code: generateCode } = parseEntryAst(transformResult.ast, tempEntryFilePath) + const relativePath = path.relative(appPath, tempEntryFilePath) + printLog(pocessTypeEnum.COPY, '发现文件', relativePath) + fs.ensureDirSync(path.dirname(outputEntryFilePath)) + fs.writeFileSync(outputEntryFilePath, generateCode) + if (components.length) { + components.forEach(item => { + copyFileToDist(item.path, tempPath, outputDir) + }) + analyzeFiles(components.map(item => item.path), tempPath, outputDir) + } + if (styleFiles.length) { + styleFiles.forEach(item => { + copyFileToDist(item, tempPath, path.join(appPath, outputDirName)) + }) + analyzeStyleFilesImport(styleFiles, tempPath, path.join(appPath, outputDirName)) + } + } catch (err) { + console.log(err) + } +} + +function copyFileToDist (filePath, sourceDir, outputDir) { + if (!path.isAbsolute(filePath)) { + return + } + const dirname = path.dirname(filePath) + const distDirname = dirname.replace(sourceDir, outputDir) + const relativePath = path.relative(appPath, filePath) + printLog(pocessTypeEnum.COPY, '发现文件', relativePath) + fs.ensureDirSync(distDirname) + fs.copyFileSync(filePath, path.format({ + dir: distDirname, + base: path.basename(filePath) + })) +} + +function parseEntryAst (ast, relativeFile) { + const styleFiles = [] + const components = [] + const importExportName = [] + let exportDefaultName = null + + traverse(ast, { + ExportNamedDeclaration (astPath) { + const node = astPath.node + const specifiers = node.specifiers + const source = node.source + if (source && source.type === 'StringLiteral') { + specifiers.forEach(specifier => { + const exported = specifier.exported + components.push({ + name: exported.name, + path: resolveScriptPath(path.resolve(path.dirname(relativeFile), source.value)) + }) + }) + } else { + specifiers.forEach(specifier => { + const exported = specifier.exported + importExportName.push(exported.name) + }) + } + }, + + ExportDefaultDeclaration (astPath) { + const node = astPath.node + const declaration = node.declaration + if (t.isIdentifier(declaration)) { + exportDefaultName = declaration.name + } + }, + + Program: { + exit (astPath) { + astPath.traverse({ + ImportDeclaration (astPath) { + const node = astPath.node + const specifiers = node.specifiers + const source = node.source + const value = source.value + const valueExtname = path.extname(value) + if (REG_STYLE.test(valueExtname)) { + const stylePath = path.resolve(path.dirname(relativeFile), value) + if (styleFiles.indexOf(stylePath) < 0) { + styleFiles.push(stylePath) + } + astPath.remove() + } else { + if (importExportName.length) { + importExportName.forEach(nameItem => { + specifiers.forEach(specifier => { + const local = specifier.local + if (local.name === nameItem) { + components.push({ + name: local.name, + path: resolveScriptPath(path.resolve(path.dirname(relativeFile), source.value)) + }) + } + }) + }) + } + if (exportDefaultName != null) { + specifiers.forEach(specifier => { + const local = specifier.local + if (local.name === exportDefaultName) { + components.push({ + name: local.name, + path: resolveScriptPath(path.resolve(path.dirname(relativeFile), source.value)) + }) + } + }) + } + } + } + }) + } + } + }) + const code = generate(ast).code + return { + code, + styleFiles, + components + } +} + +function analyzeFiles (files, sourceDir, outputDir) { + const { parseAst } = require('./weapp') + files.forEach(file => { + if (fs.existsSync(file)) { + const code = fs.readFileSync(file).toString() + const transformResult = wxTransformer({ + code, + sourcePath: file, + outputPath: file, + isNormal: true, + isTyped: REG_TYPESCRIPT.test(file) + }) + const { + styleFiles, + scriptFiles, + jsonFiles, + mediaFiles + } = parseAst('NORMAL', transformResult.ast, [], file, file, true) + const resFiles = styleFiles.concat(scriptFiles, jsonFiles, mediaFiles) + if (resFiles.length) { + resFiles.forEach(item => { + copyFileToDist(item, sourceDir, outputDir) + }) + } + if (scriptFiles.length) { + analyzeFiles(scriptFiles, sourceDir, outputDir) + } + if (styleFiles.length) { + analyzeStyleFilesImport(styleFiles, sourceDir, outputDir) + } + } + }) +} + +function analyzeStyleFilesImport (styleFiles, sourceDir, outputDir) { + styleFiles.forEach(item => { + if (!fs.existsSync(item)) { + return + } + let content = fs.readFileSync(item).toString() + content = content.replace(/(?:@import\s+)?\burl\s*\(\s*("(?:[^\\"\r\n\f]|\\[\s\S])*"|'(?:[^\\'\n\r\f]|\\[\s\S])*'|[^)}\s]+)\s*\)(\s*;?)/g, (m, $1) => { + if ($1) { + let filePath = $1.replace(/'?"?/g, '') + if (filePath.indexOf('.') === 0) { + filePath = path.resolve(path.dirname(item), filePath) + copyFileToDist(filePath, sourceDir, outputDir) + } + } + return m + }) + let imports = cssImports(content) + if (imports.length > 0) { + imports = imports.map(importItem => { + const filePath = resolveStylePath(path.resolve(path.dirname(item), importItem)) + copyFileToDist(filePath, sourceDir, outputDir) + return filePath + }) + analyzeStyleFilesImport(imports, sourceDir, outputDir) + } + }) +} + +async function buildForWeapp () { + console.log() + console.log(chalk.green('开始编译小程序端组件库!')) + if (!fs.existsSync(entryFilePath)) { + console.log(chalk.red('入口文件不存在,请检查!')) + return + } + try { + const { compileDepStyles } = require('./weapp') + const outputDir = path.join(appPath, outputDirName, weappOutputName) + const outputEntryFilePath = path.join(outputDir, entryFileName) + const code = fs.readFileSync(entryFilePath).toString() + const transformResult = wxTransformer({ + code, + sourcePath: entryFilePath, + outputPath: outputEntryFilePath, + isNormal: true, + isTyped: REG_TYPESCRIPT.test(entryFilePath) + }) + const { styleFiles, components } = parseEntryAst(transformResult.ast, entryFilePath) + if (styleFiles.length) { + const outputStylePath = path.join(outputDir, 'css', 'index.css') + await compileDepStyles(outputStylePath, styleFiles, false) + } + const relativePath = path.relative(appPath, entryFilePath) + printLog(pocessTypeEnum.COPY, '发现文件', relativePath) + fs.ensureDirSync(path.dirname(outputEntryFilePath)) + fs.copyFileSync(entryFilePath, path.format({ + dir: path.dirname(outputEntryFilePath), + base: path.basename(outputEntryFilePath) + })) + if (components.length) { + components.forEach(item => { + copyFileToDist(item.path, sourceDir, outputDir) + }) + analyzeFiles(components.map(item => item.path), sourceDir, outputDir) + } + } catch (err) { + console.log(err) + } +} + +async function buildForH5 (buildConfig) { + const { buildTemp } = require('./h5') + console.log() + console.log(chalk.green('开始编译 H5 端组件库!')) + await buildTemp(buildConfig) + if (process.env.TARO_BUILD_TYPE === 'script') { + await buildH5Script() + } else { + await buildH5Lib() + } +} + +function buildEntry () { + const content = `if (process.env.TARO_ENV === '${BUILD_TYPES.H5}') { + module.exports = require('./${h5OutputName}/index') + module.exports.default = module.exports + } else { + module.exports = require('./${weappOutputName}/index') + module.exports.default = module.exports + }` + const outputDir = path.join(appPath, outputDirName) + fs.writeFileSync(path.join(outputDir, 'index.js'), content) +} + +function watchFiles () { + console.log('\n', chalk.gray('监听文件修改中...'), '\n') + + const watchList = [sourceDir] + + const uiConfig = projectConfig.ui || {} + const { extraWatchFiles = [] } = uiConfig + extraWatchFiles.forEach(item => { + watchList.push(path.join(appPath, item.path)) + if (typeof item.handler === 'function') item.callback = item.handler({ buildH5Script }) + }) + + const watcher = chokidar.watch(watchList, { + ignored: /(^|[/\\])\../, + ignoreInitial: true + }) + + function syncWeappFile (filePath) { + const outputDir = path.join(appPath, outputDirName, weappOutputName) + copyFileToDist(filePath, sourceDir, outputDir) + // 依赖分析 + const extname = path.extname(filePath) + if (REG_STYLE.test(extname)) { + analyzeStyleFilesImport([filePath], sourceDir, outputDir) + } else { + analyzeFiles([filePath], sourceDir, outputDir) + } + } + + function syncH5File (filePath) { + const outputDir = path.join(appPath, outputDirName, h5OutputName) + const fileTempPath = filePath.replace(sourceDir, tempPath) + processFiles(filePath) + + if (process.env.TARO_BUILD_TYPE === 'script') { + buildH5Script() + } else { + copyFileToDist(fileTempPath, tempPath, outputDir) + // 依赖分析 + const extname = path.extname(filePath) + if (REG_STYLE.test(extname)) { + analyzeStyleFilesImport([fileTempPath], tempPath, outputDir) + } else { + analyzeFiles([fileTempPath], tempPath, outputDir) + } + } + } + + function handleChange (filePath, type, tips) { + const relativePath = path.relative(appPath, filePath) + printLog(type, tips, relativePath) + + let processed = false + extraWatchFiles.forEach(item => { + if (filePath.indexOf(item.path.substr(2)) < 0) return + if (typeof item.callback === 'function') { + item.callback() + processed = true + } + }) + if (processed) return + + try { + syncWeappFile(filePath) + syncH5File(filePath) + } catch (err) { + console.log(err) + } + } + + watcher + .on('add', filePath => handleChange(filePath, pocessTypeEnum.CREATE, '添加文件')) + .on('change', filePath => handleChange(filePath, pocessTypeEnum.MODIFY, '文件变动')) + .on('unlink', filePath => { + for (const path in extraWatchFiles) { + if (filePath.indexOf(path.substr(2)) > -1) return + } + + const relativePath = path.relative(appPath, filePath) + printLog(pocessTypeEnum.UNLINK, '删除文件', relativePath) + const weappOutputPath = path.join(appPath, outputDirName, weappOutputName) + const h5OutputPath = path.join(appPath, outputDirName, h5OutputName) + const fileTempPath = filePath.replace(sourceDir, tempPath) + const fileWeappPath = filePath.replace(sourceDir, weappOutputPath) + const fileH5Path = filePath.replace(sourceDir, h5OutputPath) + fs.existsSync(fileTempPath) && fs.unlinkSync(fileTempPath) + fs.existsSync(fileWeappPath) && fs.unlinkSync(fileWeappPath) + fs.existsSync(fileH5Path) && fs.unlinkSync(fileH5Path) + }) +} + +async function build ({ watch }) { + buildEntry() + await buildForWeapp() + await buildForH5() + if (watch) { + watchFiles() + } +} + +module.exports = { + build +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/util/ast_convert.js b/packages/omi-cloudbase/scripts/taro-cli/src/util/ast_convert.js new file mode 100644 index 000000000..5c37bcf0a --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/util/ast_convert.js @@ -0,0 +1,79 @@ +const t = require('babel-types') +const babylonConfig = require('../config/babylon') +const template = require('babel-template') +const generate = require('better-babel-generator').default + +function convertObjectToAstExpression (obj) { + const objArr = Object.keys(obj).map(key => { + const value = obj[key] + if (typeof value === 'string') { + return t.objectProperty(t.stringLiteral(key), t.stringLiteral(value)) + } + if (typeof value === 'number') { + return t.objectProperty(t.stringLiteral(key), t.numericLiteral(value)) + } + if (typeof value === 'boolean') { + return t.objectProperty(t.stringLiteral(key), t.booleanLiteral(value)) + } + if (Array.isArray(value)) { + return t.objectProperty(t.stringLiteral(key), t.arrayExpression(convertArrayToAstExpression(value))) + } + if (value == null) { + return t.objectProperty(t.stringLiteral(key), t.nullLiteral()) + } + if (typeof value === 'object') { + return t.objectProperty(t.stringLiteral(key), t.objectExpression(convertObjectToAstExpression(value))) + } + }) + return objArr +} + +// 最低限度的转义: https://github.com/mathiasbynens/jsesc#minimal +function generateMinimalEscapeCode (ast) { + return generate(ast, { + jsescOption: { + minimal: true + } + }).code +} + +function convertArrayToAstExpression (arr) { + return arr.map(value => { + if (typeof value === 'string') { + return t.stringLiteral(value) + } + if (typeof value === 'number') { + return t.numericLiteral(value) + } + if (typeof value === 'boolean') { + return t.booleanLiteral(value) + } + if (Array.isArray(value)) { + return convertArrayToAstExpression(value) + } + if (value == null) { + return t.nullLiteral() + } + if (typeof value === 'object') { + return t.objectExpression(convertObjectToAstExpression(value)) + } + }) +} + +function convertSourceStringToAstExpression (str, opts = {}) { + return template(str, Object.assign({}, babylonConfig, opts))() +} + +const getObjKey = (node) => { + if (t.isIdentifier(node)) { + return node.name + } else { + return node.value + } +} + +exports.obj = convertObjectToAstExpression +exports.array = convertArrayToAstExpression +exports.source = convertSourceStringToAstExpression +exports.getObjKey = getObjKey +exports.generateMinimalEscapeCode = generateMinimalEscapeCode diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/util/index.js b/packages/omi-cloudbase/scripts/taro-cli/src/util/index.js new file mode 100644 index 000000000..7dddc7fdf --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/util/index.js @@ -0,0 +1,604 @@ +const path = require('path') +const crypto = require('crypto') +const os = require('os') +const fs = require('fs-extra') +const execSync = require('child_process').execSync +const chalk = require('chalk') +const _ = require('lodash') + +const pocessTypeEnum = { + CREATE: 'create', + COMPILE: 'compile', + CONVERT: 'convert', + COPY: 'copy', + GENERATE: 'generate', + MODIFY: 'modify', + ERROR: 'error', + WARNING: 'warning', + UNLINK: 'unlink', + REFERENCE: 'reference' +} + +const processTypeMap = { + [pocessTypeEnum.CREATE]: { + name: '创建', + color: 'cyan' + }, + [pocessTypeEnum.COMPILE]: { + name: '编译', + color: 'green' + }, + [pocessTypeEnum.CONVERT]: { + name: '转换', + color: chalk.rgb(255, 136, 0) + }, + [pocessTypeEnum.COPY]: { + name: '拷贝', + color: 'magenta' + }, + [pocessTypeEnum.GENERATE]: { + name: '生成', + color: 'blue' + }, + [pocessTypeEnum.MODIFY]: { + name: '修改', + color: 'yellow' + }, + [pocessTypeEnum.ERROR]: { + name: '错误', + color: 'red' + }, + [pocessTypeEnum.WARNING]: { + name: '警告', + color: 'yellow' + }, + [pocessTypeEnum.UNLINK]: { + name: '删除', + color: 'magenta' + }, + [pocessTypeEnum.START]: { + name: '启动', + color: 'green' + }, + [pocessTypeEnum.REFERENCE]: { + name: '引用', + color: 'blue' + } +} + +exports.pocessTypeEnum = pocessTypeEnum + +exports.CSS_EXT = ['.css', '.scss', '.sass', '.less', '.styl', '.wxss', '.acss'] +exports.SCSS_EXT = ['.scss'] +exports.JS_EXT = ['.js', '.jsx'] +exports.TS_EXT = ['.ts', '.tsx'] +exports.REG_JS = /\.js(\?.*)?$/ +exports.REG_SCRIPT = /\.(js|jsx)(\?.*)?$/ +exports.REG_TYPESCRIPT = /\.(tsx|ts)(\?.*)?$/ +exports.REG_SCRIPTS = /\.[tj]sx?$/i +exports.REG_STYLE = /\.(css|scss|sass|less|styl|wxss)(\?.*)?$/ +exports.REG_MEDIA = /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/ +exports.REG_IMAGE = /\.(png|jpe?g|gif|bpm|svg|webp)(\?.*)?$/ +exports.REG_FONT = /\.(woff2?|eot|ttf|otf)(\?.*)?$/ +exports.REG_JSON = /\.json(\?.*)?$/ +exports.REG_WXML_IMPORT = /<[import|include](.*)?src=(?:(?:'([^']*)')|(?:"([^"]*)"))/gi +exports.REG_URL = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i + +exports.CSS_IMPORT_REG = /@import (["'])(.+?)\1;/g + +exports.BUILD_TYPES = { + WEAPP: 'weapp', + H5: 'h5', + RN: 'rn', + SWAN: 'swan', + ALIPAY: 'alipay', + TT: 'tt', + UI: 'ui' +} + +exports.MINI_APP_FILES = { + [exports.BUILD_TYPES.WEAPP]: { + TEMPL: '.wxml', + STYLE: '.wxss', + SCRIPT: '.js', + CONFIG: '.json' + }, + [exports.BUILD_TYPES.SWAN]: { + TEMPL: '.swan', + STYLE: '.css', + SCRIPT: '.js', + CONFIG: '.json' + }, + [exports.BUILD_TYPES.ALIPAY]: { + TEMPL: '.axml', + STYLE: '.acss', + SCRIPT: '.js', + CONFIG: '.json' + }, + [exports.BUILD_TYPES.TT]: { + TEMPL: '.ttml', + STYLE: '.ttss', + SCRIPT: '.js', + CONFIG: '.json' + } +} + +exports.CONFIG_MAP = { + [exports.BUILD_TYPES.WEAPP]: { + navigationBarTitleText: 'navigationBarTitleText', + navigationBarBackgroundColor: 'navigationBarBackgroundColor', + enablePullDownRefresh: 'enablePullDownRefresh', + list: 'list', + text: 'text', + iconPath: 'iconPath', + selectedIconPath: 'selectedIconPath' + }, + [exports.BUILD_TYPES.SWAN]: { + navigationBarTitleText: 'navigationBarTitleText', + navigationBarBackgroundColor: 'navigationBarBackgroundColor', + enablePullDownRefresh: 'enablePullDownRefresh', + list: 'list', + text: 'text', + iconPath: 'iconPath', + selectedIconPath: 'selectedIconPath' + }, + [exports.BUILD_TYPES.TT]: { + navigationBarTitleText: 'navigationBarTitleText', + navigationBarBackgroundColor: 'navigationBarBackgroundColor', + enablePullDownRefresh: 'enablePullDownRefresh', + list: 'list', + text: 'text', + iconPath: 'iconPath', + selectedIconPath: 'selectedIconPath' + }, + [exports.BUILD_TYPES.ALIPAY]: { + navigationBarTitleText: 'defaultTitle', + navigationBarBackgroundColor: 'titleBarColor', + enablePullDownRefresh: 'pullRefresh', + list: 'items', + text: 'name', + iconPath: 'icon', + selectedIconPath: 'activeIcon' + } +} + +exports.PROJECT_CONFIG = 'config/index.js' +//@fix +exports.PROJECT_CONFIG_H5 = 'config/h5.js' + +exports.DEVICE_RATIO = { + '640': 2.34 / 2, + '750': 1, + '828': 1.81 / 2 +} + +exports.FILE_PROCESSOR_MAP = { + '.js': 'babel', + '.scss': 'sass', + '.sass': 'sass', + '.less': 'less', + '.styl': 'stylus' +} + +exports.isNpmPkg = function (name) { + if (/^(\.|\/)/.test(name)) { + return false + } + return true +} + +exports.isAliasPath = function (name, pathAlias = {}) { + const prefixs = Object.keys(pathAlias) + if (prefixs.length === 0) { + return false + } + return prefixs.includes(name) || (new RegExp(`^(${prefixs.join('|')})/`).test(name)) +} + +exports.replaceAliasPath = function (filePath, name, pathAlias = {}) { + // 后续的 path.join 在遇到符号链接时将会解析为真实路径,如果 + // 这里的 filePath 没有做同样的处理,可能会导致 import 指向 + // 源代码文件,导致文件被意外修改 + filePath = fs.realpathSync(filePath) + + const prefixs = Object.keys(pathAlias) + if (prefixs.includes(name)) { + return exports.promoteRelativePath(path.relative(filePath, fs.realpathSync(pathAlias[name]))) + } + const reg = new RegExp(`^(${prefixs.join('|')})/(.*)`) + name = name.replace(reg, function (m, $1, $2) { + return exports.promoteRelativePath(path.relative(filePath, path.join(pathAlias[$1], $2))) + }) + return name +} + +exports.promoteRelativePath = function (fPath) { + const fPathArr = fPath.split(path.sep) + let dotCount = 0 + fPathArr.forEach(item => { + if (item.indexOf('..') >= 0) { + dotCount++ + } + }) + if (dotCount === 1) { + fPathArr.splice(0, 1, '.') + return fPathArr.join('/') + } + if (dotCount > 1) { + fPathArr.splice(0, 1) + return fPathArr.join('/') + } + return fPath.replace(/\\/g, '/') +} + +exports.replaceAsync = async function (str, regex, asyncFn) { + const promises = [] + str.replace(regex, (match, ...args) => { + const promise = asyncFn(match, ...args) + promises.push(promise) + }) + const data = await Promise.all(promises) + return str.replace(regex, () => data.shift()) +} + +exports.homedir = (function () { + let homedir = null + const env = process.env + const home = env.HOME + const user = env.LOGNAME || env.USER || env.LNAME || env.USERNAME + if (process.platform === 'win32') { + homedir = env.USERPROFILE || env.HOMEDRIVE + env.HOMEPATH || home || null + } else if (process.platform === 'darwin') { + homedir = home || (user ? `/Users/${user}` : null) + } else if (process.platform === 'linux') { + homedir = home || (process.getuid() === 0 ? '/root' : (user ? `/home/${user}` : null)) + } + return typeof os.homedir === 'function' ? os.homedir : function () { + return homedir + } +})() + +exports.getRootPath = function () { + return path.resolve(__dirname, '../../') +} + +exports.getTaroPath = function () { + const taroPath = path.join(exports.homedir(), '.taro') + if (!fs.existsSync(taroPath)) { + fs.mkdirSync(taroPath) + } + return taroPath +} + +exports.setConfig = function (config) { + const taroPath = exports.getTaroPath() + if (typeof config === 'object') { + const oldConfig = exports.getConfig() + config = Object.assign({}, oldConfig, config) + fs.writeFileSync(path.join(taroPath, 'config.json'), JSON.stringify(config, null, 2)) + } +} + +exports.getConfig = function () { + const configPath = path.join(exports.getTaroPath(), 'config.json') + if (fs.existsSync(configPath)) { + return require(configPath) + } + return {} +} + +exports.getSystemUsername = function () { + const userHome = exports.homedir() + const systemUsername = process.env.USER || path.basename(userHome) + return systemUsername +} + +exports.getPkgVersion = function () { + return require(path.join(exports.getRootPath(), 'package.json')).version +} + +exports.getPkgItemByKey = function (key) { + const packageMap = require(path.join(exports.getRootPath(), 'package.json')) + if (Object.keys(packageMap).indexOf(key) === -1) { + return {} + } else { + return packageMap[key] + } +} + +exports.printPkgVersion = function () { + const taroVersion = exports.getPkgVersion() + console.log(`👽 Omi-Cloud v${taroVersion}`) + console.log() +} + +exports.shouldUseYarn = function () { + try { + execSync('yarn --version', { stdio: 'ignore' }) + return true + } catch (e) { + return false + } +} + +exports.shouldUseCnpm = function () { + try { + execSync('cnpm --version', { stdio: 'ignore' }) + return true + } catch (e) { + return false + } +} + +exports.isPublic = function isPublic (addr) { + return !exports.isPrivate(addr) +} + +exports.isEmptyObject = function (obj) { + if (obj == null) { + return true + } + for (const key in obj) { + if (obj.hasOwnProperty(key)) { + return false + } + } + return true +} + +exports.urlJoin = function () { + function normalize (str) { + return str + .replace(/([/]+)/g, '/') + .replace(/\/\?(?!\?)/g, '?') + .replace(/\/#/g, '#') + .replace(/:\//g, '://') + } + + const joined = [].slice.call(arguments, 0).join('/') + return normalize(joined) +} + +exports.resolveScriptPath = function (p) { + let realPath = p + const SCRIPT_EXT = exports.JS_EXT.concat(exports.TS_EXT) + for (let i = 0; i < SCRIPT_EXT.length; i++) { + const item = SCRIPT_EXT[i] + if (fs.existsSync(`${p}${item}`)) { + return `${p}${item}` + } + if (fs.existsSync(`${p}${path.sep}index${item}`)) { + return `${p}${path.sep}index${item}` + } + } + return realPath +} + +exports.resolveStylePath = function (p) { + let realPath = p + const CSS_EXT = exports.CSS_EXT + for (let i = 0; i < CSS_EXT.length; i++) { + const item = CSS_EXT[i] + if (fs.existsSync(`${p}${item}`)) { + return `${p}${item}` + } + } + return realPath +} + +exports.isDifferentArray = function (a, b) { + if (!Array.isArray(a) || !Array.isArray(b)) { + return true + } + if (a.length !== b.length) { + return true + } + a = a.sort() + b = b.sort() + for (let i = 0; i < a.length; i++) { + if (a[i] !== b[i]) { + return true + } + } + return false +} + +exports.checksum = function (buf, length) { + if (!Buffer.isBuffer(buf)) { + buf = Buffer.from(buf) + } + return crypto.createHash('md5').update(buf).digest('hex').slice(0, length || 8) +} + +exports.printLog = function (type, tag, filePath) { + const typeShow = processTypeMap[type] + const tagLen = tag.replace(/[\u0391-\uFFE5]/g, 'aa').length + const tagFormatLen = 8 + if (tagLen < tagFormatLen) { + const rightPadding = new Array(tagFormatLen - tagLen + 1).join(' ') + tag += rightPadding + } + const padding = '' + filePath = filePath || '' + if (typeof typeShow.color === 'string') { + console.log(chalk[typeShow.color](typeShow.name), padding, tag, padding, filePath) + } else { + console.log(typeShow.color(typeShow.name), padding, tag, padding, filePath) + } +} + +exports.replaceContentEnv = function (content, env) { + if (env && !exports.isEmptyObject(env)) { + for (const key in env) { + const reg = new RegExp(`process.env.${key}`, 'g') + content = content.replace(reg, env[key]) + } + return content + } + return content +} + +exports.generateEnvList = function (env) { + const res = { } + if (env && !exports.isEmptyObject(env)) { + for (const key in env) { + try { + res[`process.env.${key}`] = JSON.parse(env[key]) + } catch (err) { + res[`process.env.${key}`] = env[key] + } + } + } + return res +} + +exports.replaceContentConstants = function (content, constants) { + if (constants && !exports.isEmptyObject(constants)) { + for (const key in constants) { + const reg = new RegExp(key, 'g') + content = content.replace(reg, constants[key]) + } + return content + } + return content +} + +exports.generateConstantsList = function (constants) { + const res = { } + if (constants && !exports.isEmptyObject(constants)) { + for (const key in constants) { + try { + res[key] = JSON.parse(constants[key]) + } catch (err) { + res[key] = constants[key] + } + } + } + return res +} + +exports.cssImports = function (content) { + let match = {} + const results = [] + content = String(content).replace(/\/\*.+?\*\/|\/\/.*(?=[\n\r])/g, '') + while ((match = exports.CSS_IMPORT_REG.exec(content))) { + results.push(match[2]) + } + return results +} + +exports.processStyleImports = function (content, adapter, process) { + const style = [] + const imports = [] + const styleReg = new RegExp(`\\${exports.MINI_APP_FILES[adapter].STYLE}`) + content = content.replace(exports.CSS_IMPORT_REG, (m, $1, $2) => { + if (styleReg.test($2)) { + style.push(m) + imports.push($2) + if (process && typeof process === 'function') { + return process(m, $2) + } + return '' + } + if (process && typeof process === 'function') { + return process(m, $2) + } + return m + }) + return { + content, + style, + imports + } +} +/*eslint-disable*/ +const retries = (process.platform === 'win32') ? 100 : 1 +exports.emptyDirectory = function (dirPath, opts = { excludes: [] }) { + if (fs.existsSync(dirPath)) { + fs.readdirSync(dirPath).forEach(file => { + const curPath = path.join(dirPath, file) + if (fs.lstatSync(curPath).isDirectory()) { + let removed = false + let i = 0 // retry counter + + do { + try { + if (!opts.excludes.length || !opts.excludes.some(item => curPath.indexOf(item) >= 0)) { + exports.emptyDirectory(curPath) + fs.rmdirSync(curPath) + } + removed = true + } catch (e) { + } finally { + if (++i < retries) { + continue + } + } + } while (!removed) + } else { + fs.unlinkSync(curPath) + } + }) + } +} +/* eslint-enable */ + +exports.recursiveFindNodeModules = function (filePath) { + const dirname = path.dirname(filePath) + const nodeModules = path.join(dirname, 'node_modules') + if (fs.existsSync(nodeModules)) { + return nodeModules + } + return exports.recursiveFindNodeModules(dirname) +} + +exports.UPDATE_PACKAGE_LIST = [ + '@tarojs/taro', + '@tarojs/async-await', + '@tarojs/cli', + '@tarojs/components', + '@tarojs/components-rn', + '@tarojs/taro-h5', + '@tarojs/taro-swan', + '@tarojs/taro-alipay', + '@tarojs/taro-tt', + '@tarojs/plugin-babel', + '@tarojs/plugin-csso', + '@tarojs/plugin-sass', + '@tarojs/plugin-less', + '@tarojs/plugin-stylus', + '@tarojs/plugin-uglifyjs', + '@tarojs/redux', + '@tarojs/redux-h5', + '@tarojs/taro-redux-rn', + '@tarojs/taro-router-rn', + '@tarojs/taro-rn', + '@tarojs/rn-runner', + '@tarojs/router', + '@tarojs/taro-weapp', + '@tarojs/webpack-runner', + 'postcss-plugin-constparse', + 'eslint-config-taro', + 'eslint-plugin-taro', + 'taro-transformer-wx', + 'postcss-pxtransform', + 'babel-plugin-transform-jsx-to-stylesheet', + '@tarojs/mobx', + '@tarojs/mobx-h5', + '@tarojs/mobx-rn', + '@tarojs/mobx-common', + '@tarojs/mobx-prop-types' +] + +exports.pascalCase = (str) => str.charAt(0).toUpperCase() + _.camelCase(str.substr(1)) + +exports.getInstalledNpmPkgVersion = function (pkgName, basedir) { + const resolvePath = require('resolve') + try { + const pkg = resolvePath.sync(`${pkgName}/package.json`, { basedir }) + const pkgJson = fs.readJSONSync(pkg) + return pkgJson.version + } catch (err) { + return null + } +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/util/npm.js b/packages/omi-cloudbase/scripts/taro-cli/src/util/npm.js new file mode 100644 index 000000000..05821fb90 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/util/npm.js @@ -0,0 +1,164 @@ +const resolvePath = require('resolve') +const spawn = require('cross-spawn') +const chalk = require('chalk') + +const Util = require('./') + +const basedir = process.cwd() +const taroPluginPrefix = '@tarojs/plugin-' +const PEERS = /UNMET PEER DEPENDENCY ([a-z\-0-9.]+)@(.+)/gm +const npmCached = {} +const erroneous = [] +const defaultInstallOptions = { + dev: false, + peerDependencies: true +} + +function resolveNpm (pluginName) { + if (!npmCached[pluginName]) { + return new Promise((resolve, reject) => { + resolvePath(`${pluginName}`, {basedir}, (err, res) => { + if (err) { + return reject(err) + } + npmCached[pluginName] = res + resolve(res) + }) + }) + } + return Promise.resolve(npmCached[pluginName]) +} + +function resolveNpmSync (pluginName) { + try { + if (!npmCached[pluginName]) { + const res = resolvePath.sync(pluginName, {basedir}) + return res + } + return npmCached[pluginName] + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + console.log(chalk.cyan(`缺少npm包${pluginName},开始安装...`)) + const installOptions = {} + if (pluginName.indexOf(taroPluginPrefix) >= 0) { + installOptions.dev = true + } + installNpmPkg(pluginName, installOptions) + return resolveNpmSync(pluginName) + } + } +} + +function installNpmPkg (pkgList, options) { + if (!pkgList) { + return + } + if (!Array.isArray(pkgList)) { + pkgList = [pkgList] + } + pkgList = pkgList.filter(dep => { + return erroneous.indexOf(dep) === -1 + }) + + if (!pkgList.length) { + return + } + options = Object.assign({}, defaultInstallOptions, options) + let installer = '' + let args = [] + + if (Util.shouldUseYarn()) { + installer = 'yarn' + } else if (Util.shouldUseCnpm()) { + installer = 'cnpm' + } else { + installer = 'npm' + } + + if (Util.shouldUseYarn()) { + args = ['add'].concat(pkgList).filter(Boolean) + args.push('--silent', '--no-progress') + if (options.dev) { + args.push('-D') + } + } else { + args = ['install'].concat(pkgList).filter(Boolean) + args.push('--silent', '--no-progress') + if (options.dev) { + args.push('--save-dev') + } else { + args.push('--save') + } + } + const output = spawn.sync(installer, args, { + stdio: ['ignore', 'pipe', 'inherit'] + }) + if (output.status) { + pkgList.forEach(dep => { + erroneous.push(dep) + }) + } + let matches = null + const peers = [] + + while ((matches = PEERS.exec(output.stdout))) { + const pkg = matches[1] + const version = matches[2] + if (version.match(' ')) { + peers.push(pkg) + } else { + peers.push(`${pkg}@${version}`) + } + } + if (options.peerDependencies && peers.length) { + console.info('正在安装 peerDependencies...') + installNpmPkg(peers, options) + } + return output +} + +async function callPlugin (pluginName, content, file, config) { + const pluginFn = await getNpmPkg(`${taroPluginPrefix}${pluginName}`) + return pluginFn(content, file, config) +} + +function callPluginSync (pluginName, content, file, config) { + const pluginFn = getNpmPkgSync(`${taroPluginPrefix}${pluginName}`) + return pluginFn(content, file, config) +} + +function getNpmPkgSync (npmName) { + const npmPath = resolveNpmSync(npmName) + const npmFn = require(npmPath) + return npmFn +} + +async function getNpmPkg (npmName) { + let npmPath + try { + npmPath = resolveNpmSync(npmName) + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + console.log(chalk.cyan(`缺少npm包${npmName},开始安装...`)) + const installOptions = {} + if (npmName.indexOf(taroPluginPrefix) >= 0) { + installOptions.dev = true + } + installNpmPkg(npmName, installOptions) + npmPath = await resolveNpm(npmName) + } + } + const npmFn = require(npmPath) + return npmFn +} + +module.exports = { + taroPluginPrefix, + installNpmPkg, + resolveNpm, + resolveNpmSync, + callPlugin, + callPluginSync, + getNpmPkg, + getNpmPkgSync +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/util/resolve_npm_files.js b/packages/omi-cloudbase/scripts/taro-cli/src/util/resolve_npm_files.js new file mode 100644 index 000000000..6476c8f4a --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/util/resolve_npm_files.js @@ -0,0 +1,270 @@ +const fs = require('fs-extra') +const path = require('path') +const resolvePath = require('resolve') +const wxTransformer = require('../../../taro-transformer-wx/lib/src/index.js').default +const babel = require('babel-core') +const traverse = require('babel-traverse').default +const t = require('babel-types') +const generate = require('babel-generator').default +const _ = require('lodash') + +const defaultUglifyConfig = require('../config/uglify') + +const { + isNpmPkg, + promoteRelativePath, + printLog, + pocessTypeEnum, + PROJECT_CONFIG, + generateEnvList, + REG_TYPESCRIPT, + BUILD_TYPES, + REG_STYLE, + recursiveFindNodeModules +} = require('./index') + +const CONFIG = require('../config') +const defaultBabelConfig = require('../config/babel') + +const npmProcess = require('./npm') + +const excludeNpmPkgs = ['ReactPropTypes'] + +const resolvedCache = {} +const copyedFiles = {} + +const basedir = process.cwd() +const configDir = path.join(basedir, PROJECT_CONFIG) +const projectConfig = require(configDir)(_.merge) +const pluginsConfig = projectConfig.plugins || {} +const outputDirName = projectConfig.outputRoot || CONFIG.OUTPUT_DIR + +const babelConfig = _.mergeWith({}, defaultBabelConfig, pluginsConfig.babel, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return Array.from(new Set(srcValue.concat(objValue))) + } +}) + +function resolveNpmPkgMainPath (pkgName, isProduction, npmConfig, buildAdapter = BUILD_TYPES.WEAPP, root = basedir) { + try { + return resolvePath.sync(pkgName, { basedir: root }) + } catch (err) { + if (err.code === 'MODULE_NOT_FOUND') { + console.log(`缺少npm包${pkgName},开始安装...`) + const installOptions = {} + if (pkgName.indexOf(npmProcess.taroPluginPrefix) >= 0) { + installOptions.dev = true + } + npmProcess.installNpmPkg(pkgName, installOptions) + return resolveNpmPkgMainPath(pkgName, isProduction, npmConfig, buildAdapter, root) + } + } +} + +function resolveNpmFilesPath (pkgName, isProduction, npmConfig, buildAdapter = BUILD_TYPES.WEAPP, root = basedir, compileInclude = []) { + if (!resolvedCache[pkgName]) { + const res = resolveNpmPkgMainPath(pkgName, isProduction, npmConfig, buildAdapter, root) + resolvedCache[pkgName] = { + main: res, + files: [] + } + resolvedCache[pkgName].files.push(res) + recursiveRequire(res, resolvedCache[pkgName].files, isProduction, npmConfig, buildAdapter, compileInclude) + } + return resolvedCache[pkgName] +} + +function parseAst (ast, filePath, files, isProduction, npmConfig, buildAdapter = BUILD_TYPES.WEAPP, compileInclude) { + const excludeRequire = [] + traverse(ast, { + IfStatement (astPath) { + astPath.traverse({ + BinaryExpression (astPath) { + const node = astPath.node + const left = node.left + if (generate(left).code === 'process.env.TARO_ENV' && + node.right.value !== buildAdapter) { + const consequentSibling = astPath.getSibling('consequent') + consequentSibling.traverse({ + CallExpression (astPath) { + if (astPath.get('callee').isIdentifier({ name: 'require' })) { + const arg = astPath.get('arguments')[0] + if (t.isStringLiteral(arg.node)) { + excludeRequire.push(arg.node.value) + } + } + } + }) + } + } + }) + }, + Program: { + exit (astPath) { + astPath.traverse({ + CallExpression (astPath) { + const node = astPath.node + const callee = node.callee + if (callee.name === 'require') { + const args = node.arguments + let requirePath = args[0].value + if (excludeRequire.indexOf(requirePath) < 0) { + if (isNpmPkg(requirePath)) { + if (excludeNpmPkgs.indexOf(requirePath) < 0) { + const res = resolveNpmFilesPath(requirePath, isProduction, npmConfig, buildAdapter, path.dirname(recursiveFindNodeModules(filePath)), compileInclude) + let relativeRequirePath = promoteRelativePath(path.relative(filePath, res.main)) + relativeRequirePath = relativeRequirePath.replace(/node_modules/g, npmConfig.name) + if (buildAdapter === BUILD_TYPES.ALIPAY) { + relativeRequirePath = relativeRequirePath.replace(/@/g, '_') + } + args[0].value = relativeRequirePath + } + } else { + let realRequirePath = path.resolve(path.dirname(filePath), requirePath) + let tempPathWithJS = `${realRequirePath}.js` + let tempPathWithIndexJS = `${realRequirePath}${path.sep}index.js` + if (fs.existsSync(tempPathWithJS)) { + realRequirePath = tempPathWithJS + requirePath += '.js' + } else if (fs.existsSync(tempPathWithIndexJS)) { + realRequirePath = tempPathWithIndexJS + requirePath += '/index.js' + } + if (files.indexOf(realRequirePath) < 0) { + files.push(realRequirePath) + recursiveRequire(realRequirePath, files, isProduction, npmConfig, buildAdapter, compileInclude) + } + args[0].value = requirePath + } + } + } + } + }) + } + } + }) + return generate(ast).code +} + +async function recursiveRequire (filePath, files, isProduction, npmConfig = {}, buildAdapter, compileInclude = []) { + let fileContent = fs.readFileSync(filePath).toString() + let outputNpmPath + if (!npmConfig.dir) { + const cwdRelate2Npm = path.relative( + filePath.slice(0, filePath.search('node_modules')), + process.cwd() + ) + outputNpmPath = filePath.replace('node_modules', path.join(cwdRelate2Npm, outputDirName, npmConfig.name)) + outputNpmPath = outputNpmPath.replace(/node_modules/g, npmConfig.name) + } else { + let npmFilePath = filePath.match(/(?=(node_modules)).*/)[0] + npmFilePath = npmFilePath.replace(/node_modules/g, npmConfig.name) + outputNpmPath = path.join(path.resolve(configDir, '..', npmConfig.dir), npmFilePath) + } + if (buildAdapter === BUILD_TYPES.ALIPAY) { + outputNpmPath = outputNpmPath.replace(/@/g, '_') + } + if (REG_STYLE.test(path.basename(filePath))) { + return + } + fileContent = npmCodeHack(filePath, fileContent, buildAdapter) + try { + const constantsReplaceList = Object.assign({ + 'process.env.TARO_ENV': buildAdapter + }, generateEnvList(projectConfig.env || {})) + const transformResult = wxTransformer({ + code: fileContent, + sourcePath: filePath, + outputPath: outputNpmPath, + isNormal: true, + adapter: buildAdapter, + isTyped: REG_TYPESCRIPT.test(filePath), + env: constantsReplaceList + }) + const ast = babel.transformFromAst(transformResult.ast, '', { + plugins: [ + [require('babel-plugin-transform-define').default, constantsReplaceList] + ] + }).ast + fileContent = parseAst(ast, filePath, files, isProduction, npmConfig, buildAdapter, compileInclude) + } catch (err) { + console.log(err) + } + if (!copyedFiles[outputNpmPath]) { + if (compileInclude && compileInclude.length) { + const filePathArr = filePath.split(path.sep) + const nodeModulesIndex = filePathArr.indexOf('node_modules') + const npmPkgName = filePathArr[nodeModulesIndex + 1] + if (compileInclude.indexOf(npmPkgName) >= 0) { + const compileScriptRes = await npmProcess.callPlugin('babel', fileContent, filePath, babelConfig) + fileContent = compileScriptRes.code + } + } + if (isProduction) { + const uglifyPluginConfig = pluginsConfig.uglify || { enable: true } + if (uglifyPluginConfig.enable) { + const uglifyConfig = Object.assign(defaultUglifyConfig, uglifyPluginConfig.config || {}) + const uglifyResult = npmProcess.callPluginSync('uglifyjs', fileContent, outputNpmPath, uglifyConfig) + if (uglifyResult.error) { + printLog(pocessTypeEnum.ERROR, '压缩错误', `文件${filePath}`) + console.log(uglifyResult.error) + } else { + fileContent = uglifyResult.code + } + } + } + fs.ensureDirSync(path.dirname(outputNpmPath)) + fs.writeFileSync(outputNpmPath, fileContent) + let modifyOutput = outputNpmPath.replace(basedir + path.sep, '') + modifyOutput = modifyOutput.split(path.sep).join('/') + printLog(pocessTypeEnum.COPY, 'NPM文件', modifyOutput) + copyedFiles[outputNpmPath] = true + } +} + +function npmCodeHack (filePath, content, buildAdapter) { + const basename = path.basename(filePath) + switch (basename) { + case 'lodash.js': + case '_global.js': + case 'lodash.min.js': + if (buildAdapter === BUILD_TYPES.ALIPAY || buildAdapter === BUILD_TYPES.SWAN) { + content = content.replace(/Function\(['"]return this['"]\)\(\)/, '{}') + } else { + content = content.replace(/Function\(['"]return this['"]\)\(\)/, 'this') + } + break + case 'mobx.js': + // 解决支付宝小程序全局window或global不存在的问题 + content = content.replace( + /typeof window\s{0,}!==\s{0,}['"]undefined['"]\s{0,}\?\s{0,}window\s{0,}:\s{0,}global/, + 'typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}' + ) + break + case '_html.js': + content = 'module.exports = false;' + break + case '_microtask.js': + content = content.replace('if(Observer)', 'if(false && Observer)') + // IOS 1.10.2 Promise BUG + content = content.replace('Promise && Promise.resolve', 'false && Promise && Promise.resolve') + break + case '_freeGlobal.js': + content = content.replace('module.exports = freeGlobal;', 'module.exports = freeGlobal || this || global || {};') + break + } + if (buildAdapter === BUILD_TYPES.ALIPAY && content.replace(/\s\r\n/g, '').length <= 0) { + content = '// Empty file' + } + return content +} + +function getResolvedCache () { + return resolvedCache +} + +module.exports = { + getResolvedCache, + resolveNpmFilesPath, + resolveNpmPkgMainPath +} diff --git a/packages/omi-cloudbase/scripts/taro-cli/src/weapp.js b/packages/omi-cloudbase/scripts/taro-cli/src/weapp.js new file mode 100644 index 000000000..fd568983a --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-cli/src/weapp.js @@ -0,0 +1,2321 @@ +const fs = require('fs-extra') +const os = require('os') +const path = require('path') +const chalk = require('chalk') +const chokidar = require('chokidar') +//@fix - 为了本地调试 +const wxTransformer = require('../../taro-transformer-wx/lib/src/index.js').default +const babel = require('babel-core') +const traverse = require('babel-traverse').default +const t = require('babel-types') +const generate = require('babel-generator').default +const template = require('babel-template') +const autoprefixer = require('autoprefixer') +const minimatch = require('minimatch') +const _ = require('lodash') + +const postcss = require('postcss') +const pxtransform = require('postcss-pxtransform') +const cssUrlParse = require('postcss-url') +const Scope = require('postcss-modules-scope') +const Values = require('postcss-modules-values') +const genericNames = require('generic-names') +const LocalByDefault = require('postcss-modules-local-by-default') +const ExtractImports = require('postcss-modules-extract-imports') +const ResolveImports = require('postcss-modules-resolve-imports') + +const Util = require('./util') +const CONFIG = require('./config') +const npmProcess = require('./util/npm') +const { resolveNpmFilesPath, resolveNpmPkgMainPath } = require('./util/resolve_npm_files') +const babylonConfig = require('./config/babylon') +const browserList = require('./config/browser_list') +const defaultUglifyConfig = require('./config/uglify') +const defaultBabelConfig = require('./config/babel') +const astConvert = require('./util/ast_convert') + +const appPath = process.cwd() +const configDir = path.join(appPath, Util.PROJECT_CONFIG) +const projectConfig = require(configDir)(_.merge) +const sourceDirName = projectConfig.sourceRoot || CONFIG.SOURCE_DIR +const outputDirName = projectConfig.outputRoot || CONFIG.OUTPUT_DIR +const sourceDir = path.join(appPath, sourceDirName) +const outputDir = path.join(appPath, outputDirName) +const entryFilePath = Util.resolveScriptPath(path.join(sourceDir, CONFIG.ENTRY)) +const entryFileName = path.basename(entryFilePath) +const outputEntryFilePath = path.join(outputDir, entryFileName) +const watcherDirs = projectConfig.watcher || [] +const pathAlias = projectConfig.alias || {} + +const pluginsConfig = projectConfig.plugins || {} +const weappConf = projectConfig.weapp || {} +const weappNpmConfig = Object.assign({ + name: CONFIG.NPM_DIR, + dir: null +}, weappConf.npm) +const appOutput = typeof weappConf.appOutput === 'boolean' ? weappConf.appOutput : true +const useCompileConf = Object.assign({}, weappConf.compile) +const compileInclude = useCompileConf.include || [] + +const notExistNpmList = [] +const taroJsFramework = '@tarojs/taro' +const taroJsComponents = '@tarojs/components' +const taroJsRedux = '@tarojs/redux' +let appConfig = {} +const dependencyTree = {} +const depComponents = {} +const hasBeenBuiltComponents = [] +const componentsBuildResult = {} +const componentsNamedMap = {} +const componentExportsMap = {} +const wxssDepTree = {} +let isBuildingScripts = {} +let isBuildingStyles = {} +let isCopyingFiles = {} +let isProduction = false +let buildAdapter = Util.BUILD_TYPES.WEAPP +let outputFilesTypes = Util.MINI_APP_FILES[buildAdapter] +let notTaroComponents = [] + +const NODE_MODULES = 'node_modules' +const NODE_MODULES_REG = /(.*)node_modules/ + +const nodeModulesPath = Util.recursiveFindNodeModules(path.join(appPath, NODE_MODULES)) +let npmOutputDir + +if (!weappNpmConfig.dir) { + npmOutputDir = path.join(outputDir, weappNpmConfig.name) +} else { + npmOutputDir = path.join(path.resolve(configDir, '..', weappNpmConfig.dir), weappNpmConfig.name) +} + +const PARSE_AST_TYPE = { + ENTRY: 'ENTRY', + PAGE: 'PAGE', + COMPONENT: 'COMPONENT', + NORMAL: 'NORMAL' +} + +const DEVICE_RATIO = 'deviceRatio' + +const isWindows = os.platform() === 'win32' + +let constantsReplaceList = Object.assign({}, Util.generateEnvList(projectConfig.env || {}), Util.generateConstantsList(projectConfig.defineConstants || {})) + +//@fix +exists(path.join('./src/cloud'), path.join('./dist/cloudfunctions'), copy) + +function getExactedNpmFilePath (npmName, filePath) { + try { + //里面会递归 require 进行拷贝到 npm 目录 + const npmInfo = resolveNpmFilesPath(npmName, isProduction, weappNpmConfig, buildAdapter, appPath, compileInclude) + const npmInfoMainPath = npmInfo.main + let outputNpmPath + if (Util.REG_STYLE.test(npmInfoMainPath)) { + outputNpmPath = npmInfoMainPath + } else { + if (!weappNpmConfig.dir) { + const cwdRelate2Npm = path.relative(npmInfoMainPath.slice(0, npmInfoMainPath.search('node_modules')), process.cwd()) + outputNpmPath = npmInfoMainPath.replace(NODE_MODULES, path.join(cwdRelate2Npm, outputDirName, weappNpmConfig.name)) + outputNpmPath = outputNpmPath.replace(/node_modules/g, weappNpmConfig.name) + } else { + let npmFilePath = npmInfoMainPath.match(/(?=(node_modules)).*/)[0] + npmFilePath = npmFilePath.replace(/node_modules/g, weappNpmConfig.name) + outputNpmPath = path.join(path.resolve(configDir, '..', weappNpmConfig.dir), npmFilePath) + } + } + if (buildAdapter === Util.BUILD_TYPES.ALIPAY) { + outputNpmPath = outputNpmPath.replace(/@/g, '_') + } + const relativePath = path.relative(filePath, outputNpmPath) + return Util.promoteRelativePath(relativePath) + } catch (err) { + console.log(err) + if (notExistNpmList.indexOf(npmName) < 0) { + notExistNpmList.push(npmName) + } + return npmName + } +} + +function traverseObjectNode (node, obj) { + if (node.type === 'ClassProperty' || node.type === 'ObjectProperty') { + const properties = node.value.properties + obj = {} + properties.forEach(p => { + let key = t.isIdentifier(p.key) ? p.key.name : p.key.value + if (Util.CONFIG_MAP[buildAdapter][key]) { + key = Util.CONFIG_MAP[buildAdapter][key] + } + obj[key] = traverseObjectNode(p.value) + }) + return obj + } + if (node.type === 'ObjectExpression') { + const properties = node.properties + obj = {} + properties.forEach(p => { + let key = t.isIdentifier(p.key) ? p.key.name : p.key.value + if (Util.CONFIG_MAP[buildAdapter][key]) { + key = Util.CONFIG_MAP[buildAdapter][key] + } + obj[key] = traverseObjectNode(p.value) + }) + return obj + } + if (node.type === 'ArrayExpression') { + return node.elements.map(item => traverseObjectNode(item)) + } + if (node.type === 'NullLiteral') { + return null + } + return node.value +} + +function analyzeImportUrl ({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles }) { + const valueExtname = path.extname(value) + const node = astPath.node + if (value.indexOf('.') === 0) { + let importPath = path.resolve(path.dirname(sourceFilePath), value) + importPath = Util.resolveScriptPath(importPath) + if (isFileToBePage(importPath)) { + astPath.remove() + } else { + if (Util.REG_SCRIPT.test(valueExtname) || Util.REG_TYPESCRIPT.test(valueExtname)) { + const vpath = path.resolve(sourceFilePath, '..', value) + let fPath = value + if (fs.existsSync(vpath) && vpath !== sourceFilePath) { + fPath = vpath + } + if (scriptFiles.indexOf(fPath) < 0) { + scriptFiles.push(fPath) + } + } else if (Util.REG_JSON.test(valueExtname)) { + const vpath = path.resolve(sourceFilePath, '..', value) + if (jsonFiles.indexOf(vpath) < 0) { + jsonFiles.push(vpath) + } + if (fs.existsSync(vpath)) { + const obj = JSON.parse(fs.readFileSync(vpath).toString()) + const specifiers = node.specifiers + let defaultSpecifier = null + specifiers.forEach(item => { + if (item.type === 'ImportDefaultSpecifier') { + defaultSpecifier = item.local.name + } + }) + if (defaultSpecifier) { + let objArr = [t.nullLiteral()] + if (Array.isArray(obj)) { + objArr = t.arrayExpression(astConvert.array(obj)) + } else { + objArr = t.objectExpression(astConvert.obj(obj)) + } + astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(defaultSpecifier), objArr)])) + } + } + } else if (Util.REG_FONT.test(valueExtname) || Util.REG_IMAGE.test(valueExtname) || Util.REG_MEDIA.test(valueExtname)) { + const vpath = path.resolve(sourceFilePath, '..', value) + if (!fs.existsSync(vpath)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`) + return + } + if (mediaFiles.indexOf(vpath) < 0) { + mediaFiles.push(vpath) + } + const specifiers = node.specifiers + let defaultSpecifier = null + specifiers.forEach(item => { + if (item.type === 'ImportDefaultSpecifier') { + defaultSpecifier = item.local.name + } + }) + let sourceDirPath = sourceDir + if (NODE_MODULES_REG.test(vpath)) { + sourceDirPath = nodeModulesPath + } + + if (defaultSpecifier) { + astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(defaultSpecifier), t.stringLiteral(vpath.replace(sourceDirPath, '').replace(/\\/g, '/')))])) + } else { + astPath.remove() + } + } else if (Util.REG_STYLE.test(valueExtname)) { + const stylePath = path.resolve(path.dirname(sourceFilePath), value) + if (styleFiles.indexOf(stylePath) < 0) { + styleFiles.push(stylePath) + } + astPath.remove() + } else { + let vpath = Util.resolveScriptPath(path.resolve(sourceFilePath, '..', value)) + let outputVpath + if (NODE_MODULES_REG.test(vpath)) { + outputVpath = vpath.replace(nodeModulesPath, npmOutputDir) + } else { + outputVpath = vpath.replace(sourceDir, outputDir) + } + let relativePath = path.relative(filePath, outputVpath) + if (vpath && vpath !== sourceFilePath) { + if (!fs.existsSync(vpath)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`) + } else { + if (fs.lstatSync(vpath).isDirectory()) { + if (fs.existsSync(path.join(vpath, 'index.js'))) { + vpath = path.join(vpath, 'index.js') + relativePath = path.join(relativePath, 'index.js') + } else { + Util.printLog(Util.pocessTypeEnum.ERROR, '引用目录', `文件 ${sourceFilePath} 中引用了目录 ${value}!`) + return + } + } + if (scriptFiles.indexOf(vpath) < 0) { + scriptFiles.push(vpath) + } + relativePath = Util.promoteRelativePath(relativePath) + relativePath = relativePath.replace(path.extname(relativePath), '.js') + node.source.value = relativePath + } + } + } + } + } +} + +function parseAst (type, ast, depComponents, sourceFilePath, filePath, npmSkip = false) { + const styleFiles = [] + const scriptFiles = [] + const jsonFiles = [] + const mediaFiles = [] + let configObj = {} + let componentClassName = null + let taroJsReduxConnect = null + let taroMiniAppFramework = `@tarojs/taro-${buildAdapter}` + let taroImportDefaultName + let needExportDefault = false + let exportTaroReduxConnected = null + ast = babel.transformFromAst(ast, '', { + plugins: [ + [require('babel-plugin-danger-remove-unused-import'), { ignore: ['@tarojs/taro', 'react', 'nervjs'] }], + [require('babel-plugin-transform-define').default, constantsReplaceList] + ] + }).ast + traverse(ast, { + ClassDeclaration (astPath) { + const node = astPath.node + let hasCreateData = false + if (node.superClass) { + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: '_createData' })) { + hasCreateData = true + } + } + }) + if (hasCreateData) { + needExportDefault = true + astPath.traverse({ + ClassMethod (astPath) { + const node = astPath.node + if (node.kind === 'constructor') { + astPath.traverse({ + ExpressionStatement (astPath) { + const node = astPath.node + if (node.expression && + node.expression.type === 'AssignmentExpression' && + node.expression.operator === '=') { + const left = node.expression.left + if (left.type === 'MemberExpression' && + left.object.type === 'ThisExpression' && + left.property.type === 'Identifier' && + left.property.name === 'config') { + configObj = traverseObjectNode(node.expression.right) + } + } + } + }) + } + } + }) + if (node.id === null) { + componentClassName = '_TaroComponentClass' + astPath.replaceWith(t.classDeclaration(t.identifier(componentClassName), node.superClass, node.body, node.decorators || [])) + } else if (node.id.name === 'App') { + componentClassName = '_App' + astPath.replaceWith(t.classDeclaration(t.identifier(componentClassName), node.superClass, node.body, node.decorators || [])) + } else { + componentClassName = node.id.name + } + } + } + }, + + ClassExpression (astPath) { + const node = astPath.node + if (node.superClass) { + let hasCreateData = false + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: '_createData' })) { + hasCreateData = true + } + } + }) + if (hasCreateData) { + needExportDefault = true + if (node.id === null) { + const parentNode = astPath.parentPath.node + if (t.isVariableDeclarator(astPath.parentPath)) { + componentClassName = parentNode.id.name + } else { + componentClassName = '_TaroComponentClass' + } + astPath.replaceWith(t.ClassExpression(t.identifier(componentClassName), node.superClass, node.body, node.decorators || [])) + } else if (node.id.name === 'App') { + componentClassName = '_App' + astPath.replaceWith(t.ClassExpression(t.identifier(componentClassName), node.superClass, node.body, node.decorators || [])) + } else { + componentClassName = node.id.name + } + } + } + }, + + ClassProperty (astPath) { + const node = astPath.node + if (node.key.name === 'config') { + configObj = traverseObjectNode(node) + } + }, + + ImportDeclaration (astPath) { + const node = astPath.node + const source = node.source + let value = source.value + const specifiers = node.specifiers + // alias 替换 + if (Util.isAliasPath(value, pathAlias)) { + value = Util.replaceAliasPath(sourceFilePath, value, pathAlias) + source.value = value + } + if (Util.isNpmPkg(value) && notExistNpmList.indexOf(value) < 0) { + if (value === taroJsComponents) { + astPath.remove() + } else { + let isDepComponent = false + if (depComponents && depComponents.length) { + depComponents.forEach(item => { + if (item.path === value) { + isDepComponent = true + } + }) + } + if (isDepComponent) { + astPath.remove() + } else { + const specifiers = node.specifiers + if (value === taroJsFramework) { + let defaultSpecifier = null + specifiers.forEach(item => { + if (item.type === 'ImportDefaultSpecifier') { + defaultSpecifier = item.local.name + } + }) + if (defaultSpecifier) { + taroImportDefaultName = defaultSpecifier + } + value = taroMiniAppFramework + } else if (value === taroJsRedux) { + specifiers.forEach(item => { + if (item.type === 'ImportSpecifier') { + const local = item.local + if (local.type === 'Identifier' && local.name === 'connect') { + taroJsReduxConnect = item.imported.name + } + } + }) + } + if (!npmSkip) { + //拷贝 npm files + source.value = getExactedNpmFilePath(value, filePath) + } else { + source.value = value + } + } + } + } else if (Util.CSS_EXT.indexOf(path.extname(value)) !== -1 && specifiers.length > 0) { // 对 使用 import style from './style.css' 语法引入的做转化处理 + Util.printLog(Util.pocessTypeEnum.GENERATE, '替换代码', `为文件 ${sourceFilePath} 生成 css modules`) + const styleFilePath = path.join(path.dirname(sourceFilePath), value) + const styleCode = fs.readFileSync(styleFilePath).toString() + const result = processStyleUseCssModule({ + css: styleCode, + filePath: styleFilePath + }) + const tokens = result.root.exports || {} + const objectPropperties = [] + for (const key in tokens) { + if (tokens.hasOwnProperty(key)) { + let keyPath = key + if (key.indexOf('-') >= 0) { + keyPath = `'${key}'` + } + objectPropperties.push(t.objectProperty(t.identifier(keyPath), t.stringLiteral(tokens[key]))) + } + } + let defaultDeclator = null + let normalDeclator = null + let importItems = [] + specifiers.forEach(s => { + if (t.isImportDefaultSpecifier(s)) { + defaultDeclator = [t.variableDeclarator(t.identifier(s.local.name), t.objectExpression(objectPropperties))] + } else { + importItems.push(t.objectProperty(t.identifier(s.local.name), t.identifier(s.local.name))) + } + }) + normalDeclator = [t.variableDeclarator(t.objectPattern(importItems), t.objectExpression(objectPropperties))] + if (defaultDeclator) { + astPath.insertBefore(t.variableDeclaration('const', defaultDeclator)) + } + if (normalDeclator) { + astPath.insertBefore(t.variableDeclaration('const', normalDeclator)) + } + astPath.remove() + if (styleFiles.indexOf(styleFilePath) < 0) { // add this css file to queue + styleFiles.push(styleFilePath) + } + } else if (path.isAbsolute(value)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 是绝对路径!`) + } + }, + + CallExpression (astPath) { + const node = astPath.node + const callee = node.callee + if (t.isMemberExpression(callee)) { + if (taroImportDefaultName && callee.object.name === taroImportDefaultName && callee.property.name === 'render') { + astPath.remove() + } + } else if (callee.name === 'require') { + const args = node.arguments + let value = args[0].value + if (Util.isAliasPath(value, pathAlias)) { + value = Util.replaceAliasPath(sourceFilePath, value, pathAlias) + args[0].value = value + } + if (Util.isNpmPkg(value) && notExistNpmList.indexOf(value) < 0) { + if (value === taroJsComponents) { + astPath.remove() + } else { + let isDepComponent = false + if (depComponents && depComponents.length) { + depComponents.forEach(item => { + if (item.path === value) { + isDepComponent = true + } + }) + } + if (isDepComponent) { + astPath.remove() + } else { + if (t.isVariableDeclaration(astPath.parentPath.parentPath)) { + const parentNode = astPath.parentPath.parentPath.node + if (parentNode.declarations.length === 1 && parentNode.declarations[0].init) { + const id = parentNode.declarations[0].id + if (value === taroJsFramework && id.type === 'Identifier') { + taroImportDefaultName = id.name + value = taroMiniAppFramework + } else if (value === taroJsRedux) { + const declarations = parentNode.declarations + declarations.forEach(item => { + const id = item.id + if (id.type === 'ObjectPattern') { + const properties = id.properties + properties.forEach(p => { + if (p.type === 'ObjectProperty') { + if (p.value.type === 'Identifier' && p.value.name === 'connect') { + taroJsReduxConnect = p.key.name + } + } + }) + } + }) + } + } + } + if (!npmSkip) { + args[0].value = getExactedNpmFilePath(value, filePath) + } else { + args[0].value = value + } + } + } + } else if (Util.CSS_EXT.indexOf(path.extname(value)) !== -1 && t.isVariableDeclarator(astPath.parentPath)) { // 对 使用 const style = require('./style.css') 语法引入的做转化处理 + Util.printLog(Util.pocessTypeEnum.GENERATE, '替换代码', `为文件 ${sourceFilePath} 生成 css modules`) + const styleFilePath = path.join(path.dirname(sourceFilePath), value) + const styleCode = fs.readFileSync(styleFilePath).toString() + const result = processStyleUseCssModule({ + css: styleCode, + filePath: styleFilePath + }) + const tokens = result.root.exports || {} + const objectPropperties = [] + for (const key in tokens) { + if (tokens.hasOwnProperty(key)) { + objectPropperties.push(t.objectProperty(t.identifier(key), t.stringLiteral(tokens[key]))) + } + } + astPath.replaceWith(t.objectExpression(objectPropperties)) + if (styleFiles.indexOf(styleFilePath) < 0) { // add this css file to queue + styleFiles.push(styleFilePath) + } + } else if (path.isAbsolute(value)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 是绝对路径!`) + } + } + }, + + ExportDefaultDeclaration (astPath) { + const node = astPath.node + const declaration = node.declaration + needExportDefault = false + if ( + declaration && + (declaration.type === 'ClassDeclaration' || declaration.type === 'ClassExpression') + ) { + const superClass = declaration.superClass + if (superClass) { + let hasCreateData = false + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: '_createData' })) { + hasCreateData = true + } + } + }) + if (hasCreateData) { + needExportDefault = true + if (declaration.id === null) { + componentClassName = '_TaroComponentClass' + } else if (declaration.id.name === 'App') { + componentClassName = '_App' + } else { + componentClassName = declaration.id.name + } + const isClassDcl = declaration.type === 'ClassDeclaration' + const classDclProps = [t.identifier(componentClassName), superClass, declaration.body, declaration.decorators || []] + astPath.replaceWith(isClassDcl ? t.classDeclaration.apply(null, classDclProps) : t.classExpression.apply(null, classDclProps)) + } + } + } else if (declaration.type === 'CallExpression') { + const callee = declaration.callee + if (callee && callee.type === 'CallExpression') { + const subCallee = callee.callee + if (subCallee.type === 'Identifier' && subCallee.name === taroJsReduxConnect) { + const args = declaration.arguments + if (args.length === 1 && args[0].name === componentClassName) { + needExportDefault = true + exportTaroReduxConnected = `${componentClassName}__Connected` + astPath.replaceWith(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(`${componentClassName}__Connected`), t.CallExpression(declaration.callee, declaration.arguments))])) + } + } + } + } + }, + + ExportNamedDeclaration (astPath) { + const node = astPath.node + const source = node.source + if (source && source.type === 'StringLiteral') { + const value = source.value + analyzeImportUrl({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles }) + } + }, + + ExportAllDeclaration (astPath) { + const node = astPath.node + const source = node.source + if (source && source.type === 'StringLiteral') { + const value = source.value + analyzeImportUrl({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles }) + } + }, + + Program: { + exit (astPath) { + astPath.traverse({ + ImportDeclaration (astPath) { + const node = astPath.node + const source = node.source + let value = source.value + analyzeImportUrl({ astPath, value, depComponents, sourceFilePath, filePath, styleFiles, scriptFiles, jsonFiles, mediaFiles }) + }, + CallExpression (astPath) { + const node = astPath.node + const callee = node.callee + if (callee.name === 'require') { + const args = node.arguments + let value = args[0].value + const valueExtname = path.extname(value) + if (value.indexOf('.') === 0) { + let importPath = path.resolve(path.dirname(sourceFilePath), value) + importPath = Util.resolveScriptPath(importPath) + if (isFileToBePage(importPath)) { + if (astPath.parent.type === 'AssignmentExpression' || 'ExpressionStatement') { + astPath.parentPath.remove() + } else if (astPath.parent.type === 'VariableDeclarator') { + astPath.parentPath.parentPath.remove() + } else { + astPath.remove() + } + } else { + if (Util.REG_STYLE.test(valueExtname)) { + const stylePath = path.resolve(path.dirname(sourceFilePath), value) + if (styleFiles.indexOf(stylePath) < 0) { + styleFiles.push(stylePath) + } + if (astPath.parent.type === 'AssignmentExpression' || 'ExpressionStatement') { + astPath.parentPath.remove() + } else if (astPath.parent.type === 'VariableDeclarator') { + astPath.parentPath.parentPath.remove() + } else { + astPath.remove() + } + } else if (Util.REG_JSON.test(valueExtname)) { + const vpath = path.resolve(sourceFilePath, '..', value) + if (jsonFiles.indexOf(vpath) < 0) { + jsonFiles.push(vpath) + } + if (fs.existsSync(vpath)) { + const obj = JSON.parse(fs.readFileSync(vpath).toString()) + let objArr = [t.nullLiteral()] + if (Array.isArray(obj)) { + objArr = t.arrayExpression(astConvert.array(obj)) + } else { + objArr = t.objectExpression(astConvert.obj(obj)) + } + astPath.replaceWith(t.objectExpression(objArr)) + } + } else if (Util.REG_SCRIPT.test(valueExtname) || Util.REG_TYPESCRIPT.test(valueExtname)) { + const vpath = path.resolve(sourceFilePath, '..', value) + let fPath = value + if (fs.existsSync(vpath) && vpath !== sourceFilePath) { + fPath = vpath + } + if (scriptFiles.indexOf(fPath) < 0) { + scriptFiles.push(fPath) + } + } else if (Util.REG_FONT.test(valueExtname) || Util.REG_IMAGE.test(valueExtname) || Util.REG_MEDIA.test(valueExtname)) { + const vpath = path.resolve(sourceFilePath, '..', value) + if (mediaFiles.indexOf(vpath) < 0) { + mediaFiles.push(vpath) + } + let sourceDirPath = sourceDir + if (NODE_MODULES_REG.test(vpath)) { + sourceDirPath = nodeModulesPath + } + astPath.replaceWith(t.stringLiteral(vpath.replace(sourceDirPath, '').replace(/\\/g, '/'))) + } else { + let vpath = Util.resolveScriptPath(path.resolve(sourceFilePath, '..', value)) + let outputVpath + if (NODE_MODULES_REG.test(vpath)) { + outputVpath = vpath.replace(nodeModulesPath, npmOutputDir) + } else { + outputVpath = vpath.replace(sourceDir, outputDir) + } + let relativePath = path.relative(filePath, outputVpath) + if (vpath) { + if (!fs.existsSync(vpath)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '引用文件', `文件 ${sourceFilePath} 中引用 ${value} 不存在!`) + } else { + if (fs.lstatSync(vpath).isDirectory()) { + if (fs.existsSync(path.join(vpath, 'index.js'))) { + vpath = path.join(vpath, 'index.js') + relativePath = path.join(relativePath, 'index.js') + } else { + Util.printLog(Util.pocessTypeEnum.ERROR, '引用目录', `文件 ${sourceFilePath} 中引用了目录 ${value}!`) + return + } + } + if (scriptFiles.indexOf(vpath) < 0) { + scriptFiles.push(vpath) + } + relativePath = Util.promoteRelativePath(relativePath) + relativePath = relativePath.replace(path.extname(relativePath), '.js') + args[0].value = relativePath + } + } + } + } + } + } + } + }) + const node = astPath.node + const exportVariableName = exportTaroReduxConnected || componentClassName + if (needExportDefault) { + //@fix 注释掉用来解决小程序报错 + //const exportDefault = template(`export default ${exportVariableName}`, babylonConfig)() + //node.body.push(exportDefault) + } + const taroMiniAppFrameworkPath = !npmSkip ? getExactedNpmFilePath(taroMiniAppFramework, filePath) : taroMiniAppFramework + switch (type) { + case PARSE_AST_TYPE.ENTRY: + const pxTransformConfig = { + designWidth: projectConfig.designWidth || 750 + } + if (projectConfig.hasOwnProperty(DEVICE_RATIO)) { + pxTransformConfig[DEVICE_RATIO] = projectConfig.deviceRatio + } + //@fix 注释掉用来解决小程序报错 + node.body[node.body.length-2].expression.callee.name = 'global.Omi.defineApp' + //node.body.push(template(`App(require('${taroMiniAppFrameworkPath}').default.createApp(${exportVariableName}))`, babylonConfig)()) + //node.body.push(template(`Taro.initPxTransform(${JSON.stringify(pxTransformConfig)})`, babylonConfig)()) + //@fix Please do not call Page constructor in files that not listed in "pages" section of app.json or plugin.json + node.body.forEach((item, index) => { + if (item.type === 'ImportDeclaration' && item.source.value.indexOf('./pages/') === 0 && node.body[index].specifiers.length === 0) { + node.body[index] = null + } + }) + break + case PARSE_AST_TYPE.PAGE: + if (buildAdapter === Util.BUILD_TYPES.WEAPP) { + //@fix 注释掉用来解决小程序报错 + const arr = sourceFilePath.split( isWindows ? '\\' : '/') + const path = arr[arr.length - 3] + '/' + arr[arr.length - 2] + '/' + arr[arr.length-1].split('.')[0] + const obj = JSON.parse(JSON.stringify(node.body[node.body.length-1].expression.arguments[0])) + obj.value = path + //给 define 增加第三个参数 + node.body[node.body.length-1].expression.arguments.push(obj) + node.body[node.body.length-1].expression.callee.name = 'global.Omi.definePage' + node.body.push(template(`global.create.Page(global.getOptions('${path}'))`, babylonConfig)()) + //node.body.push(template(`Component(require('${taroMiniAppFrameworkPath}').default.createComponent(${exportVariableName}, true))`, babylonConfig)()) + + node.body.forEach((item, index) => { + if (item.type === 'ImportDeclaration') { + const v = node.body[index].source.value + if (v.indexOf('components/') !== -1 && node.body[index].specifiers.length === 0) { + node.body[index] = null + } + } + }) + + } else { + node.body.push(template(`Page(require('${taroMiniAppFrameworkPath}').default.createComponent(${exportVariableName}, true))`, babylonConfig)()) + } + break + case PARSE_AST_TYPE.COMPONENT: + + node.body.forEach((item, index) => { + if (item.type === 'ImportDeclaration') { + const v = node.body[index].source.value + if (v.indexOf('libs/taro/') === -1 && v.indexOf('libs/omip/') === -1 && node.body[index].specifiers.length === 0) { + node.body[index] = null + } + } + }) + + //@fix 注释掉用来解决小程序报错 + //node.body.push(template(`Component(require('${taroMiniAppFrameworkPath}').default.createComponent(${exportVariableName}))`, babylonConfig)()) + break + default: + break + } + } + } + }) + return { + code: generate(ast).code, + styleFiles, + scriptFiles, + jsonFiles, + configObj, + mediaFiles, + componentClassName + } +} + +function parseComponentExportAst (ast, componentName, componentPath, componentType) { + let componentRealPath = null + let importExportName + ast = babel.transformFromAst(ast, '', { + plugins: [ + [require('babel-plugin-transform-define').default, constantsReplaceList] + ] + }).ast + traverse(ast, { + ExportNamedDeclaration (astPath) { + const node = astPath.node + const specifiers = node.specifiers + const source = node.source + if (source && source.type === 'StringLiteral') { + specifiers.forEach(specifier => { + const exported = specifier.exported + if (_.kebabCase(exported.name) === componentName) { + componentRealPath = Util.resolveScriptPath(path.resolve(path.dirname(componentPath), source.value)) + } + }) + } else { + specifiers.forEach(specifier => { + const exported = specifier.exported + if (_.kebabCase(exported.name) === componentName) { + importExportName = exported.name + } + }) + } + }, + + ExportDefaultDeclaration (astPath) { + const node = astPath.node + const declaration = node.declaration + if (componentType === 'default') { + importExportName = declaration.name + } + }, + + CallExpression (astPath) { + if (astPath.get('callee').isIdentifier({ name: 'require' })) { + const arg = astPath.get('arguments')[0] + if (t.isStringLiteral(arg.node)) { + componentRealPath = Util.resolveScriptPath(path.resolve(path.dirname(componentPath), arg.node.value)) + } + } + }, + + Program: { + exit (astPath) { + astPath.traverse({ + ImportDeclaration (astPath) { + const node = astPath.node + const specifiers = node.specifiers + const source = node.source + if (importExportName) { + specifiers.forEach(specifier => { + const local = specifier.local + if (local.name === importExportName) { + componentRealPath = Util.resolveScriptPath(path.resolve(path.dirname(componentPath), source.value)) + } + }) + } + } + }) + } + } + }) + return componentRealPath +} + +function isFileToBeTaroComponent (code, sourcePath, outputPath) { + const transformResult = wxTransformer({ + code, + sourcePath: sourcePath, + outputPath: outputPath, + isNormal: true, + isTyped: Util.REG_TYPESCRIPT.test(sourcePath), + adapter: buildAdapter, + env: constantsReplaceList + }) + const { ast } = transformResult + let isTaroComponent = false + + traverse(ast, { + ClassDeclaration (astPath) { + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: 'render' })) { + astPath.traverse({ + JSXElement () { + isTaroComponent = true + } + }) + } + } + }) + }, + + ClassExpression (astPath) { + astPath.traverse({ + ClassMethod (astPath) { + if (astPath.get('key').isIdentifier({ name: 'render' })) { + astPath.traverse({ + JSXElement () { + isTaroComponent = true + } + }) + } + } + }) + } + }) + + return { + isTaroComponent, + transformResult + } +} + +function isFileToBePage (filePath) { + let isPage = false + const extname = path.extname(filePath) + const pages = appConfig.pages || [] + const filePathWithoutExt = filePath.replace(extname, '') + pages.forEach(page => { + if (filePathWithoutExt === path.join(sourceDir, page)) { + isPage = true + } + }) + return isPage && Util.REG_SCRIPTS.test(extname) +} + +function copyFilesFromSrcToOutput (files) { + files.forEach(file => { + let outputFilePath + if (NODE_MODULES_REG.test(file)) { + outputFilePath = file.replace(nodeModulesPath, npmOutputDir) + } else { + outputFilePath = file.replace(sourceDir, outputDir) + } + if (isCopyingFiles[outputFilePath]) { + return + } + isCopyingFiles[outputFilePath] = true + let modifySrc = file.replace(appPath + path.sep, '') + modifySrc = modifySrc.split(path.sep).join('/') + let modifyOutput = outputFilePath.replace(appPath + path.sep, '') + modifyOutput = modifyOutput.split(path.sep).join('/') + Util.printLog(Util.pocessTypeEnum.COPY, '文件', modifyOutput) + if (!fs.existsSync(file)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '文件', `${modifySrc} 不存在`) + } else { + fs.ensureDir(path.dirname(outputFilePath)) + if (file === outputFilePath) { + return + } + fs.copySync(file, outputFilePath) + } + }) +} + +const babelConfig = _.mergeWith({}, defaultBabelConfig, pluginsConfig.babel, (objValue, srcValue) => { + if (Array.isArray(objValue)) { + return Array.from(new Set(srcValue.concat(objValue))) + } +}) + +const shouldTransformAgain = (function () { + const pluginsStr = JSON.stringify(babelConfig.plugins) + if (/transform-runtime/.test(pluginsStr)) { + return true + } + return false +})() + +async function compileScriptFile (content, sourceFilePath, outputFilePath, adapter) { + const compileScriptRes = await npmProcess.callPlugin('babel', content, sourceFilePath, babelConfig) + const code = compileScriptRes.code + if (!shouldTransformAgain) { + return code + } + const transformResult = wxTransformer({ + code, + sourcePath: sourceFilePath, + outputPath: outputFilePath, + isNormal: true, + isTyped: false, + adapter, + env: constantsReplaceList + }) + const res = parseAst(PARSE_AST_TYPE.NORMAL, transformResult.ast, [], sourceFilePath, outputFilePath) + return res.code +} + +async function checkCliAndFrameworkVersion () { + const frameworkName = `@tarojs/taro-${buildAdapter}` + const frameworkVersion = Util.getInstalledNpmPkgVersion(frameworkName, nodeModulesPath) + if (frameworkVersion) { + if (frameworkVersion !== Util.getPkgVersion()) { + Util.printLog(Util.pocessTypeEnum.ERROR, '版本问题', `Taro CLI 与本地安装的小程序框架 ${frameworkName} 版本不一致,请确保一致`) + console.log(`Taro CLI: ${Util.getPkgVersion()}`) + console.log(`${frameworkName}: ${frameworkVersion}`) + process.exit(1) + } + } else { + Util.printLog(Util.pocessTypeEnum.WARNING, '依赖安装', chalk.red(`项目依赖 ${frameworkName} 未安装,或安装有误!`)) + } +} + +function buildProjectConfig () { + let projectConfigFileName = `project.${buildAdapter}.json` + if (buildAdapter === Util.BUILD_TYPES.WEAPP) { + projectConfigFileName = 'project.config.json' + } + let projectConfigPath = path.join(appPath, projectConfigFileName) + + if (!fs.existsSync(projectConfigPath)) { + projectConfigPath = path.join(sourceDir, projectConfigFileName) + if (!fs.existsSync(projectConfigPath)) return + } + + const origProjectConfig = fs.readJSONSync(projectConfigPath) + if (buildAdapter === Util.BUILD_TYPES.TT) { + projectConfigFileName = 'project.config.json' + } + fs.ensureDirSync(outputDir) + //@fix + // fs.writeFileSync( + // path.join(outputDir, projectConfigFileName), + // JSON.stringify(Object.assign({}, origProjectConfig, { miniprogramRoot: './' }), null, 2) + // ) + fs.writeFileSync( + path.join(path.resolve(outputDir, '..'), projectConfigFileName), + JSON.stringify(Object.assign({}, origProjectConfig), null, 2) + ) + Util.printLog(Util.pocessTypeEnum.GENERATE, '工具配置', `${outputDirName}/${projectConfigFileName}`) +} + +async function buildFrameworkInfo () { + // 百度小程序编译出 .frameworkinfo 文件 + if (buildAdapter === Util.BUILD_TYPES.SWAN) { + const frameworkInfoFileName = '.frameworkinfo' + const frameworkName = `@tarojs/taro-${buildAdapter}` + const frameworkVersion = Util.getInstalledNpmPkgVersion(frameworkName, nodeModulesPath) + if (frameworkVersion) { + const frameworkinfo = { + toolName: 'Taro', + toolCliVersion: Util.getPkgVersion(), + toolFrameworkVersion: frameworkVersion, + createTime: new Date(projectConfig.date).getTime() + } + fs.writeFileSync( + path.join(outputDir, frameworkInfoFileName), + JSON.stringify(frameworkinfo, null, 2) + ) + Util.printLog(Util.pocessTypeEnum.GENERATE, '框架信息', `${outputDirName}/${frameworkInfoFileName}`) + } else { + Util.printLog(Util.pocessTypeEnum.WARNING, '依赖安装', chalk.red(`项目依赖 ${frameworkName} 未安装,或安装有误!`)) + } + } +} + +function buildWorkers (worker) { + Util.printLog(Util.pocessTypeEnum.COMPILE, 'Workers', '编译 worker 相关文件') + const workerDir = path.join(sourceDir, worker) + function fileRecursiveSearch (fileDir) { + fs.readdir(fileDir, (err, files) => { + if (err) { + console.warn(err) + } else { + files.forEach(filename => { + const filePath = path.join(fileDir, filename) + fs.stat(filePath, (err, stats) => { + if (err) { + console.warn(err) + } else { + const isFile = stats.isFile() + const isDir = stats.isDirectory() + if (isFile) { + if (Util.REG_SCRIPTS.test(filePath)) { + compileDepScripts([filePath]) + } else { + copyFilesFromSrcToOutput([filePath]) + } + } else if (isDir) { + fileRecursiveSearch(filePath) + } + } + }) + }) + } + }) + } + fileRecursiveSearch(workerDir) +} + +async function buildCustomTabbar () { + const customTabbarPath = path.join(sourceDir, 'custom-tab-bar') + const customTabbarJSPath = Util.resolveScriptPath(customTabbarPath) + await buildSingleComponent({ + path: customTabbarJSPath, + name: 'custom-tab-bar' + }) +} + +async function buildEntry () { + Util.printLog(Util.pocessTypeEnum.COMPILE, '入口文件', `${sourceDirName}/${entryFileName}`) + const entryFileCode = fs.readFileSync(entryFilePath).toString() + try { + const transformResult = wxTransformer({ + code: entryFileCode, + sourcePath: entryFilePath, + outputPath: outputEntryFilePath, + isApp: true, + isTyped: Util.REG_TYPESCRIPT.test(entryFilePath), + adapter: buildAdapter, + env: constantsReplaceList + }) + // app.js的template忽略 + const res = parseAst(PARSE_AST_TYPE.ENTRY, transformResult.ast, [], entryFilePath, outputEntryFilePath) + let resCode = res.code + resCode = await compileScriptFile(resCode, entryFilePath, outputEntryFilePath, buildAdapter) + if (isProduction) { + const uglifyPluginConfig = pluginsConfig.uglify || { enable: true } + if (uglifyPluginConfig.enable) { + const uglifyConfig = Object.assign(defaultUglifyConfig, uglifyPluginConfig.config || {}) + const uglifyResult = npmProcess.callPluginSync('uglifyjs', resCode, entryFilePath, uglifyConfig) + if (uglifyResult.error) { + Util.printLog(Util.pocessTypeEnum.ERROR, '压缩错误', `文件${entryFilePath}`) + console.log(uglifyResult.error) + } else { + resCode = uglifyResult.code + } + } + } + if (appOutput) { + fs.writeFileSync(path.join(outputDir, 'app.json'), JSON.stringify(res.configObj, null, 2)) + Util.printLog(Util.pocessTypeEnum.GENERATE, '入口配置', `${outputDirName}/app.json`) + fs.writeFileSync(path.join(outputDir, 'app.js'), resCode) + Util.printLog(Util.pocessTypeEnum.GENERATE, '入口文件', `${outputDirName}/app.js`) + } + if (res.configObj.workers) { + buildWorkers(res.configObj.workers) + } + if (res.configObj.tabBar && res.configObj.tabBar.custom) { + await buildCustomTabbar() + } + const fileDep = dependencyTree[entryFilePath] || {} + // 编译依赖的脚本文件 + if (Util.isDifferentArray(fileDep['script'], res.scriptFiles)) { + compileDepScripts(res.scriptFiles) + } + // 编译样式文件 + if (Util.isDifferentArray(fileDep['style'], res.styleFiles) && appOutput) { + await compileDepStyles(path.join(outputDir, `app${outputFilesTypes.STYLE}`), res.styleFiles, false) + Util.printLog(Util.pocessTypeEnum.GENERATE, '入口样式', `${outputDirName}/app${outputFilesTypes.STYLE}`) + } + // 拷贝依赖文件 + if (Util.isDifferentArray(fileDep['json'], res.jsonFiles)) { + copyFilesFromSrcToOutput(res.jsonFiles) + } + + // 处理res.configObj 中的tabBar配置 + const tabBar = res.configObj.tabBar + if (tabBar && typeof tabBar === 'object' && !Util.isEmptyObject(tabBar)) { + const { + list: listConfig, + iconPath: pathConfig, + selectedIconPath: selectedPathConfig + } = Util.CONFIG_MAP[buildAdapter] + const list = tabBar[listConfig] || [] + let tabBarIcons = [] + list.forEach(item => { + item[pathConfig] && tabBarIcons.push(item[pathConfig]) + item[selectedPathConfig] && tabBarIcons.push(item[selectedPathConfig]) + }) + tabBarIcons = tabBarIcons.map(item => path.resolve(sourceDir, item)) + if (tabBarIcons && tabBarIcons.length) { + res.mediaFiles = res.mediaFiles.concat(tabBarIcons) + } + } + if (Util.isDifferentArray(fileDep['media'], res.mediaFiles)) { + copyFilesFromSrcToOutput(res.mediaFiles) + } + fileDep['style'] = res.styleFiles + fileDep['script'] = res.scriptFiles + fileDep['json'] = res.jsonFiles + fileDep['media'] = res.mediaFiles + dependencyTree[entryFilePath] = fileDep + return res.configObj + } catch (err) { + console.log(err) + } +} + +async function buildPages () { + Util.printLog(Util.pocessTypeEnum.COMPILE, '所有页面') + // 支持分包,解析子包页面 + const pages = appConfig.pages || [] + const subPackages = appConfig.subPackages || appConfig.subpackages + if (subPackages && subPackages.length) { + subPackages.forEach(item => { + if (item.pages && item.pages.length) { + const root = item.root + item.pages.forEach(page => { + let pagePath = `${root}/${page}` + pagePath = pagePath.replace(/\/{2,}/g, '/') + if (pages.indexOf(pagePath) < 0) { + pages.push(pagePath) + } + }) + } + }) + } + const pagesPromises = pages.map(async page => { + return buildSinglePage(page) + }) + await Promise.all(pagesPromises) +} + +function processNativeWxml (componentWXMLPath, componentWXMLContent, outputComponentWXMLPath) { + let wxmlContent + let needCopy = true + if (componentWXMLPath && fs.existsSync(componentWXMLPath)) { + wxmlContent = fs.readFileSync(componentWXMLPath).toString() + } else { + needCopy = false + wxmlContent = componentWXMLContent + } + const importWxmlPathList = [] + let regResult + while ((regResult = Util.REG_WXML_IMPORT.exec(wxmlContent)) != null) { + importWxmlPathList.push(regResult[2] || regResult[3]) + } + if (importWxmlPathList.length) { + importWxmlPathList.forEach(item => { + const itemPath = path.resolve(componentWXMLPath, '..', item) + if (fs.existsSync(itemPath)) { + const outputItemPath = itemPath.replace(sourceDir, outputDir) + processNativeWxml(itemPath, null, outputItemPath) + } + }) + } + if (componentWXMLPath === outputComponentWXMLPath || !needCopy) { + return + } + copyFileSync(componentWXMLPath, outputComponentWXMLPath) +} + +function transfromNativeComponents (configFile, componentConfig) { + const usingComponents = componentConfig.usingComponents + if (usingComponents && !Util.isEmptyObject(usingComponents)) { + Object.keys(usingComponents).map(async item => { + let componentPath = usingComponents[item] + + if (Util.isAliasPath(componentPath, pathAlias)) { + componentPath = Util.replaceAliasPath(configFile, componentPath, pathAlias) + usingComponents[item] = componentPath + } + + if (/^plugin:\/\//.test(componentPath)) { + // 小程序 plugin + Util.printLog(Util.pocessTypeEnum.REFERENCE, '插件引用', `使用了插件 ${chalk.bold(componentPath)}`) + return + } + let componentJSPath = Util.resolveScriptPath(path.resolve(path.dirname(configFile), componentPath)) + if (!fs.existsSync(componentJSPath)) { + componentJSPath = Util.resolveScriptPath(path.join(sourceDir, componentPath)) + } + const componentJSONPath = componentJSPath.replace(path.extname(componentJSPath), outputFilesTypes.CONFIG) + const componentWXMLPath = componentJSPath.replace(path.extname(componentJSPath), outputFilesTypes.TEMPL) + const componentWXSSPath = componentJSPath.replace(path.extname(componentJSPath), outputFilesTypes.STYLE) + const outputComponentJSPath = componentJSPath.replace(sourceDir, outputDir).replace(path.extname(componentJSPath), outputFilesTypes.SCRIPT) + if (fs.existsSync(componentJSPath)) { + const componentJSContent = fs.readFileSync(componentJSPath).toString() + if (componentJSContent.indexOf(taroJsFramework) >= 0 && !fs.existsSync(componentWXMLPath)) { + const buildDepComponentsRes = await buildDepComponents([componentJSPath]) + return buildDepComponentsRes + } + compileDepScripts([componentJSPath]) + } else { + return Util.printLog(Util.pocessTypeEnum.ERROR, '编译错误', `原生组件文件 ${componentJSPath} 不存在!`) + } + if (fs.existsSync(componentWXMLPath)) { + const outputComponentWXMLPath = outputComponentJSPath.replace(path.extname(outputComponentJSPath), outputFilesTypes.TEMPL) + processNativeWxml(componentWXMLPath, null, outputComponentWXMLPath) + } + if (fs.existsSync(componentWXSSPath)) { + const outputComponentWXSSPath = outputComponentJSPath.replace(path.extname(outputComponentJSPath), outputFilesTypes.STYLE) + await compileDepStyles(outputComponentWXSSPath, [componentWXSSPath], true) + } + if (fs.existsSync(componentJSONPath)) { + const componentJSON = require(componentJSONPath) + const outputComponentJSONPath = outputComponentJSPath.replace(path.extname(outputComponentJSPath), outputFilesTypes.CONFIG) + copyFileSync(componentJSONPath, outputComponentJSONPath) + + // 解决组件循环依赖不断编译爆栈的问题 + if (componentJSON && componentJSON.usingComponents) { + Object.keys(componentJSON.usingComponents).forEach(key => { + if (key === item) { + delete componentJSON.usingComponents[key] + } + }) + } + + transfromNativeComponents(componentJSONPath, componentJSON) + } + }) + } +} + +// 小程序页面编译 +async function buildSinglePage (page) { + Util.printLog(Util.pocessTypeEnum.COMPILE, '页面文件', `${sourceDirName}/${page}`) + const pagePath = path.join(sourceDir, `${page}`) + let pageJs = Util.resolveScriptPath(pagePath) + if (!fs.existsSync(pageJs)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '页面文件', `${sourceDirName}/${page} 不存在!`) + return + } + const pageJsContent = fs.readFileSync(pageJs).toString() + const outputPageJSPath = pageJs.replace(sourceDir, outputDir).replace(path.extname(pageJs), outputFilesTypes.SCRIPT) + const outputPagePath = path.dirname(outputPageJSPath) + const outputPageJSONPath = outputPageJSPath.replace(path.extname(outputPageJSPath), outputFilesTypes.CONFIG) + const outputPageWXMLPath = outputPageJSPath.replace(path.extname(outputPageJSPath), outputFilesTypes.TEMPL) + const outputPageWXSSPath = outputPageJSPath.replace(path.extname(outputPageJSPath), outputFilesTypes.STYLE) + // 判断是不是小程序原生代码页面 + const pageWXMLPath = pageJs.replace(path.extname(pageJs), outputFilesTypes.TEMPL) + if (fs.existsSync(pageWXMLPath) && pageJsContent.indexOf(taroJsFramework) < 0) { + const pageJSONPath = pageJs.replace(path.extname(pageJs), outputFilesTypes.CONFIG) + const pageWXSSPath = pageJs.replace(path.extname(pageJs), outputFilesTypes.STYLE) + if (fs.existsSync(pageJSONPath)) { + const pageJSON = require(pageJSONPath) + copyFileSync(pageJSONPath, outputPageJSONPath) + transfromNativeComponents(pageJSONPath, pageJSON) + } + compileDepScripts([pageJs]) + copyFileSync(pageWXMLPath, outputPageWXMLPath) + if (fs.existsSync(pageWXSSPath)) { + await compileDepStyles(outputPageWXSSPath, [pageWXSSPath], false) + } + return + } + try { + const transformResult = wxTransformer({ + code: pageJsContent, + sourcePath: pageJs, + outputPath: outputPageJSPath, + isRoot: true, + isTyped: Util.REG_TYPESCRIPT.test(pageJs), + adapter: buildAdapter, + env: constantsReplaceList + }) + const pageDepComponents = transformResult.components + const compressTemplate = useCompileConf.compressTemplate + const pageWXMLContent = (isProduction && compressTemplate) ? transformResult.compressedTemplate : transformResult.template + const res = parseAst(PARSE_AST_TYPE.PAGE, transformResult.ast, pageDepComponents, pageJs, outputPageJSPath) + let resCode = res.code + resCode = await compileScriptFile(resCode, pageJs, outputPageJSPath, buildAdapter) + if (isProduction) { + const uglifyPluginConfig = pluginsConfig.uglify || { enable: true } + if (uglifyPluginConfig.enable) { + const uglifyConfig = Object.assign(defaultUglifyConfig, uglifyPluginConfig.config || {}) + const uglifyResult = npmProcess.callPluginSync('uglifyjs', resCode, outputPageJSPath, uglifyConfig) + if (uglifyResult.error) { + Util.printLog(Util.pocessTypeEnum.ERROR, '压缩错误', `文件${pageJs}`) + console.log(uglifyResult.error) + } else { + resCode = uglifyResult.code + } + } + } + fs.ensureDirSync(outputPagePath) + const { usingComponents = {} } = res.configObj + if (usingComponents && !Util.isEmptyObject(usingComponents)) { + const keys = Object.keys(usingComponents) + keys.forEach(item => { + pageDepComponents.forEach(component => { + if (_.camelCase(item) === _.camelCase(component.name)) { + delete usingComponents[item] + } + }) + }) + transfromNativeComponents(outputPageJSONPath.replace(outputDir, sourceDir), res.configObj) + } + const fileDep = dependencyTree[pageJs] || {} + // 编译依赖的组件文件 + let buildDepComponentsResult = [] + let realComponentsPathList = [] + if (pageDepComponents.length) { + realComponentsPathList = getRealComponentsPathList(pageJs, pageDepComponents) + res.scriptFiles = res.scriptFiles.map(item => { + for (let i = 0; i < realComponentsPathList.length; i++) { + const componentObj = realComponentsPathList[i] + const componentPath = componentObj.path + if (item === componentPath) { + return null + } + } + return item + }).filter(item => item) + buildDepComponentsResult = await buildDepComponents(realComponentsPathList) + } + if (!Util.isEmptyObject(componentExportsMap) && realComponentsPathList.length) { + const mapKeys = Object.keys(componentExportsMap) + realComponentsPathList.forEach(component => { + if (mapKeys.indexOf(component.path) >= 0) { + const componentMap = componentExportsMap[component.path] + componentMap.forEach(component => { + pageDepComponents.forEach(depComponent => { + if (depComponent.name === component.name) { + let componentPath = component.path + let realPath + if (NODE_MODULES_REG.test(componentPath)) { + componentPath = componentPath.replace(nodeModulesPath, npmOutputDir) + realPath = Util.promoteRelativePath(path.relative(outputPageJSPath, componentPath)) + } else { + realPath = Util.promoteRelativePath(path.relative(pageJs, componentPath)) + } + depComponent.path = realPath.replace(path.extname(realPath), '') + } + }) + }) + } + }) + } + fs.writeFileSync(outputPageJSONPath, JSON.stringify(_.merge({}, buildUsingComponents(pageJs, pageDepComponents), res.configObj), null, 2)) + Util.printLog(Util.pocessTypeEnum.GENERATE, '页面配置', `${outputDirName}/${page}${outputFilesTypes.CONFIG}`) + fs.writeFileSync(outputPageJSPath, resCode) + Util.printLog(Util.pocessTypeEnum.GENERATE, '页面逻辑', `${outputDirName}/${page}${outputFilesTypes.SCRIPT}`) + fs.writeFileSync(outputPageWXMLPath, pageWXMLContent) + processNativeWxml(outputPageWXMLPath.replace(outputDir, sourceDir), pageWXMLContent, outputPageWXMLPath) + Util.printLog(Util.pocessTypeEnum.GENERATE, '页面模板', `${outputDirName}/${page}${outputFilesTypes.TEMPL}`) + // 编译依赖的脚本文件 + if (Util.isDifferentArray(fileDep['script'], res.scriptFiles)) { + compileDepScripts(res.scriptFiles) + } + // 编译样式文件 + if (Util.isDifferentArray(fileDep['style'], res.styleFiles) || Util.isDifferentArray(depComponents[pageJs], pageDepComponents)) { + Util.printLog(Util.pocessTypeEnum.GENERATE, '页面样式', `${outputDirName}/${page}${outputFilesTypes.STYLE}`) + const depStyleList = getDepStyleList(outputPageWXSSPath, buildDepComponentsResult) + wxssDepTree[outputPageWXSSPath] = depStyleList + await compileDepStyles(outputPageWXSSPath, res.styleFiles, false) + } + // 拷贝依赖文件 + if (Util.isDifferentArray(fileDep['json'], res.jsonFiles)) { + copyFilesFromSrcToOutput(res.jsonFiles) + } + if (Util.isDifferentArray(fileDep['media'], res.mediaFiles)) { + copyFilesFromSrcToOutput(res.mediaFiles) + } + depComponents[pageJs] = pageDepComponents + fileDep['style'] = res.styleFiles + fileDep['script'] = res.scriptFiles + fileDep['json'] = res.jsonFiles + fileDep['media'] = res.mediaFiles + dependencyTree[pageJs] = fileDep + } catch (err) { + Util.printLog(Util.pocessTypeEnum.ERROR, '页面编译', `页面${pagePath}编译失败!`) + console.log(err) + } +} + +/** + * css module processor + * @param styleObj { css: string, filePath: '' } + * @returns postcss.process() + */ +function processStyleUseCssModule (styleObj) { + const useModuleConf = weappConf.module || {} + const customPostcssConf = useModuleConf.postcss || {} + const customCssModulesConf = Object.assign({ + enable: false, + config: { + generateScopedName: '[name]__[local]___[hash:base64:5]', + namingPattern: 'global' + } + }, customPostcssConf.cssModules || {}) + if (!customCssModulesConf.enable) { + return styleObj + } + const namingPattern = customCssModulesConf.config.namingPattern + if (namingPattern === 'module') { + // 只对 xxx.module.[css|scss|less|styl] 等样式文件做处理 + const DO_USE_CSS_MODULE_REGEX = /^(.*\.module).*\.(css|scss|less|styl)$/ + if (!DO_USE_CSS_MODULE_REGEX.test(styleObj.filePath)) return styleObj + } else { + // 对 xxx.global.[css|scss|less|styl] 等样式文件不做处理 + const DO_NOT_USE_CSS_MODULE_REGEX = /^(.*\.global).*\.(css|scss|less|styl)$/ + if (DO_NOT_USE_CSS_MODULE_REGEX.test(styleObj.filePath)) return styleObj + } + const generateScopedName = customCssModulesConf.config.generateScopedName + const context = process.cwd() + let scopedName + if (generateScopedName) { + scopedName = genericNames(generateScopedName, { context }) + } else { + scopedName = (local, filename) => Scope.generateScopedName(local, path.relative(context, filename)) + } + const postcssPlugins = [ + Values, + LocalByDefault, + ExtractImports, + new Scope({ generateScopedName: scopedName }), + new ResolveImports({ resolve: Object.assign({}, { extensions: Util.CSS_EXT }) }) + ] + const runner = postcss(postcssPlugins) + const result = runner.process(styleObj.css, Object.assign({}, { from: styleObj.filePath })) + return result +} + +async function processStyleWithPostCSS (styleObj) { + const useModuleConf = weappConf.module || {} + const customPostcssConf = useModuleConf.postcss || {} + const customCssModulesConf = Object.assign({ + enable: false, + config: { + generateScopedName: '[name]__[local]___[hash:base64:5]' + } + }, customPostcssConf.cssModules || {}) + const customPxtransformConf = Object.assign({ + enable: true, + config: {} + }, customPostcssConf.pxtransform || {}) + const customUrlConf = Object.assign({ + enable: true, + config: { + limit: 10240 + } + }, customPostcssConf.url || {}) + const customAutoprefixerConf = Object.assign({ + enable: true, + config: { + browsers: browserList + } + }, customPostcssConf.autoprefixer || {}) + const postcssPxtransformOption = { + designWidth: projectConfig.designWidth || 750, + platform: 'weapp' + } + + if (projectConfig.hasOwnProperty(DEVICE_RATIO)) { + postcssPxtransformOption[DEVICE_RATIO] = projectConfig.deviceRatio + } + const cssUrlConf = Object.assign({ limit: 10240 }, customUrlConf) + const maxSize = Math.round((customUrlConf.config.limit || cssUrlConf.limit) / 1024) + const postcssPxtransformConf = Object.assign({}, postcssPxtransformOption, customPxtransformConf, customPxtransformConf.config) + const processors = [] + if (customAutoprefixerConf.enable) { + processors.push(autoprefixer(customAutoprefixerConf.config)) + } + if (customPxtransformConf.enable) { + processors.push(pxtransform(postcssPxtransformConf)) + } + if (cssUrlConf.enable) { + processors.push(cssUrlParse({ + url: 'inline', + maxSize, + encodeType: 'base64' + })) + } + + const defaultPostCSSPluginNames = ['autoprefixer', 'pxtransform', 'url', 'cssModules'] + Object.keys(customPostcssConf).forEach(pluginName => { + if (defaultPostCSSPluginNames.indexOf(pluginName) < 0) { + const pluginConf = customPostcssConf[pluginName] + if (pluginConf && pluginConf.enable) { + if (!Util.isNpmPkg(pluginName)) { // local plugin + pluginName = path.join(appPath, pluginName) + } + processors.push(require(resolveNpmPkgMainPath(pluginName, isProduction, weappNpmConfig, buildAdapter))(pluginConf.config || {})) + } + } + }) + let css = styleObj.css + if (customCssModulesConf.enable) { + css = processStyleUseCssModule(styleObj).css + } + const postcssResult = await postcss(processors).process(css, { + from: styleObj.filePath + }) + return postcssResult.css +} + +function compileImportStyles (filePath, importStyles) { + if (importStyles.length) { + importStyles.forEach(async importItem => { + const importFilePath = path.resolve(filePath, '..', importItem) + if (fs.existsSync(importFilePath)) { + await compileDepStyles(importFilePath.replace(sourceDir, outputDir), [importFilePath]) + } + }) + } +} + +function compileDepStyles (outputFilePath, styleFiles, isComponent) { + if (isBuildingStyles[outputFilePath]) { + return Promise.resolve({}) + } + isBuildingStyles[outputFilePath] = true + return Promise.all(styleFiles.map(async p => { + const filePath = path.join(p) + const fileExt = path.extname(filePath) + const pluginName = Util.FILE_PROCESSOR_MAP[fileExt] + const fileContent = fs.readFileSync(filePath).toString() + const cssImportsRes = Util.processStyleImports(fileContent, buildAdapter, (str, stylePath) => { + if (stylePath.indexOf('~') === 0) { + let newStylePath = stylePath + newStylePath = stylePath.replace('~', '') + const npmInfo = resolveNpmFilesPath(newStylePath, isProduction, weappNpmConfig, buildAdapter, appPath, compileInclude) + const importRelativePath = Util.promoteRelativePath(path.relative(filePath, npmInfo.main)) + return str.replace(stylePath, importRelativePath) + } + return str + }) + compileImportStyles(filePath, cssImportsRes.imports) + if (pluginName) { + return npmProcess.callPlugin(pluginName, cssImportsRes.content, filePath, pluginsConfig[pluginName] || {}) + .then(res => ({ + css: cssImportsRes.style.join('\n') + '\n' + res.css, + filePath + })) + } + return new Promise(resolve => { + resolve({ + css: cssImportsRes.style.join('\n') + '\n' + cssImportsRes.content, + filePath + }) + }) + })).then(async resList => { + Promise.all(resList.map(res => processStyleWithPostCSS(res))) + .then(cssList => { + let resContent = cssList.map(res => res).join('\n') + if (isProduction) { + const cssoPuginConfig = pluginsConfig.csso || { enable: true } + if (cssoPuginConfig.enable) { + const cssoConfig = cssoPuginConfig.config || {} + const cssoResult = npmProcess.callPluginSync('csso', resContent, outputFilePath, cssoConfig) + resContent = cssoResult.css + } + } + fs.ensureDirSync(path.dirname(outputFilePath)) + fs.writeFileSync(outputFilePath, resContent) + }) + }) +} + +function getRealComponentsPathList (filePath, components) { + return components.map(component => { + let componentPath = component.path + if (Util.isAliasPath(componentPath, pathAlias)) { + componentPath = Util.replaceAliasPath(filePath, componentPath, pathAlias) + } + if (Util.isNpmPkg(componentPath)) { + try { + componentPath = resolveNpmPkgMainPath(componentPath, isProduction, weappNpmConfig, buildAdapter) + } catch (err) { + console.log(err) + } + } else { + componentPath = path.resolve(path.dirname(filePath), componentPath) + componentPath = Util.resolveScriptPath(componentPath) + } + if (isFileToBePage(componentPath)) { + Util.printLog(Util.pocessTypeEnum.ERROR, '组件引用', `文件${component.path}已经在 app.js 中被指定为页面,不能再作为组件来引用!`) + } + return { + path: componentPath, + name: component.name, + type: component.type + } + }) +} + +function buildDepComponents (componentPathList, buildConfig) { + return Promise.all(componentPathList.map(componentObj => buildSingleComponent(componentObj, buildConfig))) +} + +function getDepStyleList (outputFilePath, buildDepComponentsResult) { + let depWXSSList = [] + if (buildDepComponentsResult.length) { + depWXSSList = buildDepComponentsResult.map(item => { + let wxss = item.wxss + wxss = wxss.replace(sourceDir, outputDir) + wxss = Util.promoteRelativePath(path.relative(outputFilePath, wxss)) + return wxss + }) + } + return depWXSSList +} + +function buildUsingComponents (filePath, components, isComponent) { + const usingComponents = Object.create(null) + for (const component of components) { + let componentPath = component.path + if (Util.isAliasPath(componentPath, pathAlias)) { + componentPath = Util.replaceAliasPath(filePath, componentPath, pathAlias) + } + componentPath = Util.resolveScriptPath(path.resolve(filePath, '..', componentPath)) + if (fs.existsSync(componentPath)) { + componentPath = Util.promoteRelativePath(path.relative(filePath, componentPath)) + } else { + componentPath = component.path + } + usingComponents[component.name] = componentPath.replace(path.extname(componentPath), '') + } + return Object.assign({}, isComponent ? { component: true } : { usingComponents: {} }, components.length ? { + usingComponents + } : {}) +} + +async function buildSingleComponent (componentObj, buildConfig = {}) { + if (hasBeenBuiltComponents.indexOf(componentObj.path) >= 0 && componentsBuildResult[componentObj.path]) { + return componentsBuildResult[componentObj.path] + } + componentsNamedMap[componentObj.path] = { + name: componentObj.name, + type: componentObj.type + } + const component = componentObj.path + if (!component) { + Util.printLog(Util.pocessTypeEnum.ERROR, '组件错误', `组件${_.upperFirst(_.camelCase(componentObj.name))}路径错误,请检查!(可能原因是导出的组件名不正确)`) + return { + js: null, + wxss: null, + wxml: null + } + } + let componentShowPath = component.replace(appPath + path.sep, '') + componentShowPath = componentShowPath.split(path.sep).join('/') + let isComponentFromNodeModules = false + let sourceDirPath = sourceDir + let buildOutputDir = outputDir + // 来自 node_modules 的组件 + if (NODE_MODULES_REG.test(componentShowPath)) { + isComponentFromNodeModules = true + sourceDirPath = nodeModulesPath + buildOutputDir = npmOutputDir + } + let outputComponentShowPath = componentShowPath.replace(isComponentFromNodeModules ? NODE_MODULES : sourceDirName, buildConfig.outputDirName || outputDirName) + outputComponentShowPath = outputComponentShowPath.replace(path.extname(outputComponentShowPath), '') + Util.printLog(Util.pocessTypeEnum.COMPILE, '组件文件', componentShowPath) + const componentContent = fs.readFileSync(component).toString() + const outputComponentJSPath = component.replace(sourceDirPath, buildConfig.outputDir || buildOutputDir).replace(path.extname(component), outputFilesTypes.SCRIPT) + const outputComponentWXMLPath = outputComponentJSPath.replace(path.extname(outputComponentJSPath), outputFilesTypes.TEMPL) + const outputComponentWXSSPath = outputComponentJSPath.replace(path.extname(outputComponentJSPath), outputFilesTypes.STYLE) + const outputComponentJSONPath = outputComponentJSPath.replace(path.extname(outputComponentJSPath), outputFilesTypes.CONFIG) + if (hasBeenBuiltComponents.indexOf(component) < 0) { + hasBeenBuiltComponents.push(component) + } + try { + let isTaroComponentRes = isFileToBeTaroComponent(componentContent, component, outputComponentJSPath) + if (!isTaroComponentRes.isTaroComponent) { + const transformResult = isTaroComponentRes.transformResult + const componentRealPath = parseComponentExportAst(transformResult.ast, componentObj.name, component, componentObj.type) + const realComponentObj = { + path: componentRealPath, + name: componentObj.name, + type: componentObj.type + } + let isInMap = false + if (notTaroComponents.indexOf(component) < 0) { + notTaroComponents.push(component) + } + if (!Util.isEmptyObject(componentExportsMap)) { + Object.keys(componentExportsMap).forEach(key => { + componentExportsMap[key].forEach(item => { + if (item.path === component) { + isInMap = true + item.path = componentRealPath + } + }) + }) + } + if (!isInMap) { + componentExportsMap[component] = componentExportsMap[component] || [] + componentExportsMap[component].push(realComponentObj) + } + return await buildSingleComponent(realComponentObj, buildConfig) + } + const transformResult = wxTransformer({ + code: componentContent, + sourcePath: component, + outputPath: outputComponentJSPath, + isRoot: false, + isTyped: Util.REG_TYPESCRIPT.test(component), + isNormal: false, + adapter: buildAdapter, + env: constantsReplaceList + }) + const compressTemplate = useCompileConf.compressTemplate + const componentWXMLContent = (isProduction && compressTemplate) ? transformResult.compressedTemplate : transformResult.template + const componentDepComponents = transformResult.components + const res = parseAst(PARSE_AST_TYPE.COMPONENT, transformResult.ast, componentDepComponents, component, outputComponentJSPath, buildConfig.npmSkip) + let resCode = res.code + resCode = await compileScriptFile(resCode, component, outputComponentJSPath, buildAdapter) + fs.ensureDirSync(path.dirname(outputComponentJSPath)) + if (isProduction) { + const uglifyPluginConfig = pluginsConfig.uglify || { enable: true } + if (uglifyPluginConfig.enable) { + const uglifyConfig = Object.assign(defaultUglifyConfig, uglifyPluginConfig.config || {}) + const uglifyResult = npmProcess.callPluginSync('uglifyjs', resCode, outputComponentJSPath, uglifyConfig) + if (uglifyResult.error) { + Util.printLog(Util.pocessTypeEnum.ERROR, '压缩错误', `文件${component}`) + console.log(uglifyResult.error) + } else { + resCode = uglifyResult.code + } + } + } + const { usingComponents = {} } = res.configObj + if (usingComponents && !Util.isEmptyObject(usingComponents)) { + const keys = Object.keys(usingComponents) + keys.forEach(item => { + componentDepComponents.forEach(component => { + if (_.camelCase(item) === _.camelCase(component.name)) { + delete usingComponents[item] + } + }) + }) + transfromNativeComponents(outputComponentJSONPath.replace(buildConfig.outputDir || buildOutputDir, sourceDirPath), res.configObj) + } + + const fileDep = dependencyTree[component] || {} + // 编译依赖的组件文件 + let buildDepComponentsResult = [] + let realComponentsPathList = [] + if (componentDepComponents.length) { + realComponentsPathList = getRealComponentsPathList(component, componentDepComponents) + res.scriptFiles = res.scriptFiles.map(item => { + for (let i = 0; i < realComponentsPathList.length; i++) { + const componentObj = realComponentsPathList[i] + const componentPath = componentObj.path + if (item === componentPath) { + return null + } + } + return item + }).filter(item => item) + realComponentsPathList = realComponentsPathList.filter(item => hasBeenBuiltComponents.indexOf(item.path) < 0 || notTaroComponents.indexOf(item.path) >= 0) + buildDepComponentsResult = await buildDepComponents(realComponentsPathList) + } + if (!Util.isEmptyObject(componentExportsMap) && realComponentsPathList.length) { + const mapKeys = Object.keys(componentExportsMap) + realComponentsPathList.forEach(componentObj => { + if (mapKeys.indexOf(componentObj.path) >= 0) { + const componentMap = componentExportsMap[componentObj.path] + componentMap.forEach(componentObj => { + componentDepComponents.forEach(depComponent => { + if (depComponent.name === componentObj.name) { + let componentPath = componentObj.path + let realPath + if (NODE_MODULES_REG.test(componentPath)) { + componentPath = componentPath.replace(nodeModulesPath, npmOutputDir) + realPath = Util.promoteRelativePath(path.relative(outputComponentJSPath, componentPath)) + } else { + realPath = Util.promoteRelativePath(path.relative(component, componentPath)) + } + depComponent.path = realPath.replace(path.extname(realPath), '') + } + }) + }) + } + }) + } + fs.writeFileSync(outputComponentJSONPath, JSON.stringify(_.merge({}, buildUsingComponents(component, componentDepComponents, true), res.configObj), null, 2)) + Util.printLog(Util.pocessTypeEnum.GENERATE, '组件配置', `${outputDirName}/${outputComponentShowPath}${outputFilesTypes.CONFIG}`) + fs.writeFileSync(outputComponentJSPath, resCode) + Util.printLog(Util.pocessTypeEnum.GENERATE, '组件逻辑', `${outputDirName}/${outputComponentShowPath}${outputFilesTypes.SCRIPT}`) + fs.writeFileSync(outputComponentWXMLPath, componentWXMLContent) + processNativeWxml(outputComponentWXMLPath.replace(outputDir, sourceDir), componentWXMLContent, outputComponentWXMLPath) + Util.printLog(Util.pocessTypeEnum.GENERATE, '组件模板', `${outputDirName}/${outputComponentShowPath}${outputFilesTypes.TEMPL}`) + // 编译依赖的脚本文件 + if (Util.isDifferentArray(fileDep['script'], res.scriptFiles)) { + compileDepScripts(res.scriptFiles) + } + // 编译样式文件 + if (Util.isDifferentArray(fileDep['style'], res.styleFiles) || Util.isDifferentArray(depComponents[component], componentDepComponents)) { + Util.printLog(Util.pocessTypeEnum.GENERATE, '组件样式', `${outputDirName}/${outputComponentShowPath}${outputFilesTypes.STYLE}`) + const depStyleList = getDepStyleList(outputComponentWXSSPath, buildDepComponentsResult) + wxssDepTree[outputComponentWXSSPath] = depStyleList + await compileDepStyles(outputComponentWXSSPath, res.styleFiles, true) + } + // 拷贝依赖文件 + if (Util.isDifferentArray(fileDep['json'], res.jsonFiles)) { + copyFilesFromSrcToOutput(res.jsonFiles) + } + if (Util.isDifferentArray(fileDep['media'], res.mediaFiles)) { + copyFilesFromSrcToOutput(res.mediaFiles) + } + fileDep['style'] = res.styleFiles + fileDep['script'] = res.scriptFiles + fileDep['json'] = res.jsonFiles + fileDep['media'] = res.mediaFiles + dependencyTree[component] = fileDep + depComponents[component] = componentDepComponents + componentsBuildResult[component] = { + js: outputComponentJSPath, + wxss: outputComponentWXSSPath, + wxml: outputComponentWXMLPath + } + return componentsBuildResult[component] + } catch (err) { + Util.printLog(Util.pocessTypeEnum.ERROR, '组件编译', `组件${componentShowPath}编译失败!`) + console.log(err) + } +} + +function compileDepScripts (scriptFiles) { + scriptFiles.forEach(async item => { + if (path.isAbsolute(item)) { + let outputItem + if (NODE_MODULES_REG.test(item)) { + outputItem = item.replace(nodeModulesPath, npmOutputDir).replace(path.extname(item), '.js') + } else { + outputItem = item.replace(path.join(sourceDir), path.join(outputDir)).replace(path.extname(item), '.js') + } + const useCompileConf = Object.assign({}, weappConf.compile) + const compileExclude = useCompileConf.exclude || [] + let isInCompileExclude = false + compileExclude.forEach(excludeItem => { + if (item.indexOf(path.join(appPath, excludeItem)) >= 0) { + isInCompileExclude = true + } + }) + if (isInCompileExclude) { + copyFileSync(item, outputItem) + return + } + if (!isBuildingScripts[outputItem]) { + isBuildingScripts[outputItem] = true + try { + let code = fs.readFileSync(item).toString() + if (path.extname(item) === '.md') { + code = `export default { md: \`${code.replace(/`/g, '\\`').replace(/\$/g, '\\$')}\` }` + } + const transformResult = wxTransformer({ + code, + sourcePath: item, + outputPath: outputItem, + isNormal: true, + isTyped: Util.REG_TYPESCRIPT.test(item), + adapter: buildAdapter, + env: constantsReplaceList + }) + const ast = transformResult.ast + const res = parseAst(PARSE_AST_TYPE.NORMAL, ast, [], item, outputItem) + const fileDep = dependencyTree[item] || {} + let resCode = res.code + resCode = await compileScriptFile(res.code, item, outputItem, buildAdapter) + fs.ensureDirSync(path.dirname(outputItem)) + if (isProduction) { + const uglifyPluginConfig = pluginsConfig.uglify || { enable: true } + if (uglifyPluginConfig.enable) { + const uglifyConfig = Object.assign(defaultUglifyConfig, uglifyPluginConfig.config || {}) + const uglifyResult = npmProcess.callPluginSync('uglifyjs', resCode, item, uglifyConfig) + if (uglifyResult.error) { + Util.printLog(Util.pocessTypeEnum.ERROR, '压缩错误', `文件${item}`) + console.log(uglifyResult.error) + } else { + resCode = uglifyResult.code + } + } + } + fs.writeFileSync(outputItem, resCode) + let modifyOutput = outputItem.replace(appPath + path.sep, '') + modifyOutput = modifyOutput.split(path.sep).join('/') + Util.printLog(Util.pocessTypeEnum.GENERATE, '依赖文件', modifyOutput) + // 编译依赖的脚本文件 + if (Util.isDifferentArray(fileDep['script'], res.scriptFiles)) { + compileDepScripts(res.scriptFiles) + } + // 拷贝依赖文件 + if (Util.isDifferentArray(fileDep['json'], res.jsonFiles)) { + copyFilesFromSrcToOutput(res.jsonFiles) + } + if (Util.isDifferentArray(fileDep['media'], res.mediaFiles)) { + copyFilesFromSrcToOutput(res.mediaFiles) + } + fileDep['script'] = res.scriptFiles + fileDep['json'] = res.jsonFiles + fileDep['media'] = res.mediaFiles + dependencyTree[item] = fileDep + } catch (err) { + Util.printLog(Util.pocessTypeEnum.ERROR, '编译失败', item.replace(appPath + path.sep, '')) + console.log(err) + } + } + } + }) +} + +function copyFileSync (from, to, options) { + const filename = path.basename(from) + if (fs.statSync(from).isFile() && !path.extname(to)) { + fs.ensureDir(to) + if (from === path.join(to, filename)) { + return + } + return fs.copySync(from, path.join(to, filename), options) + } + if (from === to) { + return + } + fs.ensureDir(path.dirname(to)) + return fs.copySync(from, to, options) +} + +const stat= fs.stat + +function copy(src,dst){ + //读取目录 + fs.readdir(src,function(err,paths){ + if(err){ + throw err; + } + paths.forEach(function(path){ + var _src=src+'/'+path; + var _dst=dst+'/'+path; + var readable; + var writable; + stat(_src,function(err,st){ + if(err){ + throw err; + } + + if(st.isFile()){ + readable=fs.createReadStream(_src);//创建读取流 + writable=fs.createWriteStream(_dst);//创建写入流 + readable.pipe(writable); + }else if(st.isDirectory()){ + exists(_src,_dst,copy); + } + }); + }); + }); +} + +function exists(src,dst,callback){ + //测试某个路径下文件是否存在 + fs.exists(dst,function(exists){ + if(exists){//不存在 + callback(src,dst); + }else{//存在 + fs.mkdir(dst,function(){//创建目录 + callback(src,dst) + }) + } + }) +} + +function copyFiles () { + const copyConfig = projectConfig.copy || { patterns: [], options: {} } + if (copyConfig.patterns && copyConfig.patterns.length) { + copyConfig.options = copyConfig.options || {} + const globalIgnore = copyConfig.options.ignore + const projectDir = appPath + copyConfig.patterns.forEach(pattern => { + if (typeof pattern === 'object' && pattern.from && pattern.to) { + const from = path.join(projectDir, pattern.from) + const to = path.join(projectDir, pattern.to) + let ignore = pattern.ignore || globalIgnore + if (fs.existsSync(from)) { + const copyOptions = {} + if (ignore) { + ignore = Array.isArray(ignore) ? ignore : [ignore] + copyOptions.filter = src => { + let isMatch = false + ignore.forEach(iPa => { + if (minimatch(path.basename(src), iPa)) { + isMatch = true + } + }) + return !isMatch + } + } + copyFileSync(from, to, copyOptions) + } else { + Util.printLog(Util.pocessTypeEnum.ERROR, '拷贝失败', `${pattern.from} 文件不存在!`) + } + } + }) + } +} + +function watchFiles () { + console.log() + console.log(chalk.gray('监听文件修改中...')) + console.log() + isBuildingScripts = {} + isBuildingStyles = {} + isCopyingFiles = {} + const watcherPaths = [path.join(sourceDir)].concat(watcherDirs) + const watcher = chokidar.watch(watcherPaths, { + ignored: /(^|[/\\])\../, + persistent: true, + ignoreInitial: true + }) + watcher + .on('addDir', dirPath => { + console.log(dirPath) + }) + .on('add', filePath => { + console.log(filePath) + }) + .on('change', async filePath => { + const extname = path.extname(filePath) + // 编译JS文件 + if (Util.REG_SCRIPT.test(extname) || Util.REG_TYPESCRIPT.test(extname)) { + if (filePath.indexOf(entryFileName) >= 0) { + Util.printLog(Util.pocessTypeEnum.MODIFY, '入口文件', `${sourceDirName}/${entryFileName}.js`) + const config = await buildEntry() + // TODO 此处待优化 + if ((Util.checksum(JSON.stringify(config.pages)) !== Util.checksum(JSON.stringify(appConfig.pages))) || + (Util.checksum(JSON.stringify(config.subPackages || config.subpackages || {})) !== Util.checksum(JSON.stringify(appConfig.subPackages || appConfig.subpackages || {})))) { + appConfig = config + await buildPages() + } + } else { + const filePathWithoutExt = filePath.replace(extname, '') + if (isFileToBePage(filePath)) { // 编译页面 + filePath = filePathWithoutExt + filePath = filePath.replace(path.join(sourceDir) + path.sep, '') + filePath = filePath.split(path.sep).join('/') + Util.printLog(Util.pocessTypeEnum.MODIFY, '页面文件', `${sourceDirName}/${filePath}`) + await buildSinglePage(filePath) + } else if (hasBeenBuiltComponents.indexOf(filePath) >= 0) { // 编译组件 + let outoutShowFilePath = filePath.replace(appPath + path.sep, '') + outoutShowFilePath = outoutShowFilePath.split(path.sep).join('/') + Util.printLog(Util.pocessTypeEnum.MODIFY, '组件文件', outoutShowFilePath) + const hasbeenBuiltIndex = hasBeenBuiltComponents.indexOf(filePath) + if (hasbeenBuiltIndex >= 0) { + hasBeenBuiltComponents.splice(hasbeenBuiltIndex, 1) + } + + if (isWindows) { + await new Promise((resolve, reject) => { + setTimeout(async () => { + await buildSingleComponent(Object.assign({ + path: filePath + }, componentsNamedMap[filePath])) + resolve() + }, 300) + }) + } else { + await buildSingleComponent(Object.assign({ + path: filePath + }, componentsNamedMap[filePath])) + } + } else { + let isImported = false + for (const key in dependencyTree) { + const scripts = dependencyTree[key].script || [] + if (scripts.indexOf(filePath) >= 0) { + isImported = true + } + } + let modifySource = filePath.replace(appPath + path.sep, '') + modifySource = modifySource.split(path.sep).join('/') + if (isImported) { + Util.printLog(Util.pocessTypeEnum.MODIFY, 'JS文件', modifySource) + compileDepScripts([filePath]) + } else { + //@fix + if (modifySource.indexOf('src/cloud/') !== -1 || modifySource.indexOf('src\\cloud\\') !== -1) { + exists(path.join('./src/cloud'), path.join('./dist/cloudfunctions'), copy) + Util.printLog(Util.pocessTypeEnum.MODIFY, '云端文件', modifySource) + Util.printLog(Util.pocessTypeEnum.COPY, '云端文件', modifySource.replace('src/cloud', 'dist/cloudfunctions/')) + } else { + Util.printLog(Util.pocessTypeEnum.WARNING, 'JS文件', `${modifySource} 没有被引用到,不会被编译`) + } + } + } + } + } else if (Util.REG_STYLE.test(extname)) { + const includeStyleJSPath = [] + for (const key in dependencyTree) { + const styles = dependencyTree[key]['style'] || [] + styles.forEach(item => { + if (item === filePath) { + includeStyleJSPath.push({ + filePath: key, + styles + }) + } + }) + } + if (includeStyleJSPath.length) { + includeStyleJSPath.forEach(async item => { + let outputWXSSPath = null + outputWXSSPath = item.filePath.replace(path.extname(item.filePath), outputFilesTypes.STYLE) + let modifySource = outputWXSSPath.replace(appPath + path.sep, '') + modifySource = modifySource.split(path.sep).join('/') + Util.printLog(Util.pocessTypeEnum.MODIFY, '样式文件', modifySource) + if (NODE_MODULES_REG.test(outputWXSSPath)) { + let sourceNodeModulesDir = nodeModulesPath + let outputNodeModulesDir = npmOutputDir + outputWXSSPath = outputWXSSPath.replace(sourceNodeModulesDir, outputNodeModulesDir) + } else { + outputWXSSPath = outputWXSSPath.replace(sourceDir, outputDir) + } + let modifyOutput = outputWXSSPath.replace(appPath + path.sep, '') + modifyOutput = modifyOutput.split(path.sep).join('/') + let isComponent = false + if (!isFileToBePage(item.filePath) && item.filePath !== entryFilePath) { + isComponent = true + } + if (isWindows) { + await new Promise((resolve, reject) => { + setTimeout(async () => { + await compileDepStyles(outputWXSSPath, item.styles, isComponent) + resolve() + }, 300) + }) + } else { + await compileDepStyles(outputWXSSPath, item.styles, isComponent) + } + Util.printLog(Util.pocessTypeEnum.GENERATE, '样式文件', modifyOutput) + }) + } else { + let outputWXSSPath = filePath.replace(path.extname(filePath), outputFilesTypes.STYLE) + let modifySource = outputWXSSPath.replace(appPath + path.sep, '') + modifySource = modifySource.split(path.sep).join('/') + Util.printLog(Util.pocessTypeEnum.MODIFY, '样式文件', modifySource) + if (NODE_MODULES_REG.test(outputWXSSPath)) { + let sourceNodeModulesDir = nodeModulesPath + let outputNodeModulesDir = npmOutputDir + outputWXSSPath = outputWXSSPath.replace(sourceNodeModulesDir, outputNodeModulesDir) + } else { + outputWXSSPath = outputWXSSPath.replace(sourceDir, outputDir) + } + let modifyOutput = outputWXSSPath.replace(appPath + path.sep, '') + modifyOutput = modifyOutput.split(path.sep).join('/') + if (isWindows) { + await new Promise((resolve, reject) => { + setTimeout(async () => { + await compileDepStyles(outputWXSSPath, [filePath], false) + resolve() + }, 300) + }) + } else { + await compileDepStyles(outputWXSSPath, [filePath], false) + } + Util.printLog(Util.pocessTypeEnum.GENERATE, '样式文件', modifyOutput) + } + } else { + let modifySource = filePath.replace(appPath + path.sep, '') + modifySource = modifySource.split(path.sep).join('/') + Util.printLog(Util.pocessTypeEnum.MODIFY, '文件', modifySource) + copyFilesFromSrcToOutput([filePath]) + } + isBuildingScripts = {} + isBuildingStyles = {} + isCopyingFiles = {} + }) +} + +async function build ({ watch, adapter }) { + process.env.TARO_ENV = adapter + isProduction = process.env.NODE_ENV === 'production' || !watch + buildAdapter = adapter + outputFilesTypes = Util.MINI_APP_FILES[buildAdapter] + // 可以自定义输出文件类型 + if (weappConf.customFilesTypes && !Util.isEmptyObject(weappConf.customFilesTypes)) { + outputFilesTypes = Object.assign({}, outputFilesTypes, weappConf.customFilesTypes[buildAdapter] || {}) + } + constantsReplaceList = Object.assign({}, constantsReplaceList, { + 'process.env.TARO_ENV': buildAdapter + }) + buildProjectConfig() + await buildFrameworkInfo() + copyFiles() + appConfig = await buildEntry() + await buildPages() + if (watch) { + watchFiles() + } +} + +module.exports = { + build, + buildDepComponents, + buildSingleComponent, + compileDepStyles, + parseAst +} diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/adapter.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/adapter.js new file mode 100644 index 000000000..7fa8e3697 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/adapter.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Adapters; +(function (Adapters) { + Adapters["weapp"] = "weapp"; + Adapters["swan"] = "swan"; + Adapters["alipay"] = "alipay"; + Adapters["quickapp"] = "quickapp"; + Adapters["tt"] = "tt"; +})(Adapters = exports.Adapters || (exports.Adapters = {})); +const weixinAdapter = { + if: 'wx:if', + else: 'wx:else', + elseif: 'wx:elif', + for: 'wx:for', + forItem: 'wx:for-item', + forIndex: 'wx:for-index', + key: 'wx:key', + type: "weapp" /* weapp */ +}; +const swanAdapter = { + if: 's-if', + else: 's-else', + elseif: 's-elif', + for: 's-for', + forItem: 's-for-item', + forIndex: 's-for-index', + key: 's-key', + type: "swan" /* swan */ +}; +const alipayAdapter = { + if: 'a:if', + else: 'a:else', + elseif: 'a:elif', + for: 'a:for', + forItem: 'a:for-item', + forIndex: 'a:for-index', + key: 'a:key', + type: "alipay" /* alipay */ +}; +const ttAdapter = { + if: 'tt:if', + else: 'tt:else', + elseif: 'tt:elif', + for: 'tt:for', + forItem: 'tt:for-item', + forIndex: 'tt:for-index', + key: 'tt:key', + type: "tt" /* tt */ +}; +exports.Adapter = weixinAdapter; +function setAdapter(adapter) { + switch (adapter.toLowerCase()) { + case "swan" /* swan */: + exports.Adapter = swanAdapter; + break; + case "alipay" /* alipay */: + exports.Adapter = alipayAdapter; + break; + case "tt" /* tt */: + exports.Adapter = ttAdapter; + break; + default: + exports.Adapter = weixinAdapter; + break; + } +} +exports.setAdapter = setAdapter; +//# sourceMappingURL=adapter.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/adapter.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/adapter.js.map new file mode 100644 index 000000000..e00138eb7 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/adapter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../src/adapter.ts"],"names":[],"mappings":";;AAAA,IAAkB,QAMjB;AAND,WAAkB,QAAQ;IACxB,2BAAe,CAAA;IACf,yBAAa,CAAA;IACb,6BAAiB,CAAA;IACjB,iCAAqB,CAAA;IACrB,qBAAS,CAAA;AACX,CAAC,EANiB,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAMzB;AAaD,MAAM,aAAa,GAAY;IAC7B,EAAE,EAAE,OAAO;IACX,IAAI,EAAE,SAAS;IACf,MAAM,EAAE,SAAS;IACjB,GAAG,EAAE,QAAQ;IACb,OAAO,EAAE,aAAa;IACtB,QAAQ,EAAE,cAAc;IACxB,GAAG,EAAE,QAAQ;IACb,IAAI,qBAAgB;CACrB,CAAA;AAED,MAAM,WAAW,GAAY;IAC3B,EAAE,EAAE,MAAM;IACV,IAAI,EAAE,QAAQ;IACd,MAAM,EAAE,QAAQ;IAChB,GAAG,EAAE,OAAO;IACZ,OAAO,EAAE,YAAY;IACrB,QAAQ,EAAE,aAAa;IACvB,GAAG,EAAE,OAAO;IACZ,IAAI,mBAAe;CACpB,CAAA;AAED,MAAM,aAAa,GAAY;IAC7B,EAAE,EAAE,MAAM;IACV,IAAI,EAAE,QAAQ;IACd,MAAM,EAAE,QAAQ;IAChB,GAAG,EAAE,OAAO;IACZ,OAAO,EAAE,YAAY;IACrB,QAAQ,EAAE,aAAa;IACvB,GAAG,EAAE,OAAO;IACZ,IAAI,uBAAiB;CACtB,CAAA;AAED,MAAM,SAAS,GAAY;IACzB,EAAE,EAAE,OAAO;IACX,IAAI,EAAE,SAAS;IACf,MAAM,EAAE,SAAS;IACjB,GAAG,EAAE,QAAQ;IACb,OAAO,EAAE,aAAa;IACtB,QAAQ,EAAE,cAAc;IACxB,GAAG,EAAE,QAAQ;IACb,IAAI,eAAa;CAClB,CAAA;AAEU,QAAA,OAAO,GAAY,aAAa,CAAA;AAE3C,SAAgB,UAAU,CAAE,OAAiB;IAC3C,QAAQ,OAAO,CAAC,WAAW,EAAE,EAAE;QAC7B;YACE,eAAO,GAAG,WAAW,CAAA;YACrB,MAAK;QACP;YACE,eAAO,GAAG,aAAa,CAAA;YACvB,MAAK;QACP;YACE,eAAO,GAAG,SAAS,CAAA;YACnB,MAAK;QACP;YACE,eAAO,GAAG,aAAa,CAAA;YACvB,MAAK;KACR;AACH,CAAC;AAfD,gCAeC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/class.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/class.js new file mode 100644 index 000000000..703222a67 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/class.js @@ -0,0 +1,641 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const t = require("babel-types"); +const utils_1 = require("./utils"); +const constant_1 = require("./constant"); +const lodash_1 = require("lodash"); +const render_1 = require("./render"); +const jsx_1 = require("./jsx"); +const adapter_1 = require("./adapter"); +const babel_generator_1 = require("babel-generator"); +function buildConstructor() { + const ctor = t.classMethod('constructor', t.identifier('constructor'), [t.identifier('props')], t.blockStatement([ + t.expressionStatement(t.callExpression(t.identifier('super'), [ + t.identifier('props') + ])) + ])); + return ctor; +} +function processThisPropsFnMemberProperties(member, path, args, binded) { + const propertyArray = []; + function traverseMember(member) { + const object = member.object; + const property = member.property; + if (t.isIdentifier(property)) { + propertyArray.push(property.name); + } + if (t.isMemberExpression(object)) { + if (t.isThisExpression(object.object) && + t.isIdentifier(object.property) && + object.property.name === 'props') { + if ("alipay" /* alipay */ === adapter_1.Adapter.type) { + if (binded) + args.shift(); + path.replaceWith(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier('__triggerPropsFn')), [ + t.stringLiteral(propertyArray.reverse().join('.')), + t.arrayExpression(args) + ])); + } + else { + path.replaceWith(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier('__triggerPropsFn')), [t.stringLiteral(propertyArray.reverse().join('.')), t.callExpression(t.memberExpression(t.arrayExpression([t.nullLiteral()]), t.identifier('concat')), [t.arrayExpression(args)])])); + } + } + traverseMember(object); + } + } + traverseMember(member); +} +class Transformer { + constructor(path, sourcePath, componentProperies, + //@fix add arg => componentSourceMap + componentSourceMap) { + this.result = { + template: '', + components: [], + componentProperies: [] + }; + this.methods = new Map(); + this.initState = new Set(); + this.jsxReferencedIdentifiers = new Set(); + this.customComponents = new Map(); + this.anonymousMethod = new Map(); + this.renderMethod = null; + this.customComponentNames = new Set(); + this.usedState = new Set(); + this.loopStateName = new Map(); + this.customComponentData = []; + this.refs = []; + this.loopRefs = new Map(); + this.anonymousFuncCounter = utils_1.incrementId(); + this.buildPropsAnonymousFunc = (attr, expr, isBind = false) => { + const { code } = babel_generator_1.default(expr); + if (code.startsWith('this.props')) { + const methodName = utils_1.findMethodName(expr); + const hasMethodName = this.anonymousMethod.has(methodName) || !methodName; + const funcName = hasMethodName + ? this.anonymousMethod.get(methodName) + // 测试时使用1个稳定的 uniqueID 便于测试,实际使用5个英文字母,否则小程序不支持 + : process.env.NODE_ENV === 'test' ? lodash_1.uniqueId('funPrivate') : `funPrivate${utils_1.createRandomLetters(5)}`; + this.anonymousMethod.set(methodName, funcName); + const newVal = isBind + ? t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier(funcName)), t.identifier('bind')), expr.arguments || []) + : t.memberExpression(t.thisExpression(), t.identifier(funcName)); + attr.get('value.expression').replaceWith(newVal); + this.methods.set(funcName, null); + this.componentProperies.add(methodName); + if (hasMethodName) { + return; + } + const attrName = attr.node.name; + if (t.isJSXIdentifier(attrName) && attrName.name.startsWith('on')) { + this.componentProperies.add(`__fn_${attrName.name}`); + } + if (methodName.startsWith('on')) { + this.componentProperies.add(`__fn_${methodName}`); + } + const method = t.classMethod('method', t.identifier(funcName), [], t.blockStatement([ + t.expressionStatement(t.callExpression(t.memberExpression(t.thisExpression(), t.identifier('__triggerPropsFn')), [t.stringLiteral(methodName), t.arrayExpression([t.spreadElement(t.identifier('arguments'))])])) + ])); + this.classPath.node.body.body = this.classPath.node.body.body.concat(method); + } + }; + this.classPath = path; + this.sourcePath = sourcePath; + //@fix add arg => componentSourceMap + this.componentSourceMap = componentSourceMap; + for (let key of this.componentSourceMap) { + const arr = key[0].split('/'); + if (arr[arr.length - 1].indexOf('-') !== -1 && key[0].indexOf('components/') !== -1 && key[1].length === 0) { + this.customComponents.set(arr[arr.length - 1], { + sourcePath: key[0], + type: 'default' + }); + } + } + this.moduleNames = Object.keys(path.scope.getAllBindings('module')); + this.componentProperies = new Set(componentProperies); + this.compile(); + } + setMultipleSlots() { + const body = this.classPath.node.body.body; + if (body.some(c => t.isClassProperty(c) && c.key.name === 'multipleSlots')) { + return; + } + const multipleSlots = t.classProperty(t.identifier('multipleSlots'), t.booleanLiteral(true)); + multipleSlots.static = true; + body.push(multipleSlots); + } + createStringRef(componentName, id, refName) { + this.refs.push({ + type: constant_1.DEFAULT_Component_SET.has(componentName) ? 'dom' : 'component', + id, + refName + }); + } + createFunctionRef(componentName, id, fn) { + this.refs.push({ + type: constant_1.DEFAULT_Component_SET.has(componentName) ? 'dom' : 'component', + id, + fn + }); + } + handleRefs() { + const objExpr = this.refs.map(ref => { + return t.objectExpression([ + t.objectProperty(t.identifier('type'), t.stringLiteral(ref.type)), + t.objectProperty(t.identifier('id'), t.stringLiteral(ref.id)), + t.objectProperty(t.identifier('refName'), t.stringLiteral(ref.refName || '')), + t.objectProperty(t.identifier('fn'), ref.fn ? ref.fn : t.nullLiteral()) + ]); + }); + this.classPath.node.body.body.push(t.classProperty(t.identifier('$$refs'), t.arrayExpression(objExpr))); + } + traverse() { + const self = this; + self.classPath.traverse({ + JSXOpeningElement: (path) => { + const jsx = path.node; + const attrs = jsx.attributes; + if (!t.isJSXIdentifier(jsx.name)) { + return; + } + const loopCallExpr = path.findParent(p => utils_1.isArrayMapCallExpression(p)); + const componentName = jsx.name.name; + const refAttr = jsx_1.findJSXAttrByName(attrs, 'ref'); + if (!refAttr) { + return; + } + const idAttr = jsx_1.findJSXAttrByName(attrs, 'id'); + let id = utils_1.createRandomLetters(5); + let idExpr; + if (!idAttr) { + if (loopCallExpr && loopCallExpr.isCallExpression()) { + const [func] = loopCallExpr.node.arguments; + let indexId = null; + if (t.isFunctionExpression(func) || t.isArrowFunctionExpression(func)) { + const params = func.params; + indexId = params[1]; + } + if (indexId === null || !t.isIdentifier(indexId)) { + throw utils_1.codeFrameError(path.node, '在循环中使用 ref 必须暴露循环的第二个参数 `index`'); + } + attrs.push(t.jSXAttribute(t.jSXIdentifier('id'), t.jSXExpressionContainer(t.binaryExpression('+', t.stringLiteral(id), indexId)))); + } + else { + attrs.push(t.jSXAttribute(t.jSXIdentifier('id'), t.stringLiteral(id))); + } + } + else { + const idValue = idAttr.value; + if (t.isStringLiteral(idValue)) { + id = idValue.value; + } + else if (t.isJSXExpressionContainer(idValue)) { + if (t.isStringLiteral(idValue.expression)) { + id = idValue.expression.value; + } + else { + idExpr = idValue.expression; + } + } + } + if (t.isStringLiteral(refAttr.value)) { + if (loopCallExpr) { + throw utils_1.codeFrameError(refAttr, '循环中的 ref 只能使用函数。'); + } + this.createStringRef(componentName, id, refAttr.value.value); + } + if (t.isJSXExpressionContainer(refAttr.value)) { + const expr = refAttr.value.expression; + if (t.isStringLiteral(expr)) { + if (loopCallExpr) { + throw utils_1.codeFrameError(refAttr, '循环中的 ref 只能使用函数。'); + } + this.createStringRef(componentName, id, expr.value); + } + else if (t.isArrowFunctionExpression(expr) || t.isMemberExpression(expr)) { + const type = constant_1.DEFAULT_Component_SET.has(componentName) ? 'dom' : 'component'; + if (loopCallExpr) { + this.loopRefs.set(path.parentPath.node, { + id: idExpr || id, + fn: expr, + type, + component: path.parentPath + }); + } + else { + this.refs.push({ + type, + id, + fn: expr + }); + } + } + else { + throw utils_1.codeFrameError(refAttr, 'ref 仅支持传入字符串、匿名箭头函数和 class 中已声明的函数'); + } + } + for (const [index, attr] of attrs.entries()) { + if (attr === refAttr) { + attrs.splice(index, 1); + } + } + }, + ClassMethod(path) { + const node = path.node; + if (t.isIdentifier(node.key)) { + const name = node.key.name; + self.methods.set(name, path); + if (name === 'render') { + self.renderMethod = path; + path.traverse({ + ReturnStatement(returnPath) { + const arg = returnPath.node.argument; + const ifStem = returnPath.findParent(p => p.isIfStatement()); + if (ifStem && ifStem.isIfStatement() && arg === null) { + const consequent = ifStem.get('consequent'); + if (consequent.isBlockStatement() && consequent.node.body.includes(returnPath.node)) { + returnPath.get('argument').replaceWith(t.nullLiteral()); + } + } + } + }); + } + if (name === 'constructor') { + path.traverse({ + AssignmentExpression(p) { + if (t.isMemberExpression(p.node.left) && + t.isThisExpression(p.node.left.object) && + t.isIdentifier(p.node.left.property) && + p.node.left.property.name === 'data' && + t.isObjectExpression(p.node.right)) { + const properties = p.node.right.properties; + properties.forEach(p => { + if (t.isObjectProperty(p) && t.isIdentifier(p.key)) { + self.initState.add(p.key.name); + } + }); + } + } + }); + } + } + }, + IfStatement(path) { + const test = path.get('test'); + const consequent = path.get('consequent'); + if (utils_1.isContainJSXElement(consequent) && utils_1.hasComplexExpression(test)) { + const scope = self.renderMethod && self.renderMethod.scope || path.scope; + utils_1.generateAnonymousState(scope, test, self.jsxReferencedIdentifiers, true); + } + }, + ClassProperty(path) { + const { key: { name }, value } = path.node; + if (t.isArrowFunctionExpression(value) || t.isFunctionExpression(value)) { + self.methods.set(name, path); + } + if (name === 'data' && t.isObjectExpression(value)) { + value.properties.forEach(p => { + if (t.isObjectProperty(p)) { + if (t.isIdentifier(p.key)) { + self.initState.add(p.key.name); + } + } + }); + } + }, + JSXExpressionContainer(path) { + const attr = path.findParent(p => p.isJSXAttribute()); + const isFunctionProp = attr && typeof attr.node.name.name === 'string' && attr.node.name.name.startsWith('on'); + path.traverse({ + MemberExpression(path) { + const sibling = path.getSibling('property'); + if (path.get('object').isThisExpression() && + (path.get('property').isIdentifier({ name: 'props' }) || path.get('property').isIdentifier({ name: 'data' })) && + sibling.isIdentifier()) { + if (!isFunctionProp) { + self.usedState.add(sibling.node.name); + } + } + } + }); + const expression = path.get('expression'); + const scope = self.renderMethod && self.renderMethod.scope || path.scope; + const calleeExpr = expression.get('callee'); + const parentPath = path.parentPath; + if (utils_1.hasComplexExpression(expression) && + !isFunctionProp && + !(calleeExpr && + calleeExpr.isMemberExpression() && + calleeExpr.get('object').isMemberExpression() && + calleeExpr.get('property').isIdentifier({ name: 'bind' })) // is not bind + ) { + utils_1.generateAnonymousState(scope, expression, self.jsxReferencedIdentifiers); + } + else { + if (parentPath.isJSXAttribute()) { + if (!(expression.isMemberExpression() || expression.isIdentifier()) && parentPath.node.name.name === 'key') { + utils_1.generateAnonymousState(scope, expression, self.jsxReferencedIdentifiers); + } + } + } + if (!attr) + return; + const key = attr.node.name; + const value = attr.node.value; + if (!t.isJSXIdentifier(key)) { + return; + } + if (t.isJSXIdentifier(key) && key.name.startsWith('on') && t.isJSXExpressionContainer(value)) { + const expr = value.expression; + if (t.isCallExpression(expr) && t.isMemberExpression(expr.callee) && t.isIdentifier(expr.callee.property, { name: 'bind' })) { + self.buildPropsAnonymousFunc(attr, expr, true); + } + else if (t.isMemberExpression(expr)) { + self.buildPropsAnonymousFunc(attr, expr, false); + } + else if (t.isArrowFunctionExpression(expr)) { + const exprPath = attr.get('value.expression'); + const stemParent = path.getStatementParent(); + const counter = self.anonymousFuncCounter(); + const anonymousFuncName = `anonymousFunc${counter}`; + const isCatch = utils_1.isContainStopPropagation(exprPath); + const classBody = self.classPath.node.body.body; + const loopCallExpr = path.findParent(p => utils_1.isArrayMapCallExpression(p)); + let index; + if (loopCallExpr) { + index = lodash_1.get(loopCallExpr, 'node.arguments[0].params[1]'); + if (!t.isIdentifier(index)) { + index = t.identifier('__index' + counter); + lodash_1.set(loopCallExpr, 'node.arguments[0].params[1]', index); + } + classBody.push(t.classProperty(t.identifier(anonymousFuncName + 'Array'), t.arrayExpression([]))); + const arrayFunc = t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier(anonymousFuncName + 'Array')), t.identifier(index.name), true); + classBody.push(t.classMethod('method', t.identifier(anonymousFuncName), [t.identifier(index.name), t.identifier('e')], t.blockStatement([ + isCatch ? t.expressionStatement(t.callExpression(t.memberExpression(t.identifier('e'), t.identifier('stopPropagation')), [])) : t.emptyStatement(), + t.expressionStatement(t.logicalExpression('&&', arrayFunc, t.callExpression(arrayFunc, [t.identifier('e')]))) + ]))); + exprPath.replaceWith(t.callExpression(t.memberExpression(t.memberExpression(t.thisExpression(), t.identifier(anonymousFuncName)), t.identifier('bind')), [t.thisExpression(), t.identifier(index.name)])); + stemParent.insertBefore(t.expressionStatement(t.assignmentExpression('=', arrayFunc, expr))); + } + else { + classBody.push(t.classMethod('method', t.identifier(anonymousFuncName), [t.identifier('e')], t.blockStatement([ + isCatch ? t.expressionStatement(t.callExpression(t.memberExpression(t.identifier('e'), t.identifier('stopPropagation')), [])) : t.emptyStatement() + ]))); + exprPath.replaceWith(t.memberExpression(t.thisExpression(), t.identifier(anonymousFuncName))); + stemParent.insertBefore(t.expressionStatement(t.assignmentExpression('=', t.memberExpression(t.thisExpression(), t.identifier(anonymousFuncName)), expr))); + } + } + else { + throw utils_1.codeFrameError(path.node, '组件事件传参只能在使用匿名箭头函数,或使用类作用域下的确切引用(this.handleXX || this.props.handleXX),或使用 bind。'); + } + } + const jsx = path.findParent(p => p.isJSXOpeningElement()); + if (!jsx) + return; + const jsxName = jsx.node.name; + if (!t.isJSXIdentifier(jsxName)) + return; + if (expression.isJSXElement()) + return; + if (constant_1.DEFAULT_Component_SET.has(jsxName.name) || expression.isIdentifier() || expression.isMemberExpression() || expression.isLiteral() || expression.isLogicalExpression() || expression.isConditionalExpression() || key.name.startsWith('on') || expression.isCallExpression()) + return; + utils_1.generateAnonymousState(scope, expression, self.jsxReferencedIdentifiers); + }, + JSXElement(path) { + const id = path.node.openingElement.name; + //@fix extrat xx-xx components to customComponents list + if (t.isJSXIdentifier(id) && id.name.indexOf('-') !== -1) { + for (let key of self.componentSourceMap) { + const arr = key[0].split('/'); + if (arr[arr.length - 1] === id.name && key[1].length === 0) { + self.customComponents.set(id.name, { + sourcePath: key[0], + type: 'default' + }); + } + } + } + if (t.isJSXIdentifier(id) && + !constant_1.DEFAULT_Component_SET.has(id.name) && + self.moduleNames.indexOf(id.name) !== -1) { + const name = id.name; + const binding = self.classPath.scope.getBinding(name); + if (binding && t.isImportDeclaration(binding.path.parent)) { + const sourcePath = binding.path.parent.source.value; + if (binding.path.isImportDefaultSpecifier()) { + self.customComponents.set(name, { + sourcePath, + type: 'default' + }); + } + else { + self.customComponents.set(name, { + sourcePath, + type: 'pattern' + }); + } + } + } + }, + MemberExpression: (path) => { + const object = path.get('object'); + const property = path.get('property'); + if (!(object.isThisExpression() && property.isIdentifier({ name: 'props' }))) { + return; + } + const parentPath = path.parentPath; + if (parentPath.isMemberExpression()) { + const siblingProp = parentPath.get('property'); + if (siblingProp.isIdentifier()) { + const name = siblingProp.node.name; + if (name === 'children') { + parentPath.replaceWith(t.jSXElement(t.jSXOpeningElement(t.jSXIdentifier('slot'), [], true), t.jSXClosingElement(t.jSXIdentifier('slot')), [], true)); + } + else if (/^render[A-Z]/.test(name)) { + const slotName = utils_1.getSlotName(name); + parentPath.replaceWith(t.jSXElement(t.jSXOpeningElement(t.jSXIdentifier('slot'), [ + t.jSXAttribute(t.jSXIdentifier('name'), t.stringLiteral(slotName)) + ], true), t.jSXClosingElement(t.jSXIdentifier('slot')), [])); + this.setMultipleSlots(); + } + else { + self.componentProperies.add(siblingProp.node.name); + } + } + } + else if (parentPath.isVariableDeclarator()) { + const siblingId = parentPath.get('id'); + if (siblingId.isObjectPattern()) { + const properties = siblingId.node.properties; + for (const prop of properties) { + if (t.isRestProperty(prop)) { + throw utils_1.codeFrameError(prop.loc, 'this.props 不支持使用 rest property 语法,请把每一个 prop 都单独列出来'); + } + else if (t.isIdentifier(prop.key)) { + self.componentProperies.add(prop.key.name); + } + } + } + } + }, + CallExpression(path) { + const node = path.node; + const callee = node.callee; + if (t.isMemberExpression(callee) && t.isMemberExpression(callee.object)) { + const property = callee.property; + if (t.isIdentifier(property)) { + if (property.name.startsWith('on')) { + self.componentProperies.add(`__fn_${property.name}`); + processThisPropsFnMemberProperties(callee, path, node.arguments, false); + } + else if (property.name === 'call' || property.name === 'apply') { + self.componentProperies.add(`__fn_${property.name}`); + processThisPropsFnMemberProperties(callee.object, path, node.arguments, true); + } + } + } + } + }); + } + setComponents() { + this.customComponents.forEach((component, name) => { + this.result.components.push({ + path: utils_1.pathResolver(component.sourcePath, this.sourcePath), + name: lodash_1.kebabCase(name), + type: component.type + }); + }); + } + setMethods() { + const methods = this.classPath.get('body').get('body'); + for (const method of methods) { + if (method.isClassMethod()) { + const key = method.get('key'); + if (key.isIdentifier()) { + this.methods.set(key.node.name, method); + } + } + } + } + resetConstructor() { + const body = this.classPath.node.body.body; + if (!this.methods.has('constructor')) { + const ctor = buildConstructor(); + body.unshift(ctor); + } + if (process.env.NODE_ENV === 'test') { + return; + } + for (const method of body) { + if (t.isClassMethod(method) && method.kind === 'constructor') { + method.kind = 'method'; + method.key = t.identifier('_constructor'); + if (t.isBlockStatement(method.body)) { + for (const statement of method.body.body) { + if (t.isExpressionStatement(statement)) { + const expr = statement.expression; + if (t.isCallExpression(expr) && (t.isIdentifier(expr.callee, { name: 'super' }) || t.isSuper(expr.callee))) { + expr.callee = t.memberExpression(t.identifier('super'), t.identifier('_constructor')); + } + } + } + } + } + } + } + handleLifecyclePropParam(propParam, properties) { + let propsName = null; + if (!propParam) { + return null; + } + if (t.isIdentifier(propParam)) { + propsName = propParam.name; + } + else if (t.isObjectPattern(propParam)) { + for (const prop of propParam.properties) { + if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) { + properties.add(prop.key.name); + } + else if (t.isRestProperty(prop) && t.isIdentifier(prop.argument)) { + propsName = prop.argument.name; + } + } + } + else { + throw utils_1.codeFrameError(propParam.loc, '此生命周期的第一个参数只支持写标识符或对象解构'); + } + return propsName; + } + findMoreProps() { + // 第一个参数是 props 的生命周期 + const lifeCycles = new Set([ + // 'constructor', + 'componentDidUpdate', + 'shouldComponentUpdate', + 'getDerivedStateFromProps', + 'getSnapshotBeforeUpdate', + 'componentWillReceiveProps', + 'componentWillUpdate' + ]); + const properties = new Set(); + this.methods.forEach((method, name) => { + if (!lifeCycles.has(name)) { + return; + } + const node = method.node; + let propsName = null; + if (t.isClassMethod(node)) { + propsName = this.handleLifecyclePropParam(node.params[0], properties); + } + else if (t.isArrowFunctionExpression(node.value) || t.isFunctionExpression(node.value)) { + propsName = this.handleLifecyclePropParam(node.value.params[0], properties); + } + if (propsName === null) { + return; + } + method.traverse({ + MemberExpression(path) { + if (!path.isReferencedMemberExpression()) { + return; + } + const { object, property } = path.node; + if (t.isIdentifier(object, { name: propsName }) && t.isIdentifier(property)) { + properties.add(property.name); + } + }, + VariableDeclarator(path) { + const { id, init } = path.node; + if (t.isObjectPattern(id) && t.isIdentifier(init, { name: propsName })) { + for (const prop of id.properties) { + if (t.isObjectProperty(prop) && t.isIdentifier(prop.key)) { + properties.add(prop.key.name); + } + } + } + } + }); + properties.forEach((value) => { + this.componentProperies.add(value); + }); + }); + } + parseRender() { + if (this.renderMethod) { + this.result.template = this.result.template + + new render_1.RenderParser(this.renderMethod, this.methods, this.initState, this.jsxReferencedIdentifiers, this.usedState, this.loopStateName, this.customComponentNames, this.customComponentData, this.componentProperies, this.loopRefs).outputTemplate; + } + } + compile() { + this.traverse(); + this.setMethods(); + this.setComponents(); + this.resetConstructor(); + this.findMoreProps(); + this.handleRefs(); + this.parseRender(); + this.result.componentProperies = [...this.componentProperies]; + } +} +exports.Transformer = Transformer; +//# sourceMappingURL=class.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/class.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/class.js.map new file mode 100644 index 000000000..069ec65c5 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/class.js.map @@ -0,0 +1 @@ +{"version":3,"file":"class.js","sourceRoot":"","sources":["../../src/class.ts"],"names":[],"mappings":";;AACA,iCAAgC;AAChC,mCAYgB;AAChB,yCAAkD;AAClD,mCAA4E;AAC5E,qCAAuC;AACvC,+BAAyC;AACzC,uCAA6C;AAE7C,qDAAsC;AAItC,SAAS,gBAAgB;IACvB,MAAM,IAAI,GAAG,CAAC,CAAC,WAAW,CACxB,aAAa,EACb,CAAC,CAAC,UAAU,CAAC,aAAa,CAAC,EAC3B,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,EACvB,CAAC,CAAC,cAAc,CAAC;QACf,CAAC,CAAC,mBAAmB,CACnB,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE;YACtC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC;SACtB,CAAC,CACH;KACF,CAAC,CACH,CAAA;IACD,OAAO,IAAI,CAAA;AACb,CAAC;AAED,SAAS,kCAAkC,CACzC,MAA0B,EAC1B,IAAgC,EAChC,IAA2C,EAC3C,MAAe;IAEf,MAAM,aAAa,GAAa,EAAE,CAAA;IAClC,SAAS,cAAc,CAAE,MAA0B;QACjD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAA;QAC5B,MAAM,QAAQ,GAAG,MAAM,C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ACF;gBACH,CAAC;aACF,CAAC,CAAA;YACF,UAAU,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE;gBAC3B,IAAI,CAAC,kBAAkB,CAAC,GAAG,CAAC,KAAK,CAAC,CAAA;YACpC,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC;IAED,WAAW;QACT,IAAI,IAAI,CAAC,YAAY,EAAE;YACrB,IAAI,CAAC,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ;kBACvC,IAAI,qBAAY,CAChB,IAAI,CAAC,YAAY,EACjB,IAAI,CAAC,OAAO,EACZ,IAAI,CAAC,SAAS,EACd,IAAI,CAAC,wBAAwB,EAC7B,IAAI,CAAC,SAAS,EACd,IAAI,CAAC,aAAa,EAClB,IAAI,CAAC,oBAAoB,EACzB,IAAI,CAAC,mBAAmB,EACxB,IAAI,CAAC,kBAAkB,EACvB,IAAI,CAAC,QAAQ,CACd,CAAC,cAAc,CAAA;SACnB;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC,QAAQ,EAAE,CAAA;QACf,IAAI,CAAC,UAAU,EAAE,CAAA;QACjB,IAAI,CAAC,aAAa,EAAE,CAAA;QACpB,IAAI,CAAC,gBAAgB,EAAE,CAAA;QACvB,IAAI,CAAC,aAAa,EAAE,CAAA;QACpB,IAAI,CAAC,UAAU,EAAE,CAAA;QACjB,IAAI,CAAC,WAAW,EAAE,CAAA;QAClB,IAAI,CAAC,MAAM,CAAC,kBAAkB,GAAG,CAAC,GAAG,IAAI,CAAC,kBAAkB,CAAC,CAAA;IAC/D,CAAC;CACF;AAEQ,kCAAW"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/constant.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/constant.js new file mode 100644 index 000000000..14e9c316f --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/constant.js @@ -0,0 +1,94 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.THIRD_PARTY_COMPONENTS = new Set(); +// tslint:disable-next-line:variable-name +exports.DEFAULT_Component_SET = new Set([ + 'view', + 'scroll-view', + 'swiper', + 'movable-view', + 'cover-view', + 'cover-image', + 'icon', + 'text', + 'rich-text', + 'progress', + 'button', + 'checkbox', + 'form', + 'input', + 'label', + 'picker', + 'picker-view', + 'picker-view-column', + 'radio', + 'radio-group', + 'checkbox-group', + 'slider', + 'switch', + 'textarea', + 'navigator', + 'audio', + 'image', + 'video', + 'camera', + 'live-player', + 'live-pusher', + 'map', + 'canvas', + 'open-data', + 'web-view', + 'swiper-item', + 'movable-area', + 'movable-view', + 'functional-page-navigator', + 'ad', + 'block', + 'import', + 'official-account' +]); +exports.INTERNAL_SAFE_GET = 'internal_safe_get'; +exports.TARO_PACKAGE_NAME = '@tarojs/taro'; +exports.COMPONENTS_PACKAGE_NAME = '@tarojs/components'; +exports.REDUX_PACKAGE_NAME = '@tarojs/redux'; +exports.MOBX_PACKAGE_NAME = '@tarojs/mobx'; +exports.MAP_CALL_ITERATOR = '__item'; +exports.INTERNAL_INLINE_STYLE = 'internal_inline_style'; +exports.INTERNAL_GET_ORIGNAL = 'internal_get_original'; +exports.GEL_ELEMENT_BY_ID = 'getElementById'; +exports.LOOP_STATE = '$loopState'; +exports.LOOP_ORIGINAL = '$original'; +exports.setLoopOriginal = (s) => exports.LOOP_ORIGINAL = s; +exports.LOOP_CALLEE = '$anonymousCallee_'; +exports.SPECIAL_COMPONENT_PROPS = new Map(); +exports.SPECIAL_COMPONENT_PROPS.set('Progress', new Set([ + 'activeColor', + 'backgroundColor' +])); +exports.IMAGE_COMPONENTS = new Set([ + 'Image', + 'CoverImage' +]); +exports.swanSpecialAttrs = { + 'ScrollView': ['scrollTop', 'scrollLeft', 'scrollIntoView'], + 'Input': ['value'], + 'Textarea': ['value'], + 'MovableView': ['x', 'y'], + 'Slider': ['value'] +}; +exports.ALIPAY_BUBBLE_EVENTS = new Set([ + 'onTouchStart', + 'onTouchMove', + 'onTouchEnd', + 'onTouchCancel', + 'onClick', + 'onLongTap' +]); +exports.TRANSFORM_COMPONENT_PROPS = new Map(); +exports.TRANSFORM_COMPONENT_PROPS.set("alipay" /* alipay */, { + 'Canvas': { + 'canvasId': 'id' + } +}); +exports.lessThanSignPlacehold = '__LESS_THAN_SIGN_PLACEHOLDER__'; +//# sourceMappingURL=constant.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/constant.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/constant.js.map new file mode 100644 index 000000000..722c501d2 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/constant.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constant.js","sourceRoot":"","sources":["../../src/constant.ts"],"names":[],"mappings":";;AAEa,QAAA,sBAAsB,GAAG,IAAI,GAAG,EAAU,CAAA;AAEvD,yCAAyC;AAC5B,QAAA,qBAAqB,GAAG,IAAI,GAAG,CAAS;IACnD,MAAM;IACN,YAAY;IACZ,QAAQ;IACR,aAAa;IACb,WAAW;IACX,YAAY;IACZ,MAAM;IACN,MAAM;IACN,UAAU;IACV,UAAU;IACV,QAAQ;IACR,UAAU;IACV,MAAM;IACN,OAAO;IACP,OAAO;IACP,QAAQ;IACR,YAAY;IACZ,kBAAkB;IAClB,OAAO;IACP,YAAY;IACZ,eAAe;IACf,QAAQ;IACR,QAAQ;IACR,UAAU;IACV,WAAW;IACX,OAAO;IACP,OAAO;IACP,OAAO;IACP,QAAQ;IACR,YAAY;IACZ,YAAY;IACZ,KAAK;IACL,QAAQ;IACR,UAAU;IACV,SAAS;IACT,YAAY;IACZ,aAAa;IACb,aAAa;IACb,yBAAyB;IACzB,IAAI;IACJ,OAAO;IACP,QAAQ;IACR,iBAAiB;CAClB,CAAC,CAAA;AAEW,QAAA,iBAAiB,GAAG,mBAAmB,CAAA;AAEvC,QAAA,iBAAi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,QAAQ,EAAE;QACR,UAAU,EAAE,IAAI;KACjB;CACF,CAAC,CAAA;AAEW,QAAA,qBAAqB,GAAG,gCAAgC,CAAA"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/create-html-element.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/create-html-element.js new file mode 100644 index 000000000..98859f18b --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/create-html-element.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const voidHtmlTags = new Set([ + // 'image', + 'img', + 'input', + 'import' +]); +if (process.env.NODE_ENV === 'test') { + voidHtmlTags.add('image'); +} +function stringifyAttributes(input) { + const attributes = []; + for (const key of Object.keys(input)) { + let value = input[key]; + if (value === false) { + continue; + } + if (Array.isArray(value)) { + value = value.join(' '); + } + let attribute = key; + if (value !== true) { + attribute += `="${String(value)}"`; + } + attributes.push(attribute); + } + return attributes.length > 0 ? ' ' + attributes.join(' ') : ''; +} +exports.createHTMLElement = (options) => { + options = Object.assign({ + name: 'div', + attributes: {}, + value: '' + }, options); + const isVoidTag = voidHtmlTags.has(options.name); + let ret = `<${options.name}${stringifyAttributes(options.attributes)}${isVoidTag ? `/` : ''}>`; + if (!isVoidTag) { + ret += `${options.value}`; + } + return ret; +}; +//# sourceMappingURL=create-html-element.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/create-html-element.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/create-html-element.js.map new file mode 100644 index 000000000..5c20fb7be --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/create-html-element.js.map @@ -0,0 +1 @@ +{"version":3,"file":"create-html-element.js","sourceRoot":"","sources":["../../src/create-html-element.ts"],"names":[],"mappings":";;AAAA,MAAM,YAAY,GAAG,IAAI,GAAG,CAAS;IACnC,WAAW;IACX,KAAK;IACL,OAAO;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AAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAG,GAAG,CAAA;IAE/F,IAAI,CAAC,SAAS,EAAE;QACd,GAAG,IAAI,GAAG,OAAO,CAAC,KAAK,KAAK,OAAO,CAAC,IAAI,GAAG,CAAA;KAC5C;IAED,OAAO,GAAG,CAAA;AACZ,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/eslint.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/eslint.js new file mode 100644 index 000000000..a44d44bb1 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/eslint.js @@ -0,0 +1,47 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const eslint_1 = require("eslint"); +const utils_1 = require("./utils"); +const cli = new eslint_1.CLIEngine({ + baseConfig: { + extends: ['plugin:taro/transformer'] + }, + useEslintrc: false, + parser: 'babel-eslint', + parserOptions: { + ecmaVersion: 2018, + ecmaFeatures: { + jsx: true, + legacyDecorators: true + } + } +}); +exports.eslintValidation = () => { + return { + visitor: { + Program(_, state) { + const { file: { code } } = state; + const report = cli.executeOnText(code); + if (report.errorCount > 0) { + for (const result of report.results) { + for (const msg of result.messages) { + const err = utils_1.codeFrameError({ + start: { + line: msg.line, + column: msg.column + }, + end: { + line: msg.endLine, + column: msg.endColumn + } + }, msg.message); + // tslint:disable-next-line + console.warn('\n' + `ESLint(${msg.ruleId}) 错误:` + err.message + '\n'); + } + } + } + } + } + }; +}; +//# sourceMappingURL=eslint.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/eslint.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/eslint.js.map new file mode 100644 index 000000000..05f4f5104 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/eslint.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eslint.js","sourceRoot":"","sources":["../../src/eslint.ts"],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ages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/index.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/index.js new file mode 100644 index 000000000..9a46ef623 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/index.js @@ -0,0 +1,488 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const babel_traverse_1 = require("babel-traverse"); +const babel_generator_1 = require("babel-generator"); +const html_1 = require("html"); +const babel_core_1 = require("babel-core"); +const ts = require("typescript"); +const class_1 = require("./class"); +const utils_1 = require("./utils"); +const t = require("babel-types"); +const constant_1 = require("./constant"); +const adapter_1 = require("./adapter"); +const options_1 = require("./options"); +const lodash_1 = require("lodash"); +const template = require('babel-template'); +function getIdsFromMemberProps(member) { + let ids = []; + const { object, property } = member; + if (t.isMemberExpression(object)) { + ids = ids.concat(getIdsFromMemberProps(object)); + } + if (t.isThisExpression(object)) { + ids.push('this'); + } + if (t.isIdentifier(object)) { + ids.push(object.name); + } + if (t.isIdentifier(property)) { + ids.push(property.name); + } + return ids; +} +/** + * TS 编译器会把 class property 移到构造器, + * 而小程序要求 `config` 和所有函数在初始化(after new Class)之后就收集到所有的函数和 config 信息, + * 所以当如构造器里有 this.func = () => {...} 的形式,就给他转换成普通的 classProperty function + * 如果有 config 就给他还原 + */ +function resetTSClassProperty(body) { + for (const method of body) { + if (t.isClassMethod(method) && method.kind === 'constructor') { + if (t.isBlockStatement(method.body)) { + method.body.body = method.body.body.filter(statement => { + if (t.isExpressionStatement(statement) && t.isAssignmentExpression(statement.expression)) { + const expr = statement.expression; + const { left, right } = expr; + if (t.isMemberExpression(left) && + t.isThisExpression(left.object) && + t.isIdentifier(left.property)) { + if ((t.isArrowFunctionExpression(right) || t.isFunctionExpression(right)) + || + (left.property.name === 'config' && t.isObjectExpression(right))) { + const classProp = t.classProperty(left.property, right); + body.push(classProp); + handleThirdPartyComponent(classProp); + return false; + } + } + } + return true; + }); + } + } + } +} +function findDeclarationScope(path, id) { + const scopePath = path.findParent(p => !!p.scope.getOwnBindingIdentifier(id.name)); + if (scopePath) { + return scopePath; + } + throw utils_1.codeFrameError(path.node, '该引用从未被定义'); +} +function buildFullPathThisPropsRef(id, memberIds, path) { + const scopePath = findDeclarationScope(path, id); + const binding = scopePath.scope.getOwnBinding(id.name); + if (binding) { + const bindingPath = binding.path; + if (bindingPath.isVariableDeclarator()) { + const dclId = bindingPath.get('id'); + const dclInit = bindingPath.get('init'); + let dclInitIds = []; + if (dclInit.isMemberExpression()) { + dclInitIds = getIdsFromMemberProps(dclInit.node); + if (dclId.isIdentifier()) { + memberIds.shift(); + } + if (dclInitIds[0] === 'this' && dclInitIds[1] === 'props') { + return template(dclInitIds.concat(memberIds).join('.'))().expression; + } + } + } + } +} +function handleThirdPartyComponent(expr) { + if (t.isClassProperty(expr) && expr.key.name === 'config' && t.isObjectExpression(expr.value)) { + const properties = expr.value.properties; + for (const prop of properties) { + if (t.isObjectProperty(prop) && + (t.isIdentifier(prop.key, { name: 'usingComponents' }) || t.isStringLiteral(prop.key, { value: 'usingComponents' })) && + t.isObjectExpression(prop.value)) { + for (const value of prop.value.properties) { + if (t.isObjectProperty(value)) { + if (t.isStringLiteral(value.key)) { + constant_1.THIRD_PARTY_COMPONENTS.add(value.key.value); + } + if (t.isIdentifier(value.key)) { + constant_1.THIRD_PARTY_COMPONENTS.add(value.key.name); + } + } + } + } + } + } +} +function transform(options) { + if (options.adapter) { + adapter_1.setAdapter(options.adapter); + } + if (adapter_1.Adapter.type === "swan" /* swan */) { + constant_1.setLoopOriginal('privateOriginal'); + } + constant_1.THIRD_PARTY_COMPONENTS.clear(); + const code = options.isTyped + ? ts.transpile(options.code, { + jsx: ts.JsxEmit.Preserve, + target: ts.ScriptTarget.ESNext, + importHelpers: true, + noEmitHelpers: true + }) + : options.code; + options.env = Object.assign({ 'process.env.TARO_ENV': options.adapter || 'weapp' }, options.env || {}); + options_1.setTransformOptions(options); + utils_1.setting.sourceCode = code; + // babel-traverse 无法生成 Hub + // 导致 Path#getSource|buildCodeFrameError 都无法直接使用 + // 原因大概是 babylon.parse 没有生成 File 实例导致 scope 和 path 原型上都没有 `file` + // 将来升级到 babel@7 可以直接用 parse 而不是 transform + const ast = babel_core_1.transform(code, options_1.buildBabelTransformOptions()).ast; + if (options.isNormal) { + return { ast }; + } + // transformFromAst(ast, code) + let result; + const componentSourceMap = new Map(); + const imageSource = new Set(); + const importSources = new Set(); + let componentProperies = []; + let mainClass; + let storeName; + let renderMethod; + let isImportTaro = false; + babel_traverse_1.default(ast, { + TemplateLiteral(path) { + const nodes = []; + const { quasis, expressions } = path.node; + let index = 0; + if (path.parentPath.isTaggedTemplateExpression()) { + return; + } + for (const elem of quasis) { + if (elem.value.cooked) { + nodes.push(t.stringLiteral(elem.value.cooked)); + } + if (index < expressions.length) { + const expr = expressions[index++]; + if (!t.isStringLiteral(expr, { value: '' })) { + nodes.push(expr); + } + } + } + // + 号连接符必须保证第一和第二个 node 都是字符串 + if (!t.isStringLiteral(nodes[0]) && !t.isStringLiteral(nodes[1])) { + nodes.unshift(t.stringLiteral('')); + } + let root = nodes[0]; + for (let i = 1; i < nodes.length; i++) { + root = t.binaryExpression('+', root, nodes[i]); + } + path.replaceWith(root); + }, + ClassDeclaration(path) { + mainClass = path; + const superClass = utils_1.getSuperClassCode(path); + if (superClass) { + try { + componentProperies = transform({ + isRoot: false, + isApp: false, + code: superClass.code, + isTyped: true, + sourcePath: superClass.sourcePath, + outputPath: superClass.sourcePath + }).componentProperies; + } + catch (error) { + // + } + } + }, + ClassExpression(path) { + mainClass = path; + }, + ClassMethod(path) { + if (t.isIdentifier(path.node.key) && path.node.key.name === 'render') { + renderMethod = path; + } + }, + IfStatement(path) { + const consequent = path.get('consequent'); + if (!consequent.isBlockStatement()) { + consequent.replaceWith(t.blockStatement([ + consequent.node + ])); + } + }, + CallExpression(path) { + const callee = path.get('callee'); + if (utils_1.isContainJSXElement(path)) { + return; + } + if (callee.isReferencedMemberExpression()) { + const id = utils_1.findFirstIdentifierFromMemberExpression(callee.node); + const property = callee.node.property; + if (t.isIdentifier(property) && property.name.startsWith('on')) { + const funcExpr = path.findParent(p => p.isFunctionExpression()); + if (funcExpr && funcExpr.isFunctionExpression()) { + const taroAPI = funcExpr.findParent(p => p.isCallExpression() && t.isMemberExpression(p.node.callee) && t.isIdentifier(p.node.callee.object, { name: 'Taro' })); + if (taroAPI && taroAPI.isCallExpression()) { + throw utils_1.codeFrameError(funcExpr.node, '在回调函数使用从 props 传递的函数时,请把回调函数改造为箭头函数并一直使用 `this` 取值'); + } + } + } + const calleeIds = getIdsFromMemberProps(callee.node); + if (t.isIdentifier(id) && id.name.startsWith('on') && "alipay" /* alipay */ !== adapter_1.Adapter.type) { + const fullPath = buildFullPathThisPropsRef(id, calleeIds, path); + if (fullPath) { + path.replaceWith(t.callExpression(fullPath, path.node.arguments)); + } + } + } + if (callee.isReferencedIdentifier()) { + const id = callee.node; + const ids = [id.name]; + if (t.isIdentifier(id) && id.name.startsWith('on')) { + const funcExpr = path.findParent(p => p.isFunctionExpression()); + if (funcExpr && funcExpr.isFunctionExpression()) { + const taroAPI = funcExpr.findParent(p => p.isCallExpression() && t.isMemberExpression(p.node.callee) && t.isIdentifier(p.node.callee.object, { name: 'Taro' })); + if (taroAPI && taroAPI.isCallExpression()) { + throw utils_1.codeFrameError(funcExpr.node, '在回调函数使用从 props 传递的函数时,请把回调函数改造为箭头函数并一直使用 `this` 取值'); + } + } + const fullPath = buildFullPathThisPropsRef(id, ids, path); + if (fullPath) { + path.replaceWith(t.callExpression(fullPath, path.node.arguments)); + } + } + } + }, + // JSXIdentifier (path) { + // const parentPath = path.parentPath + // if (!parentPath.isJSXAttribute()) { + // return + // } + // const element = parentPath.parentPath + // if (!element.isJSXOpeningElement()) { + // return + // } + // const elementName = element.get('name') + // if (!elementName.isJSXIdentifier()) { + // return + // } + // if (DEFAULT_Component_SET.has(elementName.node.name)) { + // return + // } + // const expr = parentPath.get('value.expression') + // }, + JSXElement(path) { + const assignment = path.findParent(p => p.isAssignmentExpression()); + if (assignment && assignment.isAssignmentExpression() && !options.isTyped) { + const left = assignment.node.left; + if (t.isIdentifier(left)) { + const binding = assignment.scope.getBinding(left.name); + if (binding && binding.scope === assignment.scope) { + if (binding.path.isVariableDeclarator()) { + binding.path.node.init = path.node; + assignment.remove(); + } + else { + throw utils_1.codeFrameError(path.node, '同一个作用域的JSX 变量延时赋值没有意义。详见:https://github.com/NervJS/taro/issues/550'); + } + } + } + } + const switchStatement = path.findParent(p => p.isSwitchStatement()); + if (switchStatement && switchStatement.isSwitchStatement()) { + const { discriminant, cases } = switchStatement.node; + const ifStatement = cases.map((Case, index) => { + const [consequent] = Case.consequent; + if (!t.isBlockStatement(consequent)) { + throw utils_1.codeFrameError(switchStatement.node, '含有 JSX 的 switch case 语句必须每种情况都用花括号 `{}` 包裹结果'); + } + const block = t.blockStatement(consequent.body.filter(b => !t.isBreakStatement(b))); + if (index !== cases.length - 1 && t.isNullLiteral(Case.test)) { + throw utils_1.codeFrameError(Case, '含有 JSX 的 switch case 语句只有最后一个 case 才能是 default'); + } + const test = Case.test === null ? t.nullLiteral() : t.binaryExpression('===', discriminant, Case.test); + return { block, test }; + }).reduceRight((ifStatement, item) => { + if (t.isNullLiteral(item.test)) { + ifStatement.alternate = item.block; + return ifStatement; + } + const newStatement = t.ifStatement(item.test, item.block, t.isBooleanLiteral(ifStatement.test, { value: false }) + ? ifStatement.alternate + : ifStatement); + return newStatement; + }, t.ifStatement(t.booleanLiteral(false), t.blockStatement([]))); + switchStatement.insertAfter(ifStatement); + switchStatement.remove(); + } + const isForStatement = (p) => p && (p.isForStatement() || p.isForInStatement() || p.isForOfStatement()); + const forStatement = path.findParent(isForStatement); + if (isForStatement(forStatement)) { + throw utils_1.codeFrameError(forStatement.node, '不行使用 for 循环操作 JSX 元素,详情:https://github.com/NervJS/taro/blob/master/packages/eslint-plugin-taro/docs/manipulate-jsx-as-array.md'); + } + const loopCallExpr = path.findParent(p => utils_1.isArrayMapCallExpression(p)); + if (loopCallExpr && loopCallExpr.isCallExpression()) { + const [func] = loopCallExpr.node.arguments; + if (t.isArrowFunctionExpression(func) && !t.isBlockStatement(func.body)) { + func.body = t.blockStatement([ + t.returnStatement(func.body) + ]); + } + } + }, + JSXOpeningElement(path) { + const { name } = path.node.name; + if (name === 'Provider') { + const modules = path.scope.getAllBindings('module'); + const providerBinding = Object.values(modules).some((m) => m.identifier.name === 'Provider'); + if (providerBinding) { + path.node.name = t.jSXIdentifier('view'); + const store = path.node.attributes.find(attr => attr.name.name === 'store'); + if (store && t.isJSXExpressionContainer(store.value) && t.isIdentifier(store.value.expression)) { + storeName = store.value.expression.name; + } + path.node.attributes = []; + } + } + if (constant_1.IMAGE_COMPONENTS.has(name)) { + for (const attr of path.node.attributes) { + if (attr.name.name === 'src') { + if (t.isStringLiteral(attr.value)) { + imageSource.add(attr.value.value); + } + else if (t.isJSXExpressionContainer(attr.value)) { + if (t.isStringLiteral(attr.value.expression)) { + imageSource.add(attr.value.expression.value); + } + } + } + } + } + }, + JSXAttribute(path) { + const { name, value } = path.node; + if (!t.isJSXIdentifier(name) || value === null || t.isStringLiteral(value) || t.isJSXElement(value)) { + return; + } + const expr = value.expression; + const exprPath = path.get('value.expression'); + const classDecl = path.findParent(p => p.isClassDeclaration()); + const classDeclName = classDecl && classDecl.isClassDeclaration() && lodash_1.get(classDecl, 'node.id.name', ''); + let isConverted = false; + if (classDeclName) { + isConverted = classDeclName === '_C' || classDeclName.endsWith('Tmpl'); + } + if (!t.isBinaryExpression(expr, { operator: '+' }) && !t.isLiteral(expr) && name.name === 'style' && !isConverted) { + const jsxID = path.findParent(p => p.isJSXOpeningElement()).get('name'); + if (jsxID && jsxID.isJSXIdentifier() && constant_1.DEFAULT_Component_SET.has(jsxID.node.name)) { + exprPath.replaceWith(t.callExpression(t.identifier(constant_1.INTERNAL_INLINE_STYLE), [expr])); + } + } + if (name.name.startsWith('on')) { + if (exprPath.isReferencedIdentifier()) { + const ids = [expr.name]; + const fullPath = buildFullPathThisPropsRef(expr, ids, path); + if (fullPath) { + exprPath.replaceWith(fullPath); + } + } + if (exprPath.isReferencedMemberExpression()) { + const id = utils_1.findFirstIdentifierFromMemberExpression(expr); + const ids = getIdsFromMemberProps(expr); + if (t.isIdentifier(id)) { + const fullPath = buildFullPathThisPropsRef(id, ids, path); + if (fullPath) { + exprPath.replaceWith(fullPath); + } + } + } + // @TODO: bind 的处理待定 + } + }, + ImportDeclaration(path) { + const source = path.node.source.value; + if (importSources.has(source)) { + throw utils_1.codeFrameError(path.node, '无法在同一文件重复 import 相同的包。'); + } + else { + importSources.add(source); + } + const names = []; + if (source === constant_1.TARO_PACKAGE_NAME) { + isImportTaro = true; + path.node.specifiers.push(t.importSpecifier(t.identifier(constant_1.INTERNAL_SAFE_GET), t.identifier(constant_1.INTERNAL_SAFE_GET)), t.importSpecifier(t.identifier(constant_1.INTERNAL_GET_ORIGNAL), t.identifier(constant_1.INTERNAL_GET_ORIGNAL)), t.importSpecifier(t.identifier(constant_1.INTERNAL_INLINE_STYLE), t.identifier(constant_1.INTERNAL_INLINE_STYLE)), t.importSpecifier(t.identifier(constant_1.GEL_ELEMENT_BY_ID), t.identifier(constant_1.GEL_ELEMENT_BY_ID))); + } + if (source === constant_1.REDUX_PACKAGE_NAME || source === constant_1.MOBX_PACKAGE_NAME) { + path.node.specifiers.forEach((s, index, specs) => { + if (s.local.name === 'Provider') { + specs.splice(index, 1); + specs.push(t.importSpecifier(t.identifier('setStore'), t.identifier('setStore'))); + } + }); + } + path.traverse({ + ImportDefaultSpecifier(path) { + const name = path.node.local.name; + constant_1.DEFAULT_Component_SET.has(name) || names.push(name); + }, + ImportSpecifier(path) { + const name = path.node.imported.name; + constant_1.DEFAULT_Component_SET.has(name) || names.push(name); + if (source === constant_1.TARO_PACKAGE_NAME && name === 'Component') { + path.node.local = t.identifier('__BaseComponent'); + } + } + }); + componentSourceMap.set(source, names); + } + }); + if (!isImportTaro) { + ast.program.body.unshift(t.importDeclaration([ + t.importDefaultSpecifier(t.identifier('Taro')), + t.importSpecifier(t.identifier(constant_1.INTERNAL_SAFE_GET), t.identifier(constant_1.INTERNAL_SAFE_GET)), + t.importSpecifier(t.identifier(constant_1.INTERNAL_GET_ORIGNAL), t.identifier(constant_1.INTERNAL_GET_ORIGNAL)), + t.importSpecifier(t.identifier(constant_1.INTERNAL_INLINE_STYLE), t.identifier(constant_1.INTERNAL_INLINE_STYLE)) + ], t.stringLiteral('@tarojs/taro'))); + } + if (!mainClass) { + throw new Error('未找到 Taro.Component 的类定义'); + } + mainClass.node.body.body.forEach(handleThirdPartyComponent); + const storeBinding = mainClass.scope.getBinding(storeName); + mainClass.scope.rename('Component', '__BaseComponent'); + if (storeBinding) { + const statementPath = storeBinding.path.getStatementParent(); + if (statementPath) { + ast.program.body.forEach((node, index, body) => { + if (node === statementPath.node) { + body.splice(index + 1, 0, t.expressionStatement(t.callExpression(t.identifier('setStore'), [ + t.identifier(storeName) + ]))); + } + }); + } + } + resetTSClassProperty(mainClass.node.body.body); + if (options.isApp) { + renderMethod.replaceWith(t.classMethod('method', t.identifier('_createData'), [], t.blockStatement([]))); + return { ast }; + } + //@fix add arg => componentSourceMap + result = new class_1.Transformer(mainClass, options.sourcePath, componentProperies, componentSourceMap).result; + result.code = babel_generator_1.default(ast).code; + result.ast = ast; + const lessThanSignReg = new RegExp(constant_1.lessThanSignPlacehold, 'g'); + result.compressedTemplate = result.template; + result.template = html_1.prettyPrint(result.template, { + max_char: 0, + unformatted: process.env.NODE_ENV === 'test' ? [] : ['text'] + }); + result.template = result.template.replace(lessThanSignReg, '<'); + result.imageSrcs = Array.from(imageSource); + return result; +} +exports.default = transform; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/index.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/index.js.map new file mode 100644 index 000000000..11cf3f7ce --- /dev/null +++ b/packages/omi-cloudbase/scrip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9C,IAAI,OAAO,CAAC,KAAK,EAAE;QACjB,YAAY,CAAC,WAAW,CACtB,CAAC,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,cAAc,CAAC,EAAE,CAAC,CAAC,CAC/E,CAAA;QACD,OAAO,EAAE,GAAG,EAAqB,CAAA;KAClC;IACD,oCAAoC;IACpC,MAAM,GAAG,IAAI,mBAAW,CAAC,SAAS,EAAE,OAAO,CAAC,UAAU,EAAE,kBAAkB,EAAE,kBAAkB,CAAC,CAAC,MAAM,CAAA;IACtG,MAAM,CAAC,IAAI,GAAG,yBAAQ,CAAC,GAAG,CAAC,CAAC,IAAI,CAAA;IAChC,MAAM,CAAC,GAAG,GAAG,GAAG,CAAA;IAChB,MAAM,eAAe,GAAG,IAAI,MAAM,CAAC,gCAAqB,EAAE,GAAG,CAAC,CAAA;IAC9D,MAAM,CAAC,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAA;IAC3C,MAAM,CAAC,QAAQ,GAAG,kBAAW,CAAC,MAAM,CAAC,QAAQ,EAAE;QAC7C,QAAQ,EAAE,CAAC;QACX,WAAW,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;KAC7D,CAAC,CAAA;IACF,MAAM,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,eAAe,EAAE,GAAG,CAAC,CAAA;IAC/D,MAAM,CAAC,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAA;IAC1C,OAAO,MAAM,CAAA;AACf,CAAC;AApaD,4BAoaC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/jsx.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/jsx.js new file mode 100644 index 000000000..3b63fa191 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/jsx.js @@ -0,0 +1,258 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const babel_generator_1 = require("babel-generator"); +const t = require("babel-types"); +const lodash_1 = require("lodash"); +const constant_1 = require("./constant"); +const create_html_element_1 = require("./create-html-element"); +const utils_1 = require("./utils"); +const adapter_1 = require("./adapter"); +function isStartWithWX(str) { + return str[0] === 'w' && str[1] === 'x'; +} +exports.isStartWithWX = isStartWithWX; +const specialComponentName = ['block', 'Block', 'slot', 'Slot']; +function removeJSXThisProperty(path) { + if (!path.parentPath.isCallExpression()) { + const p = path.getSibling('property'); + if (p.isIdentifier({ name: 'props' }) || + p.isIdentifier({ name: 'data' })) { + path.parentPath.replaceWithSourceString('this'); + } + else { + path.parentPath.replaceWith(p); + } + } +} +exports.removeJSXThisProperty = removeJSXThisProperty; +function findJSXAttrByName(attrs, name) { + for (const attr of attrs) { + if (!t.isJSXIdentifier(attr.name)) { + break; + } + if (attr.name.name === name) { + return attr; + } + } + return null; +} +exports.findJSXAttrByName = findJSXAttrByName; +function buildRefTemplate(name, refName, loop, key) { + const attrs = [ + t.jSXAttribute(t.jSXIdentifier('is'), t.stringLiteral(name)), + t.jSXAttribute(t.jSXIdentifier('data'), t.stringLiteral(`{{...${refName ? `${loop ? '' : '$$'}${refName}` : '__data'}}}`)) + ]; + if (key) { + attrs.push(key); + } + return t.jSXElement(t.jSXOpeningElement(t.jSXIdentifier('template'), attrs), t.jSXClosingElement(t.jSXIdentifier('template')), []); +} +exports.buildRefTemplate = buildRefTemplate; +function buildJSXAttr(name, value) { + return t.jSXAttribute(t.jSXIdentifier(name), t.jSXExpressionContainer(value)); +} +exports.buildJSXAttr = buildJSXAttr; +function newJSXIfAttr(jsx, value) { + jsx.openingElement.attributes.push(buildJSXAttr(adapter_1.Adapter.if, value)); +} +exports.newJSXIfAttr = newJSXIfAttr; +function setJSXAttr(jsx, name, value, path) { + const element = jsx.openingElement; + if (!t.isJSXIdentifier(element.name)) { + return; + } + if (element.name.name === 'Block' || element.name.name === 'block' || !path) { + jsx.openingElement.attributes.push(t.jSXAttribute(t.jSXIdentifier(name), value)); + } + else { + const block = buildBlockElement(); + setJSXAttr(block, name, value); + block.children = [jsx]; + path.node = block; + } +} +exports.setJSXAttr = setJSXAttr; +function isAllLiteral(...args) { + return args.every(p => t.isLiteral(p)); +} +exports.isAllLiteral = isAllLiteral; +function buildBlockElement() { + return t.jSXElement(t.jSXOpeningElement(t.jSXIdentifier('block'), []), t.jSXClosingElement(t.jSXIdentifier('block')), []); +} +exports.buildBlockElement = buildBlockElement; +function parseJSXChildren(children) { + return children + .filter(child => { + return !(t.isJSXText(child) && child.value.trim() === ''); + }) + .reduce((str, child) => { + if (t.isJSXText(child)) { + const strings = []; + child.value.split(/(\r?\n\s*)/).forEach((val) => { + const value = val.replace(/\u00a0/g, ' ').trimLeft(); + if (!value) { + return; + } + if (value.startsWith('\n')) { + return; + } + strings.push(value); + }); + return str + strings.join(''); + } + if (t.isJSXElement(child)) { + return str + parseJSXElement(child); + } + if (t.isJSXExpressionContainer(child)) { + if (t.isJSXElement(child.expression)) { + return str + parseJSXElement(child.expression); + } + return str + `{${utils_1.decodeUnicode(babel_generator_1.default(child, { + quotes: 'single', + jsonCompatibleStrings: true + }) + .code) + .replace(/(this\.props\.)|(this\.data\.)/g, '') + .replace(/(props\.)|(data\.)/g, '') + .replace(/this\./g, '') + .replace(/ { + if (a.name.name === adapter_1.Adapter.else && !['block', 'Block'].includes(componentName) && !isDefaultComponent) { + hasElseAttr = true; + attributes.splice(index, 1); + } + }); + if (hasElseAttr) { + return create_html_element_1.createHTMLElement({ + name: 'block', + attributes: { + [adapter_1.Adapter.else]: true + }, + value: parseJSXChildren([element]) + }); + } + let attributesTrans = {}; + if (attributes.length) { + attributesTrans = attributes.reduce((obj, attr) => { + if (t.isJSXSpreadAttribute(attr)) { + throw utils_1.codeFrameError(attr.loc, 'JSX 参数暂不支持 ...spread 表达式'); + } + let name = attr.name.name; + if (constant_1.DEFAULT_Component_SET.has(componentName)) { + if (name === 'className') { + name = 'class'; + } + } + let value = true; + let attrValue = attr.value; + if (typeof name === 'string') { + const isAlipayEvent = adapter_1.Adapter.type === "alipay" /* alipay */ && /(^on[A-Z_])|(^catch[A-Z_])/.test(name); + if (t.isStringLiteral(attrValue)) { + value = attrValue.value; + } + else if (t.isJSXExpressionContainer(attrValue)) { + let isBindEvent = (name.startsWith('bind') && name !== 'bind') || (name.startsWith('catch') && name !== 'catch'); + let code = utils_1.decodeUnicode(babel_generator_1.default(attrValue.expression, { + quotes: 'single', + concise: true + }).code) + .replace(/"/g, "'") + .replace(/(this\.props\.)|(this\.data\.)/g, '') + .replace(/this\./g, ''); + if ("swan" /* swan */ === adapter_1.Adapter.type && + code !== 'true' && + code !== 'false' && + constant_1.swanSpecialAttrs[componentName] && + constant_1.swanSpecialAttrs[componentName].includes(name)) { + value = `{= ${code} =}`; + } + else { + if (adapter_1.Adapter.key === name) { + const splitCode = code.split('.'); + if (splitCode.length > 1) { + value = splitCode.slice(1).join('.'); + } + else { + value = code; + } + } + else { + value = isBindEvent || isAlipayEvent ? code : `{{${code}}}`; + } + } + if (adapter_1.Adapter.type === "swan" /* swan */ && name === adapter_1.Adapter.for) { + value = code; + } + if (t.isStringLiteral(attrValue.expression)) { + value = attrValue.expression.value; + } + } + else if (attrValue === null && name !== adapter_1.Adapter.else) { + value = `{{true}}`; + } + if (constant_1.THIRD_PARTY_COMPONENTS.has(componentName) && /^bind/.test(name) && name.includes('-')) { + name = name.replace(/^bind/, 'bind:'); + } + if (componentTransfromProps && componentTransfromProps[componentName]) { + const transfromProps = componentTransfromProps[componentName]; + Object.keys(transfromProps).forEach(oriName => { + if (transfromProps.hasOwnProperty(name)) { + name = transfromProps[oriName]; + } + }); + } + if ((componentName === 'Input' || componentName === 'input') && name === 'maxLength') { + obj['maxlength'] = value; + } + else if (componentSpecialProps && componentSpecialProps.has(name) || + name.startsWith('__fn_') || + isAlipayEvent) { + obj[name] = value; + } + else { + obj[isDefaultComponent && !name.includes('-') && !name.includes(':') ? lodash_1.kebabCase(name) : name] = value; + } + } + if (!isDefaultComponent && !specialComponentName.includes(componentName)) { + //obj[TRIGGER_OBSERER] = '{{ _triggerObserer }}'; + } + return obj; + }, {}); + } + else if (!isDefaultComponent && !specialComponentName.includes(componentName)) { + //attributesTrans[TRIGGER_OBSERER] = '{{ _triggerObserer }}'; + } + return create_html_element_1.createHTMLElement({ + name: lodash_1.kebabCase(componentName), + attributes: attributesTrans, + value: parseJSXChildren(children) + }); +} +exports.parseJSXElement = parseJSXElement; +function generateHTMLTemplate(template, name) { + return create_html_element_1.createHTMLElement({ + name: 'template', + attributes: { + name + }, + value: parseJSXElement(template) + }); +} +exports.generateHTMLTemplate = generateHTMLTemplate; +//# sourceMappingURL=jsx.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/jsx.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/jsx.js.map new file mode 100644 index 000000000..951253d74 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/jsx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsx.js","sourceRoot":"","sources":["../../src/jsx.ts"],"names":[],"mappings":";;AAAA,qDAAsC;AAEtC,iCAAgC;AAChC,mCAAkC;AAClC,yCAOmB;AACnB,+DAAyD;AACzD,mCAAuD;AACvD,uCAA6C;AAE7C,SAAgB,aAAa,CAAE,GAAW;IACxC,OAAO,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,IAAI,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,CAAA;AACzC,CAAC;AAFD,sCAEC;AAED,MAAM,oBAAoB,GAAG,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAA;AAE/D,SAAgB,qBAAqB,CAAE,IAAgC;IACrE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,g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Aa,CAAC;QAC9B,UAAU,EAAE,eAAe;QAC3B,KAAK,EAAE,gBAAgB,CAAC,QAAQ,CAAC;KAClC,CAAC,CAAA;AACJ,CAAC;AAzHD,0CAyHC;AAED,SAAgB,oBAAoB,CAAE,QAAsB,EAAE,IAAY;IACxE,OAAO,uCAAiB,CAAC;QACvB,IAAI,EAAE,UAAU;QAChB,UAAU,EAAE;YACV,IAAI;SACL;QACD,KAAK,EAAE,eAAe,CAAC,QAAQ,CAAC;KACjC,CAAC,CAAA;AACJ,CAAC;AARD,oDAQC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/lifecycle.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/lifecycle.js new file mode 100644 index 000000000..0dd3bd888 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/lifecycle.js @@ -0,0 +1,33 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var Lifecycle; +(function (Lifecycle) { + Lifecycle["constructor"] = "constructor"; + Lifecycle["componentWillMount"] = "componentWillMount"; + Lifecycle["componentDidMount"] = "componentDidMount"; + Lifecycle["componentWillUpdate"] = "componentWillUpdate"; + Lifecycle["componentDidUpdate"] = "componentDidUpdate"; + Lifecycle["componentWillUnmount"] = "componentWillUnmount"; + Lifecycle["componentDidCatch"] = "componentDidCatch"; + Lifecycle["componentDidShow"] = "componentDidShow"; + Lifecycle["componentDidHide"] = "componentDidHide"; + Lifecycle["componentDidAttached"] = "componentDidAttached"; + Lifecycle["componentDidMoved"] = "componentDidMoved"; + Lifecycle["shouldComponentUpdate"] = "shouldComponentUpdate"; + Lifecycle["componentWillReceiveProps"] = "componentWillReceiveProps"; +})(Lifecycle = exports.Lifecycle || (exports.Lifecycle = {})); +exports.PageLifecycle = { + [Lifecycle.componentDidMount]: 'onLaunch', + [Lifecycle.componentWillMount]: 'onLoad', + [Lifecycle.componentWillUnmount]: 'onUnload', + [Lifecycle.componentDidShow]: 'onShow', + [Lifecycle.componentDidHide]: 'onHide' +}; +exports.ComponentLifeCycle = { + [Lifecycle.componentWillMount]: 'created', + [Lifecycle.componentDidAttached]: 'attached', + [Lifecycle.componentDidMount]: 'ready', + [Lifecycle.componentDidMoved]: 'moved', + [Lifecycle.componentWillUnmount]: 'detached' +}; +//# sourceMappingURL=lifecycle.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/lifecycle.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/lifecycle.js.map new file mode 100644 index 000000000..f6fb74dee --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/lifecycle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"lifecycle.js","sourceRoot":"","sources":["../../src/lifecycle.ts"],"names":[],"mappings":";;AAAA,IAAY,SAcX;AAdD,WAAY,SAAS;IACnB,wCAA2B,CAAA;IAC3B,sDAAyC,CAAA;IACzC,oDAAuC,CAAA;IACvC,wDAA2C,CAAA;IAC3C,sDAAyC,CAAA;IACzC,0DAA6C,CAAA;IAC7C,oDAAuC,CAAA;IACvC,kDAAqC,CAAA;IACrC,kDAAqC,CAAA;IACrC,0DAA6C,CAAA;IAC7C,oDAAuC,CAAA;IACvC,4DAA+C,CAAA;IAC/C,oEAAuD,CAAA;AACzD,CAAC,EAdW,SAAS,GAAT,iBAAS,KAAT,iBAAS,QAcpB;AAEY,QAAA,aAAa,GAAG;IAC3B,CAAC,SAAS,CAAC,iBAAiB,CAAC,EAAE,UAAU;IACzC,CAAC,SAAS,CAAC,kBAAkB,CAAC,EAAE,QAAQ;IACxC,CAAC,SAAS,CAAC,oBAAoB,CAAC,EAAE,UAAU;IAC5C,CAAC,SAAS,CAAC,gBAAgB,CAAC,EAAE,QAAQ;IACtC,CAAC,SAAS,CAAC,gBAAgB,CAAC,EAAE,QAAQ;CACvC,CAAA;AAEY,QAAA,kBAAkB,GAAG;IAChC,CAAC,SAAS,CAAC,kBAAkB,CAAC,EAAE,SAAS;IACzC,CAAC,SAAS,CAAC,oBAAoB,CAAC,EAAE,UAAU;IAC5C,CAAC,SAAS,CAAC,iBAAiB,CAAC,EAAE,OAAO;IACtC,CAAC,SAAS,CAAC,iBAAiB,CAAC,EAAE,OAAO;IACtC,CAAC,SAAS,CAAC,oBAAoB,CAAC,EAAE,UAAU;CAC7C,CAAA"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/loop-component.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/loop-component.js new file mode 100644 index 000000000..4ffbe38ac --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/loop-component.js @@ -0,0 +1,227 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const t = require("babel-types"); +const utils_1 = require("./utils"); +const jsx_1 = require("./jsx"); +const constant_1 = require("./constant"); +const adapter_1 = require("./adapter"); +// @TODO +// 重构 parseRender 和 parseLoop 失败 +// 尚不清楚 babel 的 data 和 context 传参机制 +// 目前先写两份代码,有时间看看 babel 具体对 data 和 context 做了什么导致传参失败 +function parseLoopBody(body, jsxDeclarations, +// @TODO +// 把 templates 换成 Map 可以支持 shalow variables declared +// 现在先用 ESLint 的 no-shalow 顶着 +templates, loopScopes, finalReturnElement, returnedPaths) { + const bodyScope = body.scope; + body.traverse({ + JSXElement(jsxElementPath) { + const parentNode = jsxElementPath.parent; + const parentPath = jsxElementPath.parentPath; + const isFinalReturn = jsxElementPath.getFunctionParent().isClassMethod(); + const isJSXChildren = t.isJSXElement(parentNode); + if (!isJSXChildren) { + let statementParent = jsxElementPath.getStatementParent(); + if (!(statementParent.isVariableDeclaration() || + statementParent.isExpressionStatement())) { + statementParent = statementParent.findParent(s => s.isVariableDeclaration() || s.isExpressionStatement()); + } + jsxDeclarations.add(statementParent); + if (t.isVariableDeclarator(parentNode)) { + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + // setTemplate(name, path, templates) + name && templates.set(name, jsxElementPath.node); + } + } + else if (t.isLogicalExpression(parentNode)) { + const { left, operator } = parentNode; + if (operator === '&&') { + if (t.isExpression(left)) { + utils_1.newJSXIfAttr(jsxElementPath.node, left); + parentPath.replaceWith(jsxElementPath.node); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, templates); + // name && templates.set(name, path.node) + } + } + } + } + else if (t.isConditionalExpression(parentNode)) { + const { test, consequent, alternate } = parentNode; + const block = jsx_1.buildBlockElement(); + if (t.isJSXElement(consequent) && t.isLiteral(alternate)) { + const { value, confident } = parentPath.get('alternate').evaluate(); + if (confident && !value) { + utils_1.newJSXIfAttr(block, test); + block.children = [jsxElementPath.node]; + // newJSXIfAttr(jsxElementPath.node, test) + parentPath.replaceWith(block); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, templates); + // name && templates.set(name, path.node) + } + } + } + else if (t.isLiteral(consequent) && t.isJSXElement(consequent)) { + if (t.isNullLiteral(consequent)) { + utils_1.newJSXIfAttr(block, utils_1.reverseBoolean(test)); + // newJSXIfAttr(jsxElementPath.node, reverseBoolean(test)) + parentPath.replaceWith(block); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, templates); + // name && templates.set(name, path.node) + } + } + } + else if (t.isJSXElement(consequent) && t.isJSXElement(alternate)) { + const block2 = jsx_1.buildBlockElement(); + block.children = [consequent]; + utils_1.newJSXIfAttr(block, test); + jsx_1.setJSXAttr(block2, adapter_1.Adapter.else); + block2.children = [alternate]; + const parentBlock = jsx_1.buildBlockElement(); + parentBlock.children = [block, block2]; + parentPath.replaceWith(parentBlock); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, templates); + } + } + else { + // console.log('todo') + } + } + else if (t.isReturnStatement(parentNode)) { + if (!isFinalReturn) { + const caller = parentPath.findParent(p => p.isCallExpression()); + if (caller.isCallExpression()) { + const callee = caller.node.callee; + if (t.isMemberExpression(callee) && + t.isIdentifier(callee.property) && + callee.property.name === 'map') { + let ary = callee.object; + const blockStatementPath = parentPath.findParent(p => p.isBlockStatement()); + const body = blockStatementPath.node.body; + let stateToBeAssign = new Set(); + for (const statement of body) { + if (t.isVariableDeclaration(statement)) { + for (const dcl of statement.declarations) { + if (t.isIdentifier(dcl.id)) { + const scope = blockStatementPath.scope; + const stateName = scope.generateUid(constant_1.LOOP_STATE); + stateToBeAssign.add(stateName); + blockStatementPath.scope.rename(dcl.id.name, stateName); + } + } + } + } + if (t.isCallExpression(ary) || utils_1.isContainFunction(caller.get('callee').get('object'))) { + const variableName = `anonymousState_${bodyScope.generateUid()}`; + caller.getStatementParent().insertBefore(utils_1.buildConstVariableDeclaration(variableName, ary)); + ary = t.identifier(variableName); + } + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.for, t.jSXExpressionContainer(ary)); + const [func] = caller.node.arguments; + if (t.isFunctionExpression(func) || + t.isArrowFunctionExpression(func)) { + const [item, index] = func.params; + if (t.isIdentifier(item)) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forItem, t.stringLiteral(item.name)); + loopScopes.add(item.name); + } + else { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forItem, t.stringLiteral('__item')); + } + if (t.isIdentifier(index)) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forIndex, t.stringLiteral(index.name)); + loopScopes.add(index.name); + } + caller.replaceWith(jsxElementPath.node); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + // setTemplate(name, path, templates) + name && templates.set(name, jsxElementPath.node); + } + } + } + } + } + else { + const ifStatement = parentPath.findParent(p => p.isIfStatement()); + const blockStatement = parentPath.findParent(p => p.isBlockStatement()); + const block = finalReturnElement || jsx_1.buildBlockElement(); + if (utils_1.isBlockIfStatement(ifStatement, blockStatement)) { + const { test, alternate, consequent } = ifStatement.node; + if (alternate === blockStatement.node) { + throw utils_1.codeFrameError(parentNode.loc, '不必要的 else 分支,请遵从 ESLint consistent-return: https://eslint.org/docs/rules/consistent-return'); + } + else if (consequent === blockStatement.node) { + const parentIfStatement = ifStatement.findParent(p => p.isIfStatement()); + if (parentIfStatement) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.elseif, t.jSXExpressionContainer(test)); + } + else { + utils_1.newJSXIfAttr(jsxElementPath.node, test); + } + } + } + else if (block.children.length !== 0) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.else); + } + block.children.push(jsxElementPath.node); + finalReturnElement = block; + returnedPaths.push(parentPath); + } + } + else if (t.isArrowFunctionExpression(parentNode)) { + // + } + else if (t.isAssignmentExpression(parentNode)) { + if (t.isIdentifier(parentNode.left)) { + const name = parentNode.left.name; + const bindingNode = bodyScope.getOwnBinding(name).path.node; + const block = templates.get(name) || jsx_1.buildBlockElement(); + if (utils_1.isEmptyDeclarator(bindingNode)) { + const ifStatement = parentPath.findParent(p => p.isIfStatement()); + const blockStatement = parentPath.findParent(p => p.isBlockStatement()); + if (utils_1.isBlockIfStatement(ifStatement, blockStatement)) { + const { test, alternate, consequent } = ifStatement.node; + if (alternate === blockStatement.node) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.else); + } + else if (consequent === blockStatement.node) { + const parentIfStatement = ifStatement.findParent(p => p.isIfStatement()); + if (parentIfStatement && parentIfStatement.get('alternate') === ifStatement) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.elseif, t.jSXExpressionContainer(test)); + } + else { + if (parentIfStatement) { + utils_1.newJSXIfAttr(block, parentIfStatement.node.test); + } + utils_1.newJSXIfAttr(jsxElementPath.node, test); + } + } + block.children.push(jsxElementPath.node); + // setTemplate(name, path, templates) + name && templates.set(name, block); + } + } + else { + throw utils_1.codeFrameError(jsxElementPath.node.loc, '请将 JSX 赋值表达式初始化为 null,然后再进行 if 条件表达式赋值。'); + } + } + } + else if (!t.isJSXElement(parentNode)) { + // throwError(path, '考虑只对 JSX 元素赋值一次。') + } + } + } + }); +} +exports.parseLoopBody = parseLoopBody; +//# sourceMappingURL=loop-component.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/loop-component.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/loop-component.js.map new file mode 100644 index 000000000..5becdf88a --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/loop-component.js.map @@ -0,0 +1 @@ +{"version":3,"file":"loop-component.js","sourceRoot":"","sources":["../../src/loop-component.ts"],"names":[],"mappings":";;AACA,iCAAgC;AAChC,mCAUgB;AAChB,+BAGc;AACd,yCAAuC;AACvC,uCAAmC;AAEnC,QAAQ;AACR,gCAAgC;AAChC,mCAAmC;AACnC,qDAAqD;AACrD,SAAgB,aAAa,CAC3B,IAAgC,EAChC,eAAsC;AACtC,QAAQ;AACR,oDAAoD;AACpD,6BAA6B;AAC7B,SAAoC,EACpC,UAAuB,EACvB,kBAAgC,EAChC,aAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,CAAC,KAAK,CAAA;IAC5B,IAAI,CAAC,QAAQ,CAAC;QACZ,UAAU,CAAE,cAAc;YACxB,MAAM,UAAU,GAAG,cAAc,CAAC,MAAM,CAAA;YACxC,MAAM,UAAU,GAAG,cAAc,CAAC,UAAU,CAAA;YAC5C,MAAM,aAAa,GAAG,cAAc,CAAC,iBAAiB,EAAE,CAAC,aAAa,EAAE,CAAA;YACxE,MAAM,aAAa,GAAG,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,CAAA;YAChD,IAAI,CAAC,aAAa,EAAE;gBAClB,IAAI,eAAe,GAAG,cAAc,CAAC,kBAAkB,EAAE,CAAA;gBACzD,IACE,CAAC,CACC,eAAe,CAAC,qBAAqB,EAAE;oBACvC,eAAe,CAAC,qBAAqB,EAAE,CACx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,CAAC,IAAI,CAAC,CAC/B,CAAA;qCACF;yCAAM;wCACL,IAAI,iBAAiB,EAAE;4CACrB,oBAAY,CAAC,KAAK,EAAE,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;yCACjD;wCACD,oBAAY,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;qCACxC;iCACF;gCACD,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,CAAA;gCACxC,qCAAqC;gCACrC,IAAI,IAAI,SAAS,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;6BACnC;yBACF;6BAAM;4BACL,MAAM,sBAAc,CAClB,cAAc,CAAC,IAAI,CAAC,GAAG,EACvB,yCAAyC,CAC1C,CAAA;yBACF;qBACF;iBACF;qBAAM,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,EAAE;oBACtC,uCAAuC;iBACxC;aACF;QACH,CAAC;KACF,CAAC,CAAA;AACJ,CAAC;AAzPD,sCAyPC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/options.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/options.js new file mode 100644 index 000000000..1682411d2 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/options.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const eslint_1 = require("./eslint"); +exports.transformOptions = {}; +exports.setTransformOptions = (options) => { + for (const key in options) { + if (options.hasOwnProperty(key)) { + exports.transformOptions[key] = options[key]; + } + } +}; +exports.buildBabelTransformOptions = () => { + return { + parserOpts: { + sourceType: 'module', + plugins: [ + 'classProperties', + 'jsx', + 'flow', + 'flowComment', + 'trailingFunctionCommas', + 'asyncFunctions', + 'exponentiationOperator', + 'asyncGenerators', + 'objectRestSpread', + 'decorators', + 'dynamicImport' + ] + }, + plugins: [ + require('babel-plugin-transform-flow-strip-types'), + [require('babel-plugin-transform-define').default, exports.transformOptions.env] + ].concat(process.env.ESLINT === 'false' || exports.transformOptions.isNormal || exports.transformOptions.isTyped ? [] : eslint_1.eslintValidation) + .concat((process.env.NODE_ENV === 'test') ? [] : require('babel-plugin-remove-dead-code').default) + }; +}; +//# sourceMappingURL=options.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/options.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/options.js.map new file mode 100644 index 000000000..1729b8199 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"options.js","sourceRoot":"","sources":["../../src/options.ts"],"names":[],"mappings":";;AACA,qCAA2C;AAe9B,QAAA,gBAAgB,GAAY,EAAS,CAAA;AAErC,QAAA,mBAAmB,GAAG,CAAC,OAAgB,EAAE,EAAE;IACtD,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;QACzB,IAAI,OAAO,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;YAC/B,wBAAgB,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAA;SACrC;KACF;AACH,CAAC,CAAA;AAEY,QAAA,0BAA0B,GAA2B,GAAG,EAAE;IACrE,OAAO;QACL,UAAU,EAAE;YACV,UAAU,EAAE,QAAQ;YACpB,OAAO,EAAE;gBACP,iBAAiB;gBACjB,KAAK;gBACL,MAAM;gBACN,aAAa;gBACb,wBAAwB;gBACxB,gBAAgB;gBAChB,wBAAwB;gBACxB,iBAAiB;gBACjB,kBAAkB;gBAClB,YAAY;gBACZ,eAAe;aACP;SACX;QACD,OAAO,EAAE;YACP,OAAO,CAAC,yCAAyC,CAAC;YAClD,CAAC,OAAO,CAAC,+BAA+B,CAAC,CAAC,OAAO,EAAE,wBAAgB,CAAC,GAAG,CAAC;SACzE,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,KAAK,OAAO,IAAI,wBAAgB,CAAC,QAAQ,IAAI,wBAAgB,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,yBAAgB,CAAC;aACxH,MAAM,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,+BAA+B,CAAC,CAAC,OAAO,CAAC;KACnG,CAAA;AACH,CAAC,CAAA"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins.js new file mode 100644 index 000000000..c1fa59f43 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins.js @@ -0,0 +1,45 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const t = require("babel-types"); +function isString(node) { + return t.isLiteral(node) && typeof node.value === 'string'; +} +function buildBinaryExpression(left, right) { + return t.binaryExpression('+', left, right); +} +function templateLiterals(path, state) { + let nodes = []; + const expressions = path.get('expressions'); + for (const elem of (path.node.quasis)) { + nodes.push(t.stringLiteral(elem.value.cooked)); + const expr = expressions.shift(); + if (expr) { + // tslint:disable-next-line:no-multi-spaces + if (state.opts.spec && !expr.isBaseType('string') && !expr.isBaseType('number')) { + nodes.push(t.callExpression(t.identifier('String'), [expr.node])); + } + else { + nodes.push(expr.node); + } + } + } + // filter out empty string literals + nodes = nodes.filter((n) => !t.isLiteral(n, { value: '' })); + // since `+` is left-to-right associative + // ensure the first node is a string if first/second isn't + if (!isString(nodes[0]) && !isString(nodes[1])) { + nodes.unshift(t.stringLiteral('')); + } + if (nodes.length > 1) { + let root = buildBinaryExpression(nodes.shift(), nodes.shift()); + for (const node of nodes) { + root = buildBinaryExpression(root, node); + } + path.replaceWith(root); + } + else { + path.replaceWith(nodes[0]); + } +} +exports.templateLiterals = templateLiterals; +//# sourceMappingURL=plugins.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins.js.map new file mode 100644 index 000000000..898d70b7a --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins.js.map @@ -0,0 +1 @@ +{"version":3,"file":"plugins.js","sourceRoot":"","sources":["../../src/plugins.ts"],"names":[],"mappings":";;AAAA,iCAAgC;AAEhC,SAAS,QAAQ,CAAE,IAAI;IACrB,OAAO,CAAC,CAAC,SAAS,CAAC,IAAW,CAAC,IAAI,OAAO,IAAI,CAAC,KAAK,KAAK,QAAQ,CAAA;AACnE,CAAC;AAED,SAAS,qBAAqB,CAAE,IAAI,EAAE,KAAK;IACzC,OAAO,CAAC,CAAC,gBAAgB,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,CAAC,CAAA;AAC7C,CAAC;AACD,SAAgB,gBAAgB,CAAE,IAAI,EAAE,KAAK;IAE3C,IAAI,KAAK,GAAkB,EAAE,CAAA;IAE7B,MAAM,WAAW,GAAG,IAAI,CAAC,GAAG,CAAC,aAAa,CAAC,CAAA;IAE3C,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;QACrC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAA;QAE9C,MAAM,IAAI,GAAG,WAAW,CAAC,KAAK,EAAE,CAAA;QAChC,IAAI,IAAI,EAAE;YACR,2CAA2C;YAC3C,IAAI,KAAK,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAG;gBAChF,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA;aAClE;iBAAM;gBACL,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;aACtB;SACF;KACF;IAED,mCAAmC;IACnC,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC,CAAA;IAE3D,yCAAyC;IACzC,0DAA0D;IAC1D,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE;QAC9C,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,EAAE,CAAC,CAAC,CAAA;KACnC;IAED,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE;QACpB,IAAI,IAAI,GAAG,qBAAqB,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC,CAAA;QAE9D,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE;YACxB,IAAI,GAAG,qBAAqB,CAAC,IAAI,EAAE,IAAI,CAAC,CAAA;SACzC;QAED,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;KACvB;SAAM;QACL,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAA;KAC3B;AACH,CAAC;AAxCD,4CAwCC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins/remove-dead-code.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins/remove-dead-code.js new file mode 100644 index 000000000..d108edecf --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins/remove-dead-code.js @@ -0,0 +1,1137 @@ +/* eslint-disable */ +// 修改自: https://github.com/babel/minify/blob/master/packages/babel-plugin-minify-dead-code-elimination/src/index.js +// 主要更改了 `toStatements` 函数,remove if statement 发生在 render JSX 函数时不生成 block statement +const { some } = require("lodash"); +const { markEvalScopes, hasEval } = require("babel-helper-mark-eval-scopes"); +const evaluate = require("babel-helper-evaluate-path"); +function evaluateTruthy(path) { + const res = evaluate(path); + if (res.confident) + return !!res.value; +} +function prevSiblings(path) { + const parentPath = path.parentPath; + const siblings = []; + let key = parentPath.key; + while ((path = parentPath.getSibling(--key)).type) { + siblings.push(path); + } + return siblings; +} +function forEachAncestor(path, callback) { + while ((path = path.parentPath)) { + callback(path); + } +} +function containJSXElement(path) { + let matched = false; + path.traverse({ + JSXElement(p) { + matched = true; + p.stop(); + } + }); + return matched; +} +module.exports = ({ types: t, traverse }) => { + const removeOrVoid = require("babel-helper-remove-or-void")(t); + const shouldRevisit = Symbol("shouldRevisit"); + // this is used for tracking fn params that can be removed + // as traversal takes place from left and + // unused params can be removed only on the right + const markForRemoval = Symbol("markForRemoval"); + const main = { + // remove side effectless statement + ExpressionStatement(path) { + if (path.get("expression").isPure()) { + removeOrVoid(path); + } + }, + Function: { + // Let's take all the vars in a function that are not in the top level scope and hoist them + // with the first var declaration in the top-level scope. This transform in itself may + // not yield much returns (or even can be marginally harmful to size). However it's great + // for taking away statements from blocks that can be only expressions which the `simplify` + // plugin can turn into other things (e.g. if => conditional). + exit(path) { + // This hurts gzip size. + if (!this.optimizeRawSize) { + return; + } + const { node, scope } = path; + const seen = new Set(); + const declars = []; + const mutations = []; + for (const name in scope.bindings) { + const binding = scope.bindings[name]; + if (!binding.path.isVariableDeclarator()) { + continue; + } + const declarPath = binding.path.parentPath; + if (seen.has(declarPath)) { + continue; + } + seen.add(declarPath); + if (declarPath.parentPath.isForInStatement()) { + continue; + } + if (declarPath.parentPath.parentPath.isFunction()) { + continue; + } + if (!declarPath.node || !declarPath.node.declarations) { + continue; + } + const assignmentSequence = []; + for (const declar of declarPath.node.declarations) { + declars.push(declar); + if (declar.init) { + assignmentSequence.push(t.assignmentExpression("=", declar.id, declar.init)); + mutations.push(() => { + declar.init = null; + }); + } + } + if (assignmentSequence.length) { + mutations.push(() => declarPath.replaceWith(t.sequenceExpression(assignmentSequence))); + } + else { + mutations.push(() => removeOrVoid(declarPath)); + } + } + if (declars.length) { + mutations.forEach(f => f()); + for (const statement of node.body.body) { + if (t.isVariableDeclaration(statement)) { + statement.declarations.push(...declars); + return; + } + } + const varDecl = t.variableDeclaration("var", declars); + node.body.body.unshift(varDecl); + } + } + }, + // Remove bindings with no references. + Scope: { + exit(path) { + if (path.node[shouldRevisit]) { + delete path.node[shouldRevisit]; + path.visit(); + } + }, + enter(path) { + if (path.isProgram()) { + return; + } + if (hasEval(path.scope)) { + return; + } + const { scope } = path; + // if the scope is created by a function, we obtain its + // parameter list + const canRemoveParams = path.isFunction() && path.node.kind !== "set"; + const paramsList = canRemoveParams ? path.get("params") : []; + for (let i = paramsList.length - 1; i >= 0; i--) { + const param = paramsList[i]; + if (param.isIdentifier()) { + const binding = scope.bindings[param.node.name]; + if (!binding) + continue; + if (binding.referenced) { + // when the first binding is referenced (right to left) + // exit without marking anything after this + break; + } + binding[markForRemoval] = true; + continue; + } + else if (param.isAssignmentPattern()) { + const left = param.get("left"); + const right = param.get("right"); + if (left.isIdentifier() && right.isPure()) { + const binding = scope.bindings[left.node.name]; + if (binding.referenced) { + // when the first binding is referenced (right to left) + // exit without marking anything after this + break; + } + binding[markForRemoval] = true; + continue; + } + } + // other patterns - assignment, object have side-effects + // and cannot be safely removed + break; + } + for (const name in scope.bindings) { + const binding = scope.bindings[name]; + if (!binding.referenced && binding.kind !== "module") { + if (binding.kind === "param" && + (this.keepFnArgs || !binding[markForRemoval])) { + continue; + } + else if (binding.path.isVariableDeclarator()) { + const declaration = binding.path.parentPath; + const maybeBlockParent = declaration.parentPath; + if (maybeBlockParent && + maybeBlockParent.isForXStatement({ + left: declaration.node + })) { + // Can't remove if in a for-in/for-of/for-await statement `for (var x in wat)`. + continue; + } + } + else if (!scope.isPure(binding.path.node)) { + // TODO: AssignmentPattern are marked as impure and unused ids aren't removed yet + continue; + } + else if (binding.path.isFunctionExpression() || + binding.path.isClassExpression()) { + // `bar(function foo() {})` foo is not referenced but it's used. + continue; + } + else if ( + // ClassDeclaration has binding in two scopes + // 1. The scope in which it is declared + // 2. The class's own scope + binding.path.isClassDeclaration() && + binding.path === scope.path) { + continue; + } + const mutations = []; + let bail = false; + // Make sure none of the assignments value is used + binding.constantViolations.forEach(p => { + if (bail || p === binding.path) { + return; + } + if (!p.parentPath.isExpressionStatement()) { + bail = true; + } + if (p.isAssignmentExpression()) { + if (t.isArrayPattern(p.node.left) || + t.isObjectPattern(p.node.left)) { + bail = true; + } + else if (p.get("right").isPure()) { + mutations.push(() => removeOrVoid(p)); + } + else { + mutations.push(() => p.replaceWith(p.get("right"))); + } + } + }); + if (bail) { + continue; + } + if (binding.path.isVariableDeclarator()) { + if (!binding.path.get("id").isIdentifier()) { + // deopt for object and array pattern + continue; + } + // if declarator has some impure init expression + // var x = foo(); + // => foo(); + if (binding.path.node.init && + !scope.isPure(binding.path.node.init) && + binding.path.parentPath.node.declarations) { + // binding path has more than one declarations + if (binding.path.parentPath.node.declarations.length !== 1) { + continue; + } + binding.path.parentPath.replaceWith(binding.path.node.init); + } + else { + updateReferences(binding.path, this); + removeOrVoid(binding.path); + } + } + else { + updateReferences(binding.path, this); + removeOrVoid(binding.path); + } + mutations.forEach(f => f()); + scope.removeBinding(name); + } + else if (binding.constant) { + if (binding.path.isFunctionDeclaration() || + (binding.path.isVariableDeclarator() && + binding.path.get("init").isFunction())) { + const fun = binding.path.isFunctionDeclaration() + ? binding.path + : binding.path.get("init"); + let allInside = true; + for (const ref of binding.referencePaths) { + if (!ref.find(p => p.node === fun.node)) { + allInside = false; + break; + } + } + if (allInside) { + scope.removeBinding(name); + updateReferences(binding.path, this); + removeOrVoid(binding.path); + continue; + } + } + if (binding.references === 1 && + binding.kind !== "param" && + binding.kind !== "module" && + binding.constant) { + let replacement = binding.path.node; + let replacementPath = binding.path; + let isReferencedBefore = false; + const refPath = binding.referencePaths[0]; + if (t.isVariableDeclarator(replacement)) { + const _prevSiblings = prevSiblings(replacementPath); + // traverse ancestors of a reference checking if it's before declaration + forEachAncestor(refPath, ancestor => { + if (_prevSiblings.indexOf(ancestor) > -1) { + isReferencedBefore = true; + } + }); + // deopt if reference is in different scope than binding + // since we don't know if it's sync or async execution + // (i.e. whether value has been assigned to a reference or not) + if (isReferencedBefore && refPath.scope !== binding.scope) { + continue; + } + // simulate hoisting by replacing value + // with undefined if declaration is after reference + replacement = isReferencedBefore + ? t.unaryExpression("void", t.numericLiteral(0), true) + : replacement.init; + // Bail out for ArrayPattern and ObjectPattern + // TODO: maybe a more intelligent approach instead of simply bailing out + if (!replacementPath.get("id").isIdentifier()) { + continue; + } + replacementPath = replacementPath.get("init"); + } + if (!replacement) { + continue; + } + if (!scope.isPure(replacement, true) && !isReferencedBefore) { + continue; + } + let bail = false; + if (replacementPath.isIdentifier()) { + const binding = scope.getBinding(replacement.name); + // the reference should be in the same scope + // and the replacement should be a constant - this is to + // ensure that the duplication of replacement is not affected + // https://github.com/babel/minify/issues/685 + bail = !(binding && + refPath.scope.getBinding(replacement.name) === binding && + binding.constantViolations.length === 0); + } + else { + replacementPath.traverse({ + Function(path) { + path.skip(); + }, + ReferencedIdentifier({ node }) { + if (bail) { + return; + } + const binding = scope.getBinding(node.name); + if (binding && + refPath.scope.getBinding(node.name) === binding) { + bail = binding.constantViolations.length > 0; + } + } + }); + } + if (bail) { + continue; + } + let parent = binding.path.parent; + if (t.isVariableDeclaration(parent)) { + parent = binding.path.parentPath.parent; + } + // 1. Make sure we share the parent with the node. In other words it's lexically defined + // and not in an if statement or otherwise. + // 2. If the replacement is an object then we have to make sure we are not in a loop or a function + // because otherwise we'll be inlining and doing a lot more allocation than we have to + // which would also could affect correctness in that they are not the same reference. + let mayLoop = false; + const sharesRoot = refPath.find(({ node }) => { + if (!mayLoop) { + mayLoop = + t.isWhileStatement(node) || + t.isFor(node) || + t.isFunction(node); + } + return node === parent; + }); + // Anything that inherits from Object. + const isObj = n => t.isFunction(n) || + t.isObjectExpression(n) || + t.isArrayExpression(n); + const isReplacementObj = isObj(replacement) || some(replacement, isObj); + if (!sharesRoot || (isReplacementObj && mayLoop)) { + continue; + } + // check if it's safe to replace + // To solve https://github.com/babel/minify/issues/691 + // Here we bail for property checks using the "in" operator + // This is because - `in` is a side-effect-free operation but the property + // could be deleted between the replacementPath and referencePath + // It is expensive to compute the delete operation and we bail for + // all the binary "in" operations + let inExpression = replacementPath.isBinaryExpression({ + operator: "in" + }); + if (!inExpression) { + replacementPath.traverse({ + Function(path) { + path.skip(); + }, + BinaryExpression(path) { + if (path.node.operator === "in") { + inExpression = true; + path.stop(); + } + } + }); + } + if (inExpression) { + continue; + } + const replaced = replace(binding.referencePaths[0], { + binding, + scope, + replacement, + replacementPath + }); + if (replaced) { + scope.removeBinding(name); + if (binding.path.node) { + removeOrVoid(binding.path); + } + } + } + } + } // end-for-of + } + }, + // Remove unreachable code. + BlockStatement(path) { + const paths = path.get("body"); + let purge = false; + for (let i = 0; i < paths.length; i++) { + const p = paths[i]; + if (!purge && p.isCompletionStatement()) { + purge = true; + continue; + } + if (purge && !canExistAfterCompletion(p)) { + removeOrVoid(p); + } + } + }, + // Double check unreachable code and remove return statements that + // have no semantic meaning + ReturnStatement(path) { + const { node } = path; + if (!path.inList) { + return; + } + // Not last in its block? (See BlockStatement visitor) + if (path.container.length - 1 !== path.key && + !canExistAfterCompletion(path.getSibling(path.key + 1)) && + path.parentPath.isBlockStatement()) { + // This is probably a new oppurtinity by some other transform + // let's call the block visitor on this again before proceeding. + path.parentPath.pushContext(path.context); + path.parentPath.visit(); + path.parentPath.popContext(); + return; + } + if (node.argument) { + return; + } + let noNext = true; + let parentPath = path.parentPath; + while (parentPath && !parentPath.isFunction() && noNext) { + // https://github.com/babel/minify/issues/265 + if (hasLoopParent(parentPath)) { + noNext = false; + break; + } + const nextPath = parentPath.getSibling(parentPath.key + 1); + if (nextPath.node) { + if (nextPath.isReturnStatement()) { + nextPath.pushContext(path.context); + nextPath.visit(); + nextPath.popContext(); + if (parentPath.getSibling(parentPath.key + 1).node) { + noNext = false; + break; + } + } + else { + noNext = false; + break; + } + } + parentPath = parentPath.parentPath; + } + if (noNext) { + removeOrVoid(path); + } + }, + ConditionalExpression(path) { + const { node } = path; + const evaluateTest = evaluateTruthy(path.get("test")); + if (evaluateTest === true) { + path.replaceWith(node.consequent); + } + else if (evaluateTest === false) { + path.replaceWith(node.alternate); + } + }, + SwitchStatement: { + exit(path) { + const discriminantPath = path.get("discriminant"); + const evaluated = evaluate(discriminantPath, { tdz: this.tdz }); + if (!evaluated.confident) + return; + // the simplify transformation might have brought in the previous + // expressions into the switch's test expression and instead of + // bailing out of impure path, we collect the impurities of it's + // a sequence expression and bail out if the primary test itself + // is impure + let beforeTest = []; + if (t.isSequenceExpression(discriminantPath.node)) { + const expressions = discriminantPath.get("expressions"); + const lastExpression = expressions[expressions.length - 1]; + if (!lastExpression.isPure()) { + return; + } + beforeTest = [ + t.expressionStatement(t.sequenceExpression(expressions + .slice(0, expressions.length - 1) + .map(path => path.node))) + ]; + } + else if (!discriminantPath.isPure()) { + return; + } + const discriminant = evaluated.value; + const cases = path.get("cases"); + let matchingCaseIndex = -1; + let defaultCaseIndex = -1; + for (let i = 0; i < cases.length; i++) { + const test = cases[i].get("test"); + // handle default case + if (test.node === null) { + defaultCaseIndex = i; + continue; + } + const testResult = evaluate(test, { + tdz: this.tdz + }); + // if we are not able to deternine a test during + // compile time, we terminate immediately + if (!testResult.confident) + return; + if (testResult.value === discriminant) { + matchingCaseIndex = i; + break; + } + } + let result; + if (matchingCaseIndex === -1) { + if (defaultCaseIndex === -1) { + path.skip(); + path.replaceWithMultiple(extractVars(path)); + return; + } + else { + result = getStatementsUntilBreak(defaultCaseIndex); + } + } + else { + result = getStatementsUntilBreak(matchingCaseIndex); + } + if (result.bail) + return; + // we extract vars from the entire switch statement + // and there will be duplicates which + // will be again removed by DCE + replaceSwitch([ + ...extractVars(path), + ...beforeTest, + ...result.statements + ]); + function getStatementsUntilBreak(start) { + const result = { bail: false, statements: [] }; + for (let i = start; i < cases.length; i++) { + const consequent = cases[i].get("consequent"); + for (let j = 0; j < consequent.length; j++) { + const _isBreaking = isBreaking(consequent[j], path); + if (_isBreaking.bail) { + result.bail = true; + return result; + } + if (_isBreaking.break) { + // compute no more + // exit out of the loop + return result; + } + else { + result.statements.push(consequent[j].node); + } + } + } + return result; + } + function replaceSwitch(statements) { + let isBlockRequired = false; + for (let i = 0; i < statements.length; i++) { + if (t.isVariableDeclaration(statements[i], { kind: "let" })) { + isBlockRequired = true; + break; + } + if (t.isVariableDeclaration(statements[i], { kind: "const" })) { + isBlockRequired = true; + break; + } + } + if (isBlockRequired) { + path.replaceWith(t.BlockStatement(statements)); + } + else { + path.replaceWithMultiple(statements); + } + } + } + }, + WhileStatement(path) { + const test = path.get("test"); + const result = evaluate(test, { tdz: this.tdz }); + if (result.confident && test.isPure() && !result.value) { + path.remove(); + } + }, + ForStatement(path) { + const test = path.get("test"); + if (!test.isPure()) + return; + const result = evaluate(test, { tdz: this.tdz }); + if (result.confident) { + if (result.value) { + test.remove(); + } + else { + const init = path.get("init"); + if (init.node && !init.isPure()) { + path.replaceWith(init); + } + else { + path.remove(); + } + } + } + }, + DoWhileStatement(path) { + const test = path.get("test"); + const result = evaluate(test, { tdz: this.tdz }); + if (result.confident && test.isPure() && !result.value) { + const body = path.get("body"); + if (body.isBlockStatement()) { + const stmts = body.get("body"); + for (const stmt of stmts) { + const _isBreaking = isBreaking(stmt, path); + if (_isBreaking.bail || _isBreaking.break) + return; + const _isContinuing = isContinuing(stmt, path); + if (_isContinuing.bail || isContinuing.continue) + return; + } + path.replaceWith(body.node); + } + else if (body.isBreakStatement()) { + const _isBreaking = isBreaking(body, path); + if (_isBreaking.bail) + return; + if (_isBreaking.break) + path.remove(); + } + else if (body.isContinueStatement()) { + return; + } + else { + path.replaceWith(body.node); + } + } + }, + // Join assignment and definition when in sequence. + // var x; x = 1; -> var x = 1; + AssignmentExpression(path) { + if (!path.get("left").isIdentifier() || + !path.parentPath.isExpressionStatement()) { + return; + } + const prev = path.parentPath.getSibling(path.parentPath.key - 1); + if (!(prev && prev.isVariableDeclaration())) { + return; + } + const declars = prev.node.declarations; + if (declars.length !== 1 || + declars[0].init || + declars[0].id.name !== path.get("left").node.name) { + return; + } + declars[0].init = path.node.right; + removeOrVoid(path); + }, + // Remove named function expression name. While this is dangerous as it changes + // `function.name` all minifiers do it and hence became a standard. + FunctionExpression(path) { + if (!this.keepFnName) { + removeUnreferencedId(path); + } + }, + // remove class names + ClassExpression(path) { + if (!this.keepClassName) { + removeUnreferencedId(path); + } + }, + // Put the `var` in the left if feasible. + ForInStatement(path) { + const left = path.get("left"); + if (!left.isIdentifier()) { + return; + } + const binding = path.scope.getBinding(left.node.name); + if (!binding) { + return; + } + if (binding.scope.getFunctionParent() !== path.scope.getFunctionParent()) { + return; + } + if (!binding.path.isVariableDeclarator()) { + return; + } + if (binding.path.parentPath.parentPath.isForInStatement({ + left: binding.path.parent + })) { + return; + } + // If it has company then it's probably more efficient to keep. + if (binding.path.parent.declarations.length > 1) { + return; + } + // meh + if (binding.path.node.init) { + return; + } + removeOrVoid(binding.path); + path.node.left = t.variableDeclaration("var", [ + t.variableDeclarator(left.node) + ]); + binding.path = path.get("left").get("declarations")[0]; + } + }; + return { + name: "minify-dead-code-elimination", + visitor: { + IfStatement: { + exit(path, { opts: { tdz = false } = {} }) { + const consequent = path.get("consequent"); + const alternate = path.get("alternate"); + const test = path.get("test"); + const evalResult = evaluate(test, { tdz }); + const isPure = test.isPure(); + const replacements = []; + const isRenderFunction = !!path.findParent(p => p.isClassMethod() && t.isIdentifier(p.node.key) && p.node.key.name.startsWith('render')) && containJSXElement(path); + if (evalResult.confident && !isPure && test.isSequenceExpression()) { + replacements.push(t.expressionStatement(extractSequenceImpure(test))); + } + // we can check if a test will be truthy 100% and if so then we can inline + // the consequent and completely ignore the alternate + // + // if (true) { foo; } -> { foo; } + // if ("foo") { foo; } -> { foo; } + // + if (evalResult.confident && evalResult.value) { + path.replaceWithMultiple([ + ...replacements, + ...toStatements(consequent, isRenderFunction), + ...extractVars(alternate) + ]); + return; + } + // we can check if a test will be falsy 100% and if so we can inline the + // alternate if there is one and completely remove the consequent + // + // if ("") { bar; } else { foo; } -> { foo; } + // if ("") { bar; } -> + // + if (evalResult.confident && !evalResult.value) { + if (alternate.node) { + path.replaceWithMultiple([ + ...replacements, + ...toStatements(alternate, isRenderFunction), + ...extractVars(consequent) + ]); + return; + } + else { + path.replaceWithMultiple([ + ...replacements, + ...extractVars(consequent) + ]); + } + } + // remove alternate blocks that are empty + // + // if (foo) { foo; } else {} -> if (foo) { foo; } + // + if (alternate.isBlockStatement() && !alternate.node.body.length) { + alternate.remove(); + // For if-statements babel-traverse replaces with an empty block + path.node.alternate = null; + } + // if the consequent block is empty turn alternate blocks into a consequent + // and flip the test + // + // if (foo) {} else { bar; } -> if (!foo) { bar; } + // + if (consequent.isBlockStatement() && + !consequent.node.body.length && + alternate.isBlockStatement() && + alternate.node.body.length) { + consequent.replaceWith(alternate.node); + alternate.remove(); + // For if-statements babel-traverse replaces with an empty block + path.node.alternate = null; + test.replaceWith(t.unaryExpression("!", test.node, true)); + } + } + }, + EmptyStatement(path) { + if (path.parentPath.isBlockStatement() || path.parentPath.isProgram()) { + path.remove(); + } + }, + Program: { + exit(path, { opts: { + // set defaults + optimizeRawSize = false, keepFnName = false, keepClassName = false, keepFnArgs = false, tdz = false } = {} } = {}) { + (traverse.clearCache || traverse.cache.clear)(); + path.scope.crawl(); + markEvalScopes(path); + // We need to run this plugin in isolation. + path.traverse(main, { + functionToBindings: new Map(), + optimizeRawSize, + keepFnName, + keepClassName, + keepFnArgs, + tdz + }); + } + } + } + }; + function toStatements(path, isRenderFunction) { + const { node } = path; + if (path.isBlockStatement()) { + if (isRenderFunction) { + return node.body; + } + let hasBlockScoped = false; + for (let i = 0; i < node.body.length; i++) { + const bodyNode = node.body[i]; + if (t.isBlockScoped(bodyNode)) { + hasBlockScoped = true; + } + } + if (!hasBlockScoped) { + return node.body; + } + } + return [node]; + } + // Extracts vars from a path + // Useful for removing blocks or paths that can contain + // variable declarations inside them + // Note: + // drops are inits + // extractVars({ var x = 5, y = x }) => var x, y; + function extractVars(path) { + const declarators = []; + if (path.isVariableDeclaration({ kind: "var" })) { + for (const decl of path.node.declarations) { + const bindingIds = Object.keys(t.getBindingIdentifiers(decl.id)); + declarators.push(...bindingIds.map(name => t.variableDeclarator(t.identifier(name)))); + } + } + else { + path.traverse({ + VariableDeclaration(varPath) { + if (!varPath.isVariableDeclaration({ kind: "var" })) + return; + if (!isSameFunctionScope(varPath, path)) + return; + for (const decl of varPath.node.declarations) { + const bindingIds = Object.keys(t.getBindingIdentifiers(decl.id)); + declarators.push(...bindingIds.map(name => t.variableDeclarator(t.identifier(name)))); + } + } + }); + } + if (declarators.length <= 0) + return []; + return [t.variableDeclaration("var", declarators)]; + } + function replace(path, options) { + const { replacement, replacementPath, scope, binding } = options; + // Same name, different binding. + if (scope.getBinding(path.node.name) !== binding) { + return; + } + // We don't want to move code around to different scopes because: + // 1. Original bindings that is referenced could be shadowed + // 2. Moving defintions to potentially hot code is bad + if (scope !== path.scope) { + if (t.isClass(replacement) || t.isFunction(replacement)) { + return; + } + let bail = false; + traverse(replacement, { + Function(path) { + if (bail) { + return; + } + bail = true; + path.stop(); + } + }, scope); + if (bail) { + return; + } + } + // Avoid recursion. + if (path.find(({ node }) => node === replacement)) { + return; + } + // https://github.com/babel/minify/issues/611 + // this is valid only for FunctionDeclaration where we convert + // function declaration to expression in the next step + if (replacementPath.isFunctionDeclaration()) { + const fnName = replacementPath.get("id").node.name; + for (let name in replacementPath.scope.bindings) { + if (name === fnName) { + return; + } + } + } + // https://github.com/babel/minify/issues/130 + if (!t.isExpression(replacement)) { + t.toExpression(replacement); + } + // We don't remove fn name here, we let the FnExpr & ClassExpr visitors + // check its references and remove unreferenced ones + // if (t.isFunction(replacement)) { + // replacement.id = null; + // } + path.replaceWith(replacement); + return true; + } + function updateReferences(fnToDeletePath) { + if (!fnToDeletePath.isFunction()) { + return; + } + fnToDeletePath.traverse({ + ReferencedIdentifier(path) { + const { node, scope } = path; + const binding = scope.getBinding(node.name); + if (!binding || + !binding.path.isFunction() || + binding.scope === scope || + !binding.constant) { + return; + } + const index = binding.referencePaths.indexOf(path); + if (index === -1) { + return; + } + binding.references--; + binding.referencePaths.splice(index, 1); + if (binding.references === 0) { + binding.referenced = false; + } + if (binding.references <= 1 && binding.scope.path.node) { + binding.scope.path.node[shouldRevisit] = true; + } + } + }); + } + function removeUnreferencedId(path) { + const id = path.get("id").node; + if (!id) { + return; + } + const { node, scope } = path; + const binding = scope.getBinding(id.name); + // Check if shadowed or is not referenced. + if (binding && (binding.path.node !== node || !binding.referenced)) { + node.id = null; + } + } + // path1 -> path2 + // is path1 an ancestor of path2 + function isAncestor(path1, path2) { + return !!path2.findParent(parent => parent === path1); + } + function isSameFunctionScope(path1, path2) { + return path1.scope.getFunctionParent() === path2.scope.getFunctionParent(); + } + function isBreaking(stmt, path) { + return isControlTransfer(stmt, path, "break"); + } + function isContinuing(stmt, path) { + return isControlTransfer(stmt, path, "continue"); + } + // tells if a "stmt" is a break/continue statement + function isControlTransfer(stmt, path, control = "break") { + const { [control]: type } = { + break: "BreakStatement", + continue: "ContinueStatement" + }; + if (!type) { + throw new Error("Can only handle break and continue statements"); + } + const checker = `is${type}`; + if (stmt[checker]()) { + return _isControlTransfer(stmt, path); + } + let isTransferred = false; + let result = { + [control]: false, + bail: false + }; + stmt.traverse({ + [type](cPath) { + // if we already detected a break/continue statement, + if (isTransferred) + return; + result = _isControlTransfer(cPath, path); + if (result.bail || result[control]) { + isTransferred = true; + } + } + }); + return result; + function _isControlTransfer(cPath, path) { + const label = cPath.get("label"); + if (label.node !== null) { + // labels are fn scoped and not accessible by inner functions + // path is the switch statement + if (!isSameFunctionScope(path, cPath)) { + // we don't have to worry about this break statement + return { + break: false, + bail: false + }; + } + // here we handle the break labels + // if they are outside switch, we bail out + // if they are within the case, we keep them + let labelPath; + if (path.scope.getLabel) { + labelPath = getLabel(label.node.name, path); + } + else { + labelPath = path.scope.getBinding(label.node.name).path; + } + const _isAncestor = isAncestor(labelPath, path); + return { + bail: _isAncestor, + [control]: _isAncestor + }; + } + // set the flag that it is indeed breaking + let isCTransfer = true; + // this flag is to capture + // switch(0) { case 0: while(1) if (x) break; } + let possibleRunTimeControlTransfer = false; + // and compute if it's breaking the correct thing + let parent = cPath.parentPath; + while (parent !== stmt.parentPath) { + // loops and nested switch cases + if (parent.isLoop() || parent.isSwitchCase()) { + // invalidate all the possible runtime breaks captured + // while (1) { if (x) break; } + possibleRunTimeControlTransfer = false; + // and set that it's not breaking our switch statement + isCTransfer = false; + break; + } + // + // this is a special case and depends on + // the fact that SwitchStatement is handled in the + // exit hook of the traverse + // + // switch (0) { + // case 0: if (x) break; + // } + // + // here `x` is runtime only. + // in this case, we need to bail out. So we depend on exit hook + // of switch so that, it would have visited the IfStatement first + // before the SwitchStatement and would have removed the + // IfStatement if it was a compile time determined + // + if (parent.isIfStatement()) { + possibleRunTimeControlTransfer = true; + } + parent = parent.parentPath; + } + return { + [control]: possibleRunTimeControlTransfer || isCTransfer, + bail: possibleRunTimeControlTransfer + }; + } + } + // things that are hoisted + function canExistAfterCompletion(path) { + return (path.isFunctionDeclaration() || + path.isVariableDeclaration({ kind: "var" })); + } + function getLabel(name, _path) { + let label, path = _path; + do { + label = path.scope.getLabel(name); + if (label) { + return label; + } + } while ((path = path.parentPath)); + return null; + } + function hasLoopParent(path) { + let parent = path; + do { + if (parent.isLoop()) { + return true; + } + } while ((parent = parent.parentPath)); + return false; + } + function extractSequenceImpure(seq) { + const expressions = seq.get("expressions"); + const result = []; + for (let i = 0; i < expressions.length; i++) { + if (!expressions[i].isPure()) { + result.push(expressions[i].node); + } + } + return t.sequenceExpression(result); + } +}; +//# sourceMappingURL=remove-dead-code.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins/remove-dead-code.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins/remove-dead-code.js.map new file mode 100644 index 000000000..3d9a44730 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/plugins/remove-dead-code.js.map @@ -0,0 +1 @@ +{"version":3,"file":"remove-dead-code.js","sourceRoot":"","sources":["../../../src/plugins/remove-dead-code.js"],"names":[],"mappings":"AAAA,oBAAoB;AACpB,mHAAmH;AACnH,oFAAoF;AACpF,MAAM,EAAE,IAAI,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AACnC,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,+BAA+B,CAAC,CAAC;AAC7E,MAAM,QAAQ,GAAG,OAAO,CAAC,4BAA4B,CAAC,CAAC;AAEvD,SAAS,cAAc,CAAC,IAAI;IAC1B,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC3B,IAAI,GAAG,CAAC,SAAS;QAAE,OAAO,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC;AACxC,CAAC;AAGD,SAAS,YAAY,CAAC,IAAI;IACxB,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IACnC,MAAM,QAAQ,GAAG,EAAE,CAAC;IAEpB,IAAI,GAAG,GAAG,UAAU,CAAC,GAAG,CAAC;IAEzB,OAAO,CAAC,IAAI,GAAG,UAAU,CAAC,UAAU,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE;QACjD,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KACrB;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,SAAS,eAAe,CAAC,IAAI,EAAE,QAA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G;QAChC,MAAM,WAAW,GAAG,GAAG,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;QAC3C,MAAM,MAAM,GAAG,EAAE,CAAC;QAClB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YAC3C,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE;gBAC5B,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;aAClC;SACF;QACD,OAAO,CAAC,CAAC,kBAAkB,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/render.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/render.js new file mode 100644 index 000000000..97b8dc31f --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/render.js @@ -0,0 +1,1395 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const babel_traverse_1 = require("babel-traverse"); +const t = require("babel-types"); +const babel_core_1 = require("babel-core"); +const utils_1 = require("./utils"); +const lodash_1 = require("lodash"); +const jsx_1 = require("./jsx"); +const constant_1 = require("./constant"); +const adapter_1 = require("./adapter"); +const options_1 = require("./options"); +const babel_generator_1 = require("babel-generator"); +const template = require('babel-template'); +function findParents(path, cb) { + const parents = []; + // tslint:disable-next-line:no-conditional-assignment + while (path = path.parentPath) { + if (cb(path)) { + parents.push(path); + } + } + return parents; +} +function isClassDcl(p) { + return p.isClassExpression() || p.isClassDeclaration(); +} +function isChildrenOfJSXAttr(p) { + return !!p.findParent(p => p.isJSXAttribute()); +} +function buildAssignState(pendingState) { + return t.expressionStatement(t.callExpression(t.memberExpression(t.identifier('Object'), t.identifier('assign')), [ + t.memberExpression(t.thisExpression(), t.identifier('data')), + pendingState + ])); +} +class RenderParser { + constructor(renderPath, methods, initState, referencedIdentifiers, usedState, loopStateName, customComponentNames, customComponentData, componentProperies, loopRefs) { + this.classProperties = new Set(); + this.templates = new Map(); + this.jsxDeclarations = new Set(); + this.loopScopes = new Set(); + this.returnedPaths = []; + this.usedThisState = new Set(); + this.loopComponents = new Map(); + this.loopRefIdentifiers = new Map(); + this.reserveStateWords = new Set(['data', 'props']); + this.topLevelIfStatement = new Set(); + this.usedEvents = new Set(); + this.loopCalleeId = new Set(); + this.usedThisProperties = new Set(); + this.incrementCalleeId = utils_1.incrementId(); + this.classComputedState = new Set(); + this.handleJSXElement = (jsxElementPath, func) => { + const parentNode = jsxElementPath.parent; + const parentPath = jsxElementPath.parentPath; + const isJSXChildren = t.isJSXElement(parentNode); + if (!isJSXChildren) { + let statementParent = jsxElementPath.getStatementParent(); + const isReturnStatement = statementParent.isReturnStatement(); + const isFinalReturn = statementParent.getFunctionParent().isClassMethod(); + if (!(statementParent.isVariableDeclaration() || + statementParent.isExpressionStatement())) { + statementParent = statementParent.findParent(s => s.isVariableDeclaration() || s.isExpressionStatement()); + } + if (t.isVariableDeclarator(parentNode)) { + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + // setTemplate(name, path, templates) + name && this.templates.set(name, jsxElementPath.node); + } + } + func({ parentNode, parentPath, statementParent, isReturnStatement, isFinalReturn }); + } + }; + this.isLiteralOrUndefined = (node) => t.isLiteral(node) || t.isIdentifier(node, { name: 'undefined' }); + this.replaceIdWithTemplate = (handleRefId = false) => (path) => { + if (!t.isJSXAttribute(path.parent)) { + path.traverse({ + Identifier: (path) => { + const parentPath = path.parentPath; + if (parentPath.isConditionalExpression() || + parentPath.isLogicalExpression() || + path.isReferencedIdentifier()) { + const name = path.node.name; + if (handleRefId && Object.keys(this.renderScope.getAllBindings()).includes(name)) { + this.addRefIdentifier(path, path.node); + // referencedIdentifiers.add(path.node) + } + if (this.templates.has(name)) { + path.replaceWith(this.templates.get(name)); + } + } + } + }); + } + }; + this.hasStateOrProps = (key) => (p) => t.isObjectProperty(p) && t.isIdentifier(p.key) && p.key.name === key; + this.loopComponentVisitor = { + VariableDeclarator: (path) => { + const id = path.get('id'); + const init = path.get('init'); + const parentPath = path.parentPath; + if (id.isObjectPattern() && + init.isThisExpression() && + parentPath.isVariableDeclaration()) { + const { properties } = id.node; + this.destructStateOrProps('data', path, properties, parentPath); + this.destructStateOrProps('props', path, properties, parentPath); + } + }, + JSXElement: { + enter: (jsxElementPath) => { + this.handleJSXElement(jsxElementPath, (options) => { + this.handleConditionExpr(options, jsxElementPath); + const ifStem = jsxElementPath.findParent(p => p.isIfStatement()); + if (ifStem && ifStem.findParent(utils_1.isArrayMapCallExpression)) { + const block = jsx_1.buildBlockElement(); + block.children = [jsxElementPath.node]; + utils_1.newJSXIfAttr(block, ifStem.node.test); + if (!jsxElementPath.node.openingElement.attributes.some(a => a.name.name === adapter_1.Adapter.if)) { + jsxElementPath.replaceWith(block); + } + } + }); + }, + exit: (jsxElementPath) => { + this.handleJSXElement(jsxElementPath, ({ parentNode, parentPath, statementParent, isFinalReturn }) => { + if (statementParent && statementParent.findParent(p => p === this.renderPath)) { + this.jsxDeclarations.add(statementParent); + } + if (t.isReturnStatement(parentNode)) { + if (!isFinalReturn) { + const callExpr = parentPath.findParent(p => p.isCallExpression()); + if (callExpr.isCallExpression()) { + const callee = callExpr.node.callee; + if (this.loopComponents.has(callExpr)) { + return; + } + if (t.isMemberExpression(callee) && + t.isIdentifier(callee.property) && + callee.property.name === 'map') { + let ary = callee.object; + if (t.isCallExpression(ary) || utils_1.isContainFunction(callExpr.get('callee').get('object'))) { + const variableName = `${constant_1.LOOP_CALLEE}_${this.incrementCalleeId()}`; + callExpr.getStatementParent().insertBefore(utils_1.buildConstVariableDeclaration(variableName, utils_1.setParentCondition(jsxElementPath, ary, true))); + ary = t.identifier(variableName); + } + if (t.isMemberExpression(ary)) { + const id = utils_1.findFirstIdentifierFromMemberExpression(ary); + if (t.isIdentifier(id)) { + this.referencedIdentifiers.add(id); + } + } + else if (t.isIdentifier(ary)) { + const parentCallExpr = callExpr.find(p => p.isCallExpression()); + if (!utils_1.isArrayMapCallExpression(parentCallExpr) && parentCallExpr !== callExpr) { + this.referencedIdentifiers.add(ary); + } + } + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.for, t.jSXExpressionContainer(ary)); + this.loopCalleeId.add(utils_1.findFirstIdentifierFromMemberExpression(callee)); + const [func] = callExpr.node.arguments; + if (t.isFunctionExpression(func) || + t.isArrowFunctionExpression(func)) { + const [item, index] = func.params; + if (t.isIdentifier(item)) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forItem, t.stringLiteral(item.name)); + this.loopScopes.add(item.name); + } + else if (t.isObjectPattern(item)) { + throw utils_1.codeFrameError(item.loc, 'JSX map 循环参数暂时不支持使用 Object pattern 解构。'); + } + else { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forItem, t.stringLiteral('__item')); + } + if (t.isIdentifier(index)) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.forIndex, t.stringLiteral(index.name)); + this.loopScopes.add(index.name); + } + this.loopComponents.set(callExpr, jsxElementPath); + // caller.replaceWith(jsxElementPath.node) + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + // setTemplate(name, path, templates) + name && this.templates.set(name, jsxElementPath.node); + } + } + } + } + } + } + else if (t.isArrowFunctionExpression(parentNode)) { + parentPath.replaceWith(t.arrowFunctionExpression(parentNode.params, t.blockStatement([ + t.returnStatement(jsxElementPath.node) + ]))); + } + }); + } + } + }; + this.renameIfScopeVaribale = (blockStatement) => { + return { + VariableDeclarator: (p) => { + const { id, init } = p.node; + const ifStem = p.parentPath.parentPath.parentPath; + if (!ifStem.isIfStatement() || utils_1.isContainJSXElement(p)) { + return; + } + if (t.isIdentifier(id)) { + if (id.name.startsWith('loopArray') || id.name.startsWith(constant_1.LOOP_CALLEE)) { + this.renderPath.node.body.body.unshift(t.variableDeclaration('let', [t.variableDeclarator(t.identifier(id.name))])); + p.parentPath.replaceWith(template('ID = INIT;')({ ID: t.identifier(id.name), INIT: init })); + } + else { + const newId = this.renderScope.generateDeclaredUidIdentifier('$' + id.name); + blockStatement.scope.rename(id.name, newId.name); + p.parentPath.replaceWith(template('ID = INIT;')({ ID: newId, INIT: init || t.identifier('undefined') })); + } + } + }, + JSXElement: (jsxElementPath) => { + this.handleJSXElement(jsxElementPath, (options) => { + this.handleConditionExpr(options, jsxElementPath); + }); + }, + JSXExpressionContainer: this.replaceIdWithTemplate() + }; + }; + this.jsxElementVisitor = { + JSXElement: (jsxElementPath) => { + this.handleJSXElement(jsxElementPath, (options) => { + this.handleConditionExpr(options, jsxElementPath); + this.handleJSXInIfStatement(jsxElementPath, options); + }); + // handle jsx attrs + jsxElementPath.traverse(this.jsxAttrVisitor); + } + }; + this.jsxAttrVisitor = { + JSXExpressionContainer: (path) => { + if (!isChildrenOfJSXAttr(path)) { + return; + } + const expression = path.get('expression'); + if (expression.isStringLiteral()) { + path.replaceWith(expression); + } + else if (expression.isCallExpression()) { + const node = expression.node; + if (t.isMemberExpression(node.callee) && + t.isIdentifier(node.callee.property) && + node.callee.property.name === 'bind') { + const JSXElement = path.findParent(p => p.isJSXElement()) + .node; + // const JSXAttribute = path.findParent(p => p.isJSXAttribute()) + let bindCalleeName = null; + if (t.isIdentifier(node.callee.object)) { + bindCalleeName = node.callee.object.name; + } + else if (t.isMemberExpression(node.callee.object)) { + if (t.isIdentifier(node.callee.object.property)) { + bindCalleeName = node.callee.object.property.name; + } + } + if (bindCalleeName !== null) { + const attr = path.parentPath.node; + let bindEventName = attr.name.name; + bindEventName = bindEventName.replace(/^bind|^catch/, ''); + const args = expression.get('arguments'); + args.forEach((arg, index) => { + const node = arg.node; + const argName = babel_generator_1.default(node).code; + if (index === 0) { + jsx_1.setJSXAttr(JSXElement, `data-e-${bindEventName}-so`, t.stringLiteral(argName)); + } + else { + let expr = null; + if (t.isIdentifier(node) && path.scope.hasBinding(argName)) { + this.addRefIdentifier(path, node); + expr = t.jSXExpressionContainer(node); + } + else if (t.isMemberExpression(node)) { + const id = utils_1.findFirstIdentifierFromMemberExpression(node); + this.addRefIdentifier(path, id); + expr = t.jSXExpressionContainer(node); + } + else if (node.type === 'NumericLiteral' || t.isStringLiteral(node) || t.isBooleanLiteral(node) || t.isNullLiteral(node)) { + expr = t.jSXExpressionContainer(node); + } + else if (utils_1.hasComplexExpression(arg)) { + const isCookedLoop = JSXElement.openingElement.attributes.some(attr => attr.name.name === adapter_1.Adapter.for); + if (isCookedLoop) { + throw utils_1.codeFrameError(arg.node, '在循环中使用 bind 时,需要声明将此复杂表达式声明为一个变量再放入 bind 参数中。'); + } + else { + const id = utils_1.generateAnonymousState(this.renderScope, arg, this.referencedIdentifiers); + expr = t.jSXExpressionContainer(id); + } + } + else { + expr = t.jSXExpressionContainer(t.identifier(argName)); + } + jsx_1.setJSXAttr(JSXElement, `data-e-${bindEventName}-a-${utils_1.toLetters(index)}`, expr); + } + }); + expression.replaceWith(t.stringLiteral(`${bindCalleeName}`)); + } + } + } + }, + JSXAttribute: (path) => { + const { name, value } = path.node; + let eventShouldBeCatched = false; + const jsxElementPath = path.parentPath.parentPath; + if (t.isJSXIdentifier(name) && jsxElementPath.isJSXElement()) { + const componentName = jsxElementPath.node.openingElement.name.name; + const isThirdPartyKey = name.name === 'taroKey'; + if (name.name === 'key' || isThirdPartyKey) { + if (constant_1.THIRD_PARTY_COMPONENTS.has(componentName) && !isThirdPartyKey) { + return; + } + const jsx = path.findParent(p => p.isJSXElement()); + const loopBlock = jsx.findParent(p => { + if (p.isJSXElement()) { + const element = p.get('openingElement'); + if (element.get('name').isJSXIdentifier({ name: 'block' })) { + const attrs = element.node.attributes; + const hasWXForLoop = attrs.some(attr => t.isJSXIdentifier(attr.name, { name: adapter_1.Adapter.for })); + const hasWXKey = attrs.some(attr => t.isJSXIdentifier(attr.name, { name: adapter_1.Adapter.key })); + return hasWXForLoop && !hasWXKey; + } + } + return false; + }); + if (loopBlock) { + jsx_1.setJSXAttr(loopBlock.node, adapter_1.Adapter.key, value); + path.remove(); + } + else { + path.get('name').replaceWith(t.jSXIdentifier(adapter_1.Adapter.key)); + } + } + else if (name.name.startsWith('on')) { + if (t.isJSXExpressionContainer(value)) { + const methodName = utils_1.findMethodName(value.expression); + methodName && this.usedEvents.add(methodName); + const method = this.methods.get(methodName); + const classDecl = path.findParent(p => p.isClassDeclaration()); + const componentName = jsxElementPath.node.openingElement.name; + // if (method && t.isIdentifier(method.node.key)) { + // this.usedEvents.add(methodName) + // } else if (method === null) { + // this.usedEvents.add(methodName) + // } + if (!babel_generator_1.default(value.expression).code.includes('.bind')) { + path.node.value = t.stringLiteral(`${methodName}`); + } + if (this.methods.has(methodName)) { + eventShouldBeCatched = utils_1.isContainStopPropagation(method); + } + if (classDecl && classDecl.isClassDeclaration()) { + const superClass = utils_1.getSuperClassCode(classDecl); + if (superClass) { + try { + const ast = babel_core_1.transform(superClass.code, options_1.buildBabelTransformOptions()).ast; + babel_traverse_1.default(ast, { + ClassMethod(p) { + if (!p.get('key').isIdentifier({ name: methodName })) { + return; + } + eventShouldBeCatched = utils_1.isContainStopPropagation(method); + }, + ClassProperty(p) { + if (!p.get('key').isIdentifier({ name: methodName })) { + return; + } + eventShouldBeCatched = utils_1.isContainStopPropagation(method); + } + }); + } + catch (error) { + // + } + } + } + if (t.isJSXIdentifier(componentName) && !constant_1.DEFAULT_Component_SET.has(componentName.name)) { + const element = path.parent; + if (process.env.NODE_ENV !== 'test' && adapter_1.Adapter.type !== "alipay" /* alipay */) { + const fnName = `__fn_${name.name}`; + element.attributes = element.attributes.concat([t.jSXAttribute(t.jSXIdentifier(fnName))]); + } + } + } + if (t.isJSXIdentifier(jsxElementPath.node.openingElement.name)) { + const componentName = jsxElementPath.node.openingElement.name.name; + if (adapter_1.Adapter.type === "alipay" /* alipay */) { + let transformName = name.name; + if (constant_1.DEFAULT_Component_SET.has(componentName) && constant_1.ALIPAY_BUBBLE_EVENTS.has(name.name)) { + if (name.name === 'onClick') { + transformName = eventShouldBeCatched ? 'catchTap' : 'onTap'; + } + else { + transformName = `${eventShouldBeCatched ? 'catch' : 'on'}${name.name.slice(2)}`; + } + } + path.node.name = t.jSXIdentifier(transformName); + } + else if (constant_1.DEFAULT_Component_SET.has(componentName)) { + let transformName = `${eventShouldBeCatched ? 'catch' : 'bind'}` + + name.name.slice(2).toLowerCase(); + if (name.name === 'onClick') { + transformName = eventShouldBeCatched ? 'catchtap' : 'bindtap'; + } + path.node.name = t.jSXIdentifier(transformName); + } + else if (constant_1.THIRD_PARTY_COMPONENTS.has(componentName)) { + path.node.name = t.jSXIdentifier('bind' + name.name[2].toLowerCase() + name.name.slice(3)); + } + else { + //@fix + let n = name.name.toLowerCase(); + if (n === 'onclick') + n = 'ontap'; + path.node.name = t.jSXIdentifier('bind' + n.substr(2, n.length - 2)); + } + } + // let transformName = `${eventShouldBeCatched ? 'catch' : 'bind'}` + name.name.slice(2, name.name.length) + // transformName = eventShouldBeCatched + // ? CATCH_EVENT_MAP.get(name.name)! + // : BIND_EVENT_MAP.get(name.name)! + } + else if (/^render[A-Z]/.test(name.name) && !constant_1.DEFAULT_Component_SET.has(componentName)) { + if (!t.isJSXExpressionContainer(value)) { + throw utils_1.codeFrameError(value, '以 render 开头的 props 只能传入包含一个 JSX 元素的 JSX 表达式。'); + } + const expression = value.expression; + if (!t.isJSXElement(expression)) { + throw utils_1.codeFrameError(value, '以 render 开头的 props 只能传入包含一个 JSX 元素的 JSX 表达式。'); + } + const slotName = utils_1.getSlotName(name.name); + const slot = lodash_1.cloneDeep(expression); + jsx_1.setJSXAttr(slot, 'slot', t.stringLiteral(slotName)); + jsxElementPath.node.children.push(slot); + path.remove(); + } + } + }, + Identifier: (path) => { + if (!isChildrenOfJSXAttr(path)) { + return; + } + if (!path.isReferencedIdentifier()) { + return; + } + const parentPath = path.parentPath; + if (parentPath.isConditionalExpression() || + parentPath.isLogicalExpression() || + parentPath.isJSXExpressionContainer() || + parentPath.isBinaryExpression() || + this.renderScope.hasOwnBinding(path.node.name)) { + this.addRefIdentifier(path, path.node); + } + }, + MemberExpression: { + exit: (path) => { + const { object, property } = path.node; + if (!path.isReferencedMemberExpression()) { + return; + } + if (!t.isThisExpression(object)) { + return; + } + const reserves = new Set([ + 'data', + 'props', + ...this.methods.keys() + ]); + if (t.isIdentifier(property) || t.isMemberExpression(property)) { + const id = t.isIdentifier(property) ? property : utils_1.findFirstIdentifierFromMemberExpression(property); + if (reserves.has(id.name)) { + return; + } + const jsxAttr = path.findParent(p => p.isJSXAttribute()); + if (jsxAttr && t.isJSXIdentifier(jsxAttr.node.name) && jsxAttr.node.name.name.startsWith('on')) { + return; + } + if (t.isIdentifier(id)) { + this.referencedIdentifiers.add(id); + this.usedThisProperties.add(id.name); + } + } + }, + enter: (path) => { + if (!isChildrenOfJSXAttr(path)) { + return; + } + if (!path.isReferencedMemberExpression() || path.parentPath.isMemberExpression()) { + return; + } + const { object, property } = path.node; + if (t.isMemberExpression(object) && + t.isThisExpression(object.object) && + t.isIdentifier(object.property, { name: 'data' })) { + if (t.isIdentifier(property)) { + this.usedThisState.add(property.name); + } + else if (t.isMemberExpression(property)) { + const id = utils_1.findFirstIdentifierFromMemberExpression(property); + if (id && this.renderScope.hasBinding(id.name)) { + this.usedThisState.add(id.name); + } + } + return; + } + const code = babel_generator_1.default(path.node).code; + if (code.includes('this.$router.params') && t.isIdentifier(property)) { + const name = this.renderScope.generateUid(property.name); + const dcl = utils_1.buildConstVariableDeclaration(name, path.node); + this.renderPath.node.body.body.unshift(dcl); + path.replaceWith(t.identifier(name)); + } + const parentPath = path.parentPath; + const id = utils_1.findFirstIdentifierFromMemberExpression(path.node); + if (t.isThisExpression(id)) { + return; + } + if (parentPath.isConditionalExpression() || + parentPath.isLogicalExpression() || + parentPath.isJSXExpressionContainer() || + parentPath.isBinaryExpression() || + (this.renderScope.hasOwnBinding(id.name))) { + this.addRefIdentifier(path, id); + } + } + }, + ArrowFunctionExpression: (path) => { + if (!isChildrenOfJSXAttr(path)) { + return; + } + const uid = path.scope.generateUid('_anonymous_function_'); + const c = t.classProperty(t.identifier(uid), path.node); + this.classProperties.add(c); + } + }; + this.visitors = Object.assign({ VariableDeclarator: (path) => { + const init = path.get('init'); + const id = path.get('id'); + const ifStem = init.findParent(p => p.isIfStatement()); + if (ifStem && init.node === null) { + init.replaceWith(t.identifier('undefined')); + } + let isDerivedFromState = false; + if (init.isMemberExpression()) { + const object = init.get('object'); + if (object.isMemberExpression() && object.get('object').isThisExpression() && object.get('property').isIdentifier({ name: 'data' })) { + isDerivedFromState = true; + } + if (object.isThisExpression() && init.get('property').isIdentifier({ name: 'data' })) { + isDerivedFromState = true; + } + } + if (!isDerivedFromState) { + const errMsg = 'Warning: render 函数定义一个不从 this.data 解构或赋值而来的变量,此变量又与 this.data 下的变量重名可能会导致无法渲染。'; + if (id.isIdentifier()) { + const name = id.node.name; + if (this.initState.has(name)) { + // tslint:disable-next-line + console.log(utils_1.codeFrameError(id.node, errMsg).message); + } + } + if (id.isObjectPattern()) { + const { properties } = id.node; + for (const p of properties) { + if (t.isIdentifier(p)) { + if (this.initState.has(p.name)) { + // tslint:disable-next-line + console.log(utils_1.codeFrameError(id.node, errMsg).message); + } + } + if (t.isSpreadProperty(p) && t.isIdentifier(p.argument)) { + if (this.initState.has(p.argument.name)) { + // tslint:disable-next-line + console.log(utils_1.codeFrameError(id.node, errMsg).message); + } + } + } + } + } + }, JSXEmptyExpression(path) { + const parent = path.parentPath; + if (path.parentPath.isJSXExpressionContainer()) { + parent.remove(); + } + }, + NullLiteral(path) { + const statementParent = path.getStatementParent(); + if (statementParent && statementParent.isReturnStatement() && !t.isBinaryExpression(path.parent) && !isChildrenOfJSXAttr(path)) { + path.replaceWith(t.jSXElement(t.jSXOpeningElement(t.jSXIdentifier('view'), []), undefined, [], true)); + } + }, ReturnStatement: (path) => { + const parentPath = path.parentPath; + if (parentPath.parentPath.isClassMethod() || + (parentPath.parentPath.isIfStatement() && parentPath.parentPath.parentPath.isClassMethod())) { + this.replaceIdWithTemplate()(path); + } + } }, this.jsxElementVisitor, { JSXExpressionContainer: this.replaceIdWithTemplate(true) }); + /** + * jsxDeclarations, + * renderScope, + * methods, + * loopScopes, + * initState, + * templates + */ + this.handleLoopComponents = () => { + const loopArrayId = utils_1.incrementId(); + const replaceQueue = []; + let hasLoopRef = false; + this.loopComponents.forEach((component, callee) => { + if (!callee.isCallExpression()) { + return; + } + for (const dcl of this.jsxDeclarations) { + const isChildren = dcl && dcl.findParent(d => d === callee); + if (isChildren) { + this.jsxDeclarations.delete(dcl); + dcl.remove(); + } + } + const blockStatementPath = component.findParent(p => p.isBlockStatement()); + const body = blockStatementPath.node.body; + let loopRefComponent; + this.loopRefs.forEach((ref, jsx) => { + if (ref.component.findParent(p => p === component)) { + loopRefComponent = jsx; + } + }); + if (this.loopRefs.has(component.node) || loopRefComponent) { + hasLoopRef = true; + const ref = this.loopRefs.get(component.node) || this.loopRefs.get(loopRefComponent); + const [func] = callee.node.arguments; + let indexId = null; + if (t.isFunctionExpression(func) || t.isArrowFunctionExpression(func)) { + const params = func.params; + indexId = params[1]; + } + if (indexId === null || !t.isIdentifier(indexId)) { + throw utils_1.codeFrameError(component.node, '在循环中使用 ref 必须暴露循环的第二个参数 `index`'); + } + const id = typeof ref.id === 'string' ? t.binaryExpression('+', t.stringLiteral(ref.id), indexId) : ref.id; + const refDeclName = '__ref'; + const args = [ + t.identifier('__scope'), + t.binaryExpression('+', t.stringLiteral('#'), id) + ]; + if (ref.type === 'component') { + args.push(t.stringLiteral('component')); + } + const callGetElementById = t.callExpression(t.identifier(constant_1.GEL_ELEMENT_BY_ID), args); + const refDecl = utils_1.buildConstVariableDeclaration(refDeclName, process.env.NODE_ENV === 'test' ? callGetElementById : t.logicalExpression('&&', t.identifier('__scope'), t.logicalExpression('&&', t.identifier('__runloopRef'), callGetElementById))); + const callRef = t.callExpression(ref.fn, [t.identifier(refDeclName)]); + const callRefFunc = t.expressionStatement(process.env.NODE_ENV === 'test' ? callRef : t.logicalExpression('&&', t.identifier(refDeclName), callRef)); + body.push(refDecl, callRefFunc); + } + let stateToBeAssign = new Set(lodash_1.difference(Object.keys(blockStatementPath.scope.getAllBindings()), Object.keys(this.renderScope.getAllBindings())).filter(i => { + return !this.methods.has(i); + }) + .filter(i => !this.loopScopes.has(i)) + .filter(i => !this.initState.has(i)) + .filter(i => !this.templates.has(i)) + .filter(i => !i.includes('.')) + .filter(i => i !== constant_1.MAP_CALL_ITERATOR)); + if (body.length > 1) { + const [func] = callee.node.arguments; + if (t.isFunctionExpression(func) || t.isArrowFunctionExpression(func)) { + const [item] = func.params; + const parents = findParents(callee, (p) => utils_1.isArrayMapCallExpression(p)); + const iterators = new Set([item.name, ...parents + .map((p) => lodash_1.get(p, 'node.arguments[0].params[0].name', '')) + .filter(Boolean)]); + for (const [index, statement] of body.entries()) { + if (t.isVariableDeclaration(statement)) { + for (const dcl of statement.declarations) { + if (t.isIdentifier(dcl.id)) { + const name = dcl.id.name; + if (name.startsWith(constant_1.LOOP_STATE) || + name.startsWith(constant_1.LOOP_CALLEE)) { + stateToBeAssign.add(name); + dcl.id = t.identifier(name); + } + } + } + } + if (t.isReturnStatement(statement)) { + body.splice(index, 1); + } + } + stateToBeAssign.forEach(s => this.loopRefIdentifiers.set(s, callee)); + const properties = Array.from(stateToBeAssign).map(state => t.objectProperty(t.identifier(state), t.identifier(state))); + // tslint:disable-next-line:no-inner-declarations + function replaceOriginal(path, parent, name) { + if (path.isReferencedIdentifier() && + iterators.has(name) && + !(t.isMemberExpression(parent) && t.isIdentifier(parent.property, { name: constant_1.LOOP_ORIGINAL })) && + !(t.isMemberExpression(parent) && t.isIdentifier(parent.property) && (parent.property.name.startsWith(constant_1.LOOP_STATE) || parent.property.name.startsWith(constant_1.LOOP_CALLEE)))) { + path.replaceWith(t.memberExpression(t.identifier(name), t.identifier(constant_1.LOOP_ORIGINAL))); + } + } + const bodyPath = callee.get('arguments')[0].get('body'); + bodyPath.traverse({ + Identifier(path) { + const name = path.node.name; + const parent = path.parent; + replaceOriginal(path, parent, name); + } + }); + const replacements = new Set(); + component.traverse({ + JSXExpressionContainer: this.replaceIdWithTemplate(), + Identifier: (path) => { + const name = path.node.name; + const parent = path.parent; + const parentCallExpr = path.findParent(p => p.isCallExpression()); + if (replacements.has(parent) || (this.renderScope.hasOwnBinding(name) && + (this.loopCalleeId.has(path.node) || parentCallExpr && this.loopCalleeId.has(parentCallExpr.node)))) { + return; + } + if (stateToBeAssign.has(name) && path.isReferencedIdentifier()) { + if (t.isMemberExpression(parent) && t.isIdentifier(parent.property, { name: 'map' })) { + const grandParentPath = path.parentPath.parentPath; + if (grandParentPath.isCallExpression() && this.loopComponents.has(grandParentPath)) { + return; + } + } + const replacement = t.memberExpression(t.identifier(item.name), path.node); + path.replaceWith(replacement); + replacements.add(replacement); + } + else { + replaceOriginal(path, parent, name); + } + }, + MemberExpression(path) { + const { object, property } = path.node; + if (t.isThisExpression(object) && t.isIdentifier(property, { name: 'data' })) { + if (path.parentPath.isMemberExpression() && path.parentPath.parentPath.isMemberExpression()) { + // tslint:disable-next-line + console.warn(utils_1.codeFrameError(path.parentPath.parentPath.node, `在循环中使用 this.data.xx.xx 可能会存在问题,请给 xx 起一个别名,例如 const { xx } = this.data`)); + } + } + } + }); + const originalProp = t.objectProperty(t.identifier(constant_1.LOOP_ORIGINAL), t.memberExpression(t.identifier(item.name), t.identifier(constant_1.LOOP_ORIGINAL))); + properties.push(originalProp); + body.unshift(t.expressionStatement(t.assignmentExpression('=', t.identifier(item.name), t.objectExpression([ + t.objectProperty(t.identifier(constant_1.LOOP_ORIGINAL), t.callExpression(t.identifier(constant_1.INTERNAL_GET_ORIGNAL), [t.identifier(item.name)])) + ])))); + const returnStatement = t.returnStatement(properties.length ? t.objectExpression(properties) : item); + const parentCallee = callee.findParent(c => utils_1.isArrayMapCallExpression(c)); + if (utils_1.isArrayMapCallExpression(parentCallee)) { + const [func] = parentCallee.node.arguments; + const { object } = callee.node.callee; + if (t.isFunctionExpression(func) || t.isArrowFunctionExpression(func)) { + const funcBody = func.body; + if (t.isBlockStatement(funcBody)) { + if (t.isIdentifier(object) || t.isMemberExpression(object)) { + const variableName = `${constant_1.LOOP_CALLEE}_${this.incrementCalleeId()}`; + funcBody.body.splice(funcBody.body.length - 1, 0, utils_1.buildConstVariableDeclaration(variableName, utils_1.setParentCondition(component, callee.node, true))); + const iterator = func.params[0]; + component.node.openingElement.attributes.forEach(attr => { + if (attr.name.name === adapter_1.Adapter.for && t.isIdentifier(iterator)) { + attr.value = t.jSXExpressionContainer(t.memberExpression(iterator, t.identifier(variableName))); + } + }); + } + else { + throw utils_1.codeFrameError(object.loc, '多层循环中循环的数组只能是一个变量或成员表达式'); + } + } + } + body.push(returnStatement); + } + else { + body.push(returnStatement); + const stateName = 'loopArray' + loopArrayId(); + this.loopStateName.forEach((newName, callExpr) => { + if (callExpr === callee) { + const classBody = this.renderPath.parent; + for (const property of classBody.body) { + if (t.isClassProperty(property) && property.key.name === '$dynamicComponents') { + const objects = property.value; + for (const objProp of objects.properties) { + if (t.isObjectProperty(objProp) && t.isIdentifier(objProp.key, { name: newName })) { + const func = objProp.value; + func.body.body[0] = utils_1.buildConstVariableDeclaration('stateName', t.stringLiteral(stateName)); + } + } + } + } + } + }); + // setJSXAttr(returned, Adapter.for, t.identifier(stateName)) + this.addRefIdentifier(callee, t.identifier(stateName)); + // this.referencedIdentifiers.add(t.identifier(stateName)) + jsx_1.setJSXAttr(component.node, adapter_1.Adapter.for, t.jSXExpressionContainer(t.identifier(stateName))); + const returnBody = this.renderPath.node.body.body; + const ifStem = callee.findParent(p => p.isIfStatement()); + // @TEST + if (ifStem && ifStem.isIfStatement()) { + const consequent = ifStem.get('consequent'); + if (consequent.isBlockStatement()) { + const assignment = t.expressionStatement(t.assignmentExpression('=', t.identifier(stateName), utils_1.setParentCondition(component, callee.node, true))); + returnBody.unshift(t.variableDeclaration('let', [t.variableDeclarator(t.identifier(stateName))])); + consequent.node.body.push(assignment); + } + } + else { + const decl = utils_1.buildConstVariableDeclaration(stateName, utils_1.setParentCondition(component, callee.node, true)); + returnBody.push(decl); + } + } + } + } + replaceQueue.push(() => { + const statement = component.getStatementParent(); + callee.replaceWith(statement.isReturnStatement() + ? statement.get('argument').node + : component.node); + }); + }); + if (hasLoopRef) { + const scopeDecl = template('const __scope = this.$scope')(); + this.renderPath.node.body.body.unshift(scopeDecl); + } + replaceQueue.forEach(func => func()); + }; + this.setReserveWord = (word) => { + const binding = this.renderScope.getOwnBinding(word); + let hasStateId = false; + if (binding) { + const path = binding.path; + const id = path.get('id'); + const init = path.get('init'); + if (init.isThisExpression()) { + return hasStateId; + } + if (id.isObjectPattern()) { + hasStateId = id.node.properties.some(p => { + return (t.isObjectProperty(p) && t.isIdentifier(p.key, { name: word })) + || (t.isRestProperty(p) && t.isIdentifier(p.argument, { name: word })); + }); + } + else if (id.isIdentifier({ name: word })) { + hasStateId = true; + } + if (hasStateId) { + this.referencedIdentifiers.add(t.identifier(word)); + } + } + if (hasStateId) { + this.reserveStateWords.delete(word); + } + }; + this.renderPath = renderPath; + this.methods = methods; + this.initState = initState; + this.referencedIdentifiers = referencedIdentifiers; + this.loopStateName = loopStateName; + this.usedState = usedState; + this.customComponentNames = customComponentNames; + this.customComponentData = customComponentData; + this.componentProperies = componentProperies; + this.loopRefs = loopRefs; + const renderBody = renderPath.get('body'); + this.renderScope = renderBody.scope; + const [, error] = renderPath.node.body.body.filter(s => t.isReturnStatement(s)); + if (error) { + throw utils_1.codeFrameError(error.loc, 'render 函数顶级作用域暂时只支持一个 return'); + } + renderBody.traverse(this.loopComponentVisitor); + this.handleLoopComponents(); + renderBody.traverse(this.visitors); + this.setOutputTemplate(); + this.checkDuplicateName(); + this.removeJSXStatement(); + this.setUsedState(); + this.setPendingState(); + this.setCustomEvent(); + this.createData(); + this.setProperies(); + this.setLoopRefFlag(); + } + handleConditionExpr({ parentNode, parentPath, statementParent }, jsxElementPath) { + if (parentPath.isObjectProperty()) { + const value = parentPath.get('value'); + if (value !== jsxElementPath) { + return; + } + if (!parentPath.parentPath.isObjectExpression()) { + return; + } + const properties = parentPath.parentPath.get('properties'); + if (!parentPath.parentPath.parentPath.isMemberExpression()) { + return; + } + const rval = parentPath.parentPath.parentPath.get('property'); + if (!rval || !rval.node || !Array.isArray(properties)) { + return; + } + const children = properties.map(p => p.node).map((p, index) => { + const block = jsx_1.buildBlockElement(); + const tester = t.binaryExpression('===', p.key, rval.node); + block.children = [t.jSXExpressionContainer(p.value)]; + if (index === 0) { + utils_1.newJSXIfAttr(block, tester); + } + else { + jsx_1.setJSXAttr(block, adapter_1.Adapter.elseif, t.jSXExpressionContainer(tester)); + } + return block; + }); + const block = jsx_1.buildBlockElement(); + block.children = children; + parentPath.parentPath.parentPath.replaceWith(block); + } + else if (t.isLogicalExpression(parentNode)) { + const { left, operator, right } = parentNode; + const leftExpression = parentPath.get('left'); + if (operator === '&&' && t.isExpression(left)) { + if (utils_1.hasComplexExpression(leftExpression)) { + utils_1.generateAnonymousState(this.renderScope, leftExpression, this.referencedIdentifiers, true); + } + const block = jsx_1.buildBlockElement(); + utils_1.newJSXIfAttr(block, leftExpression.node); + block.children = [jsxElementPath.node]; + parentPath.replaceWith(block); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, this.templates); + // name && templates.set(name, path.node) + } + } + if (operator === '||' && t.isExpression(left)) { + const newNode = t.conditionalExpression(left, left, right); + parentPath.replaceWith(newNode); + // this.handleConditionExpr({ parentNode: newNode, parentPath, statementParent }, jsxElementPath) + } + } + else if (t.isConditionalExpression(parentNode)) { + const { consequent, alternate } = parentNode; + const testExpression = parentPath.get('test'); + const block = jsx_1.buildBlockElement(); + if (utils_1.hasComplexExpression(testExpression)) { + utils_1.generateAnonymousState(parentPath.scope, testExpression, this.referencedIdentifiers, true); + } + const test = testExpression.node; + if (t.isJSXElement(consequent) && this.isLiteralOrUndefined(alternate)) { + const { value, confident } = parentPath.get('alternate').evaluate(); + if (confident && !value || t.isIdentifier({ name: 'undefined' })) { + utils_1.newJSXIfAttr(block, test); + block.children = [jsxElementPath.node]; + // newJSXIfAttr(jsxElementPath.node, test) + parentPath.replaceWith(block); + } + else { + const block2 = jsx_1.buildBlockElement(); + block.children = [consequent]; + utils_1.newJSXIfAttr(block, test); + jsx_1.setJSXAttr(block2, adapter_1.Adapter.else); + block2.children = [t.jSXExpressionContainer(alternate)]; + const parentBlock = jsx_1.buildBlockElement(); + parentBlock.children = [block, block2]; + parentPath.replaceWith(parentBlock); + } + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, this.templates); + // name && templates.set(name, path.node) + } + } + else if (this.isLiteralOrUndefined(consequent) && t.isJSXElement(alternate)) { + const { value, confident } = parentPath.get('consequent').evaluate(); + if (confident && !value || t.isIdentifier({ name: 'undefined' })) { + utils_1.newJSXIfAttr(block, utils_1.reverseBoolean(test)); + block.children = [jsxElementPath.node]; + // newJSXIfAttr(jsxElementPath.node, test) + parentPath.replaceWith(block); + } + else { + const block2 = jsx_1.buildBlockElement(); + block.children = [t.jSXExpressionContainer(consequent)]; + utils_1.newJSXIfAttr(block, test); + jsx_1.setJSXAttr(block2, adapter_1.Adapter.else); + block2.children = [alternate]; + const parentBlock = jsx_1.buildBlockElement(); + parentBlock.children = [block, block2]; + parentPath.replaceWith(parentBlock); + } + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, this.templates); + // name && templates.set(name, path.node) + } + } + else if (t.isJSXElement(consequent) && t.isJSXElement(alternate)) { + const block2 = jsx_1.buildBlockElement(); + block.children = [consequent]; + utils_1.newJSXIfAttr(block, test); + jsx_1.setJSXAttr(block2, adapter_1.Adapter.else); + block2.children = [alternate]; + const parentBlock = jsx_1.buildBlockElement(); + parentBlock.children = [block, block2]; + parentPath.replaceWith(parentBlock); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, this.templates); + } + } + else if (t.isJSXElement(consequent) && t.isCallExpression(alternate) && !utils_1.isArrayMapCallExpression(parentPath.get('alternate'))) { + const id = utils_1.generateAnonymousState(this.renderScope, parentPath.get('alternate'), this.referencedIdentifiers, true); + parentPath.get('alternate').replaceWith(id); + // + } + else if (t.isJSXElement(alternate) && t.isCallExpression(consequent) && !utils_1.isArrayMapCallExpression(parentPath.get('consequent'))) { + const id = utils_1.generateAnonymousState(this.renderScope, parentPath.get('consequent'), this.referencedIdentifiers, true); + parentPath.get('consequent').replaceWith(id); + } + else { + block.children = [t.jSXExpressionContainer(consequent)]; + utils_1.newJSXIfAttr(block, test); + const block2 = jsx_1.buildBlockElement(); + jsx_1.setJSXAttr(block2, adapter_1.Adapter.else); + block2.children = [t.jSXExpressionContainer(alternate)]; + const parentBlock = jsx_1.buildBlockElement(); + parentBlock.children = [block, block2]; + parentPath.replaceWith(parentBlock); + if (statementParent) { + const name = utils_1.findIdentifierFromStatement(statementParent.node); + utils_1.setTemplate(name, jsxElementPath, this.templates); + } + } + } + } + setProperies() { + const properties = []; + this.componentProperies.forEach((propName) => { + properties.push(t.objectProperty(t.stringLiteral(propName), t.objectExpression([ + t.objectProperty(t.stringLiteral('type'), t.nullLiteral()), + t.objectProperty(t.stringLiteral('value'), t.nullLiteral()) + ]))); + }); + let classProp = t.classProperty(t.identifier('properties'), t.objectExpression(properties)); + classProp.static = true; + const classPath = this.renderPath.findParent(isClassDcl); + adapter_1.Adapter.type !== "alipay" /* alipay */ && classPath.node.body.body.unshift(classProp); + } + setLoopRefFlag() { + if (this.loopRefs.size) { + const classPath = this.renderPath.findParent(isClassDcl); + classPath.node.body.body.unshift(t.classProperty(t.identifier('$$hasLoopRef'), t.booleanLiteral(true))); + } + } + destructStateOrProps(key, path, properties, parentPath) { + const hasStateOrProps = properties.filter(p => t.isObjectProperty(p) && t.isIdentifier(p.key) && key === p.key.name); + if (hasStateOrProps.length === 0) { + return; + } + if (hasStateOrProps.length !== properties.length) { + throw utils_1.codeFrameError(path.node, 'data 或 props 只能单独从 this 中解构'); + } + const declareState = template(`const ${key} = this.${key};`)(); + if (properties.length > 1) { + const index = properties.findIndex(p => t.isObjectProperty(p) && t.isIdentifier(p.key, { name: key })); + properties.splice(index, 1); + parentPath.insertAfter(declareState); + } + else { + parentPath.insertAfter(declareState); + parentPath.remove(); + } + } + handleJSXInIfStatement(jsxElementPath, { parentNode, parentPath, isFinalReturn }) { + if (t.isReturnStatement(parentNode)) { + if (!isFinalReturn) { + return; + } + else { + const ifStatement = parentPath.findParent(p => p.isIfStatement()); + const blockStatement = parentPath.findParent(p => p.isBlockStatement() && (p.parentPath === ifStatement)); + if (blockStatement && blockStatement.isBlockStatement()) { + blockStatement.traverse(this.renameIfScopeVaribale(blockStatement)); + } + const block = this.finalReturnElement || jsx_1.buildBlockElement(); + if (utils_1.isBlockIfStatement(ifStatement, blockStatement)) { + const { test, alternate, consequent } = ifStatement.node; + // blockStatement.node.body.push(t.returnStatement( + // t.memberExpression(t.thisExpression(), t.identifier('data')) + // )) + if (alternate === blockStatement.node) { + throw utils_1.codeFrameError(parentNode.loc, '不必要的 else 分支,请遵从 ESLint consistent-return: https://eslint.org/docs/rules/consistent-return'); + } + else if (consequent === blockStatement.node) { + const parentIfStatement = ifStatement.findParent(p => p.isIfStatement()); + if (parentIfStatement) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.elseif, t.jSXExpressionContainer(test), jsxElementPath); + } + else { + if (this.topLevelIfStatement.size > 0) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.elseif, t.jSXExpressionContainer(test), jsxElementPath); + } + else { + utils_1.newJSXIfAttr(jsxElementPath.node, test, jsxElementPath); + this.topLevelIfStatement.add(ifStatement); + } + } + } + } + else if (block.children.length !== 0) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.else); + } + block.children.push(jsxElementPath.node); + this.finalReturnElement = block; + this.returnedPaths.push(parentPath); + } + } + else if (t.isArrowFunctionExpression(parentNode)) { + // console.log('arrow') + } + else if (t.isAssignmentExpression(parentNode)) { + const ifStatement = parentPath.findParent(p => p.isIfStatement()); + const blockStatement = parentPath.findParent(p => p.isBlockStatement() && (p.parentPath === ifStatement)); + if (blockStatement && blockStatement.isBlockStatement()) { + blockStatement.traverse(this.renameIfScopeVaribale(blockStatement)); + } + if (t.isIdentifier(parentNode.left)) { + const assignmentName = parentNode.left.name; + const bindingNode = this.renderScope.getOwnBinding(assignmentName).path.node; + let block = this.templates.get(assignmentName) || jsx_1.buildBlockElement(); + if (utils_1.isEmptyDeclarator(bindingNode)) { + const blockStatement = parentPath.findParent(p => p.isBlockStatement()); + if (utils_1.isBlockIfStatement(ifStatement, blockStatement)) { + const { test, alternate, consequent } = ifStatement.node; + if (alternate === blockStatement.node) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.else); + } + else if (consequent === blockStatement.node) { + const parentIfStatement = ifStatement.findParent(p => p.isIfStatement()); + const assignments = []; + let isAssignedBefore = false; + // @TODO: 重构这两种循环为通用模块 + // 如果这个 JSX assigmnent 的作用域中有其他的 if block 曾经赋值过,它应该是 else-if + if (blockStatement && blockStatement.isBlockStatement()) { + for (const parentStatement of blockStatement.node.body) { + if (t.isIfStatement(parentStatement) && t.isBlockStatement(parentStatement.consequent)) { + const statements = parentStatement.consequent.body; + for (const statement of statements) { + if (t.isExpressionStatement(statement) && t.isAssignmentExpression(statement.expression) && t.isIdentifier(statement.expression.left, { name: assignmentName })) { + isAssignedBefore = true; + } + } + } + } + } + // 如果这个 JSX assigmnent 的的父级作用域中的 prev sibling 有相同的赋值,它应该是 else-if + if (parentIfStatement) { + const { consequent } = parentIfStatement.node; + if (t.isBlockStatement(consequent)) { + const body = consequent.body; + for (const parentStatement of body) { + if (t.isIfStatement(parentStatement) && t.isBlockStatement(parentStatement.consequent)) { + const statements = parentStatement.consequent.body; + for (const statement of statements) { + if (t.isExpressionStatement(statement) && t.isAssignmentExpression(statement.expression) && t.isIdentifier(statement.expression.left, { name: assignmentName })) { + assignments.push(statement.expression); + } + } + } + } + } + } + if ((parentIfStatement && + (parentIfStatement.get('alternate') === ifStatement || + assignments.findIndex(a => a === parentNode) > 0)) + || + isAssignedBefore) { + jsx_1.setJSXAttr(jsxElementPath.node, adapter_1.Adapter.elseif, t.jSXExpressionContainer(test), jsxElementPath); + } + else { + if (parentIfStatement) { + utils_1.newJSXIfAttr(block, parentIfStatement.node.test, jsxElementPath); + } + utils_1.newJSXIfAttr(jsxElementPath.node, test, jsxElementPath); + } + } + const ifAttr = block.openingElement.attributes.find(a => a.name.name === adapter_1.Adapter.if); + if (ifAttr && t.isJSXExpressionContainer(ifAttr.value, { expression: test })) { + const newBlock = jsx_1.buildBlockElement(); + newBlock.children = [block, jsxElementPath.node]; + block = newBlock; + } + else { + block.children.push(jsxElementPath.node); + } + // setTemplate(name, path, templates) + assignmentName && this.templates.set(assignmentName, block); + } + } + else { + throw utils_1.codeFrameError(jsxElementPath.node.loc, '请将 JSX 赋值表达式初始化为 null,然后再进行 if 条件表达式赋值。'); + } + } + } + else if (!t.isJSXElement(parentNode)) { + // throwError(path, '考虑只对 JSX 元素赋值一次。') + } + } + checkDuplicateData() { + this.initState.forEach((stateName) => { + if (this.templates.has(stateName)) { + throw utils_1.codeFrameError(this.templates.get(stateName), `自定义变量组件名: \`${stateName}\` 和已有 this.data.${stateName} 重复。请使用另一个变量名。`); + } + }); + this.componentProperies.forEach((componentName) => { + if (this.componentProperies.has(componentName)) { + throw utils_1.codeFrameError(this.renderPath.node, `data: \`${componentName}\` 和已有 this.props.${componentName} 重复。请使用另一个变量名。`); + } + if (this.templates.has(componentName)) { + throw utils_1.codeFrameError(this.templates.get(componentName), `自定义变量组件名: \`${componentName}\` 和已有 this.props.${componentName} 重复。请使用另一个变量名。`); + } + }); + } + addRefIdentifier(path, id) { + const arrayMap = path.findParent(p => utils_1.isArrayMapCallExpression(p)); + if (arrayMap && arrayMap.isCallExpression()) { + this.loopRefIdentifiers.set(id.name, arrayMap); + } + else { + id && this.referencedIdentifiers.add(id); + } + } + setOutputTemplate() { + this.outputTemplate = jsx_1.parseJSXElement(this.finalReturnElement); + } + removeJSXStatement() { + this.jsxDeclarations.forEach(d => d && d.remove()); + this.returnedPaths.forEach((p) => { + const ifStem = p.findParent(_ => _.isIfStatement()); + if (ifStem) { + const node = p.node; + if (t.isJSXElement(node.argument)) { + const jsx = node.argument; + if (jsx.children.length === 0 && jsx.openingElement.attributes.length === 0) { + node.argument = t.nullLiteral(); + } + else { + p.remove(); + } + } + else { + const isValid = p.get('argument').evaluateTruthy(); + if (!isValid) { + node.argument = t.nullLiteral(); + } + else { + p.remove(); + } + } + } + else { + p.remove(); + } + }); + } + setCustomEvent() { + const classPath = this.renderPath.findParent(isClassDcl); + let classProp = t.classProperty(t.identifier('$$events'), t.arrayExpression(Array.from(this.usedEvents).map(s => t.stringLiteral(s)))); // babel 6 typing 没有 static + classProp.static = true; + classPath.node.body.body.unshift(classProp); + } + setUsedState() { + for (const [key, method] of this.methods) { + if (method) { + if (method.isClassMethod()) { + const kind = method.node.kind; + if (kind === 'get') { + this.classComputedState.add(key); + } + } + } + } + const componentProperies = lodash_1.cloneDeep(this.componentProperies); + componentProperies.forEach(s => { + if (s.startsWith('__fn_')) { + const eventName = s.slice(5); + if (componentProperies.has(eventName)) { + componentProperies.delete(s); + componentProperies.delete(eventName); + } + } + }); + Array.from(this.reserveStateWords).forEach(this.setReserveWord); + const usedState = Array.from(new Set(Array.from(this.referencedIdentifiers) + .map(i => i.name) + .concat([...this.initState, ...this.usedThisState, ...componentProperies, ...this.classComputedState]))) + .concat(...this.usedState) + // .filter(i => { + // return !methods.has(i) + // }) + .filter(i => !this.loopScopes.has(i)) + .filter(i => !this.templates.has(i)) + .filter(Boolean); + const classPath = this.renderPath.findParent(isClassDcl); + classPath.node.body.body.unshift(t.classProperty(t.identifier('$usedState'), t.arrayExpression([...new Set(usedState + .filter(s => !this.loopScopes.has(s.split('.')[0])) + .filter(i => i !== constant_1.MAP_CALL_ITERATOR && !this.reserveStateWords.has(i)) + .filter(i => utils_1.isVarName(i)) + .filter(i => !this.loopRefIdentifiers.has(i)) + .concat(Array.from(this.customComponentNames)))] + .map(s => t.stringLiteral(s))))); + } + checkDuplicateName() { + this.loopScopes.forEach(s => { + if (this.renderPath.scope.hasBinding(s)) { + const err = utils_1.codeFrameError(this.renderPath.scope.getBinding(s).path.node, '此变量声明与循环变量冲突,可能会造成问题。'); + // tslint:disable-next-line + console.warn('Warning: ', err.message); + this.loopScopes.delete(s); + } + }); + } + setPendingState() { + const propertyKeys = Array.from(new Set(Array.from(this.referencedIdentifiers) + .map(i => i.name))) + .filter(i => { + const method = this.methods.get(i); + let isGet = false; + if (method) { + if (method.isClassMethod()) { + const kind = method.node.kind; + if (kind === 'get') { + isGet = true; + } + } + } + return !this.methods.has(i) || isGet; + }) + .filter(i => !this.loopScopes.has(i)) + .filter(i => !this.initState.has(i)) + .filter(i => !this.templates.has(i)) + .filter(i => utils_1.isVarName(i)) + .filter(i => i !== constant_1.MAP_CALL_ITERATOR && !this.reserveStateWords.has(i)) + .filter(i => !i.startsWith('$$')) + .filter(i => !this.loopRefIdentifiers.has(i)); + let properties = propertyKeys.map(i => t.objectProperty(t.identifier(i), t.identifier(i))); + if (this.customComponentData.length > 0) { + properties = properties.concat(this.customComponentData); + } + const pendingState = t.objectExpression(properties.concat(adapter_1.Adapter.type === "swan" /* swan */ && options_1.transformOptions.isRoot ? t.objectProperty(t.identifier('_triggerObserer'), t.booleanLiteral(false)) : []).concat(Array.from(this.classComputedState).filter(i => { + return !propertyKeys.includes(i); + }).map(i => { + return t.objectProperty(t.identifier(i), t.memberExpression(t.thisExpression(), t.identifier(i))); + }))); + this.renderPath.node.body.body = this.renderPath.node.body.body.concat(buildAssignState(pendingState), t.returnStatement(t.memberExpression(t.thisExpression(), t.identifier('data')))); + } + createData() { + const renderBody = this.renderPath.get('body'); + renderBody.traverse({ + ThisExpression(path) { + const property = path.getSibling('property'); + if (property.isIdentifier({ name: 'data' })) { + property.replaceWith(t.identifier('__state')); + } + if (property.isIdentifier({ name: 'props' })) { + property.replaceWith(t.identifier('__props')); + } + } + }); + this.usedThisProperties.forEach(prop => { + if (this.renderScope.hasBinding(prop)) { + const binding = this.renderScope.getBinding(prop); + throw utils_1.codeFrameError(binding.path.node, `此变量声明与 this.${prop} 的声明冲突,请更改其中一个变量名。详情见:https://github.com/NervJS/taro/issues/822`); + } + }); + this.renderPath.node.body.body.unshift(template(`this.__state = arguments[0] || this.data || {};`)(), template(`this.__props = arguments[1] || this.props || {};`)(), template(`const __runloopRef = arguments[2];`)(), this.usedThisProperties.size + ? t.variableDeclaration('const', [ + t.variableDeclarator(t.objectPattern(Array.from(this.usedThisProperties).map(p => t.objectProperty(t.identifier(p), t.identifier(p)))), t.thisExpression()) + ]) + : t.emptyStatement()); + if (t.isIdentifier(this.renderPath.node.key)) { + this.renderPath.node.key.name = '_createData'; + } + } +} +exports.RenderParser = RenderParser; +//# sourceMappingURL=render.js.map \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/render.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/render.js.map new file mode 100644 index 000000000..aaadec65c --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/render.js.map @@ -0,0 +1 @@ +{"version":3,"file":"render.js","sourceRoot":"","sources":["../../src/render.ts"],"names":[],"mappings":";;AAAA,mDAAmE;AACnE,iCAAgC;AAChC,2CAA+C;AAC/C,mCAuBgB;AAChB,mCAA8D;AAC9D,+BAIc;AACd,yCAUmB;AACnB,uCAA6C;AAC7C,uCAAwE;AACxE,qDAAsC;AAEtC,MAAM,QAAQ,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;AAI1C,SAAS,WAAW,CAAE,IAAsB,EAAE,EAAoC;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AAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,cAAc,CAC3E,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EACf,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CACT,CAAC,CAAC,EACV,CAAC,CAAC,cAAc,EAAE,CACnB;aACF,CACF;YACD,CAAC,CAAC,CAAC,CAAC,cAAc,EAAE,CACvB,CAAA;QAED,IAAI,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;YAC5C,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,GAAG,aAAa,CAAA;SAC9C;IACH,CAAC;CACF;AA7jDD,oCA6jDC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/utils.js b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/utils.js new file mode 100644 index 000000000..95394f38f --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/utils.js @@ -0,0 +1,493 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const t = require("babel-types"); +const babel_generator_1 = require("babel-generator"); +const code_frame_1 = require("@babel/code-frame"); +const constant_1 = require("./constant"); +const lodash_1 = require("lodash"); +const fs = require("fs"); +const path = require("path"); +const jsx_1 = require("./jsx"); +const adapter_1 = require("./adapter"); +const options_1 = require("./options"); +const template = require('babel-template'); +exports.incrementId = () => { + let id = 0; + return () => id++; +}; +function getSuperClassCode(path) { + const superClass = path.node.superClass; + if (t.isIdentifier(superClass)) { + const binding = path.scope.getBinding(superClass.name); + if (binding && binding.kind === 'module') { + const bindingPath = binding.path.parentPath; + if (bindingPath.isImportDeclaration()) { + const source = bindingPath.node.source; + if (source.value === constant_1.TARO_PACKAGE_NAME) { + return; + } + try { + const p = pathResolver(source.value, options_1.transformOptions.sourcePath) + (options_1.transformOptions.isTyped ? '.tsx' : '.js'); + const code = fs.readFileSync(p, 'utf8'); + return { + code, + sourcePath: source.value + }; + } + catch (error) { + return; + } + } + } + } +} +exports.getSuperClassCode = getSuperClassCode; +function isContainStopPropagation(path) { + let matched = false; + if (path) { + path.traverse({ + Identifier(p) { + if (p.node.name === 'stopPropagation' && + p.parentPath.parentPath.isCallExpression()) { + matched = true; + } + } + }); + } + return matched; +} +exports.isContainStopPropagation = isContainStopPropagation; +function decodeUnicode(s) { + return unescape(s.replace(/\\(u[0-9a-fA-F]{4})/gm, '%$1')); +} +exports.decodeUnicode = decodeUnicode; +function isVarName(str) { + if (typeof str !== 'string') { + return false; + } + if (str.trim() !== str) { + return false; + } + try { + // tslint:disable-next-line:no-unused-expression + new Function(str, 'var ' + str); + } + catch (e) { + return false; + } + return true; +} +exports.isVarName = isVarName; +function findMethodName(expression) { + let methodName; + if (t.isIdentifier(expression) || + t.isJSXIdentifier(expression)) { + methodName = expression.name; + } + else if (t.isStringLiteral(expression)) { + methodName = expression.value; + } + else if (t.isMemberExpression(expression) && + t.isIdentifier(expression.property)) { + const { code } = babel_generator_1.default(expression); + const ids = code.split('.'); + if (ids[0] === 'this' && ids[1] === 'props' && ids[2]) { + methodName = code.replace('this.props.', ''); + } + else { + methodName = expression.property.name; + } + } + else if (t.isCallExpression(expression) && + t.isMemberExpression(expression.callee) && + t.isIdentifier(expression.callee.object)) { + methodName = expression.callee.object.name; + } + else if (t.isCallExpression(expression) && + t.isMemberExpression(expression.callee) && + t.isMemberExpression(expression.callee.object) && + t.isIdentifier(expression.callee.property) && + expression.callee.property.name === 'bind' && + t.isIdentifier(expression.callee.object.property)) { + methodName = expression.callee.object.property.name; + } + else { + throw codeFrameError(expression.loc, '当 props 为事件时(props name 以 `on` 开头),只能传入一个 this 作用域下的函数。'); + } + return methodName; +} +exports.findMethodName = findMethodName; +function setParentCondition(jsx, expr, array = false) { + const conditionExpr = jsx.findParent(p => p.isConditionalExpression()); + const logicExpr = jsx.findParent(p => p.isLogicalExpression({ operator: '&&' })); + if (array) { + const ifAttrSet = new Set([ + adapter_1.Adapter.if, + adapter_1.Adapter.else + ]); + const logicalJSX = jsx.findParent(p => p.isJSXElement() && p.node.openingElement.attributes.some(a => ifAttrSet.has(a.name.name))); + if (logicalJSX) { + const attr = logicalJSX.node.openingElement.attributes.find(a => ifAttrSet.has(a.name.name)); + if (attr) { + if (attr.name.name === adapter_1.Adapter.else) { + const prevElement = logicalJSX.getPrevSibling(); + if (prevElement && prevElement.isJSXElement()) { + const attr = prevElement.node.openingElement.attributes.find(a => a.name.name === adapter_1.Adapter.if); + if (attr && t.isJSXExpressionContainer(attr.value)) { + expr = t.conditionalExpression(reverseBoolean(lodash_1.cloneDeep(attr.value.expression)), expr, t.arrayExpression()); + return expr; + } + } + } + else if (t.isJSXExpressionContainer(attr.value)) { + expr = t.conditionalExpression(lodash_1.cloneDeep(attr.value.expression), expr, t.arrayExpression()); + return expr; + } + } + } + } + if (conditionExpr && conditionExpr.isConditionalExpression()) { + const consequent = conditionExpr.get('consequent'); + if (consequent === jsx || jsx.findParent(p => p === consequent)) { + expr = t.conditionalExpression(lodash_1.cloneDeep(conditionExpr.get('test').node), expr, array ? t.arrayExpression([]) : t.nullLiteral()); + } + } + if (logicExpr && logicExpr.isLogicalExpression({ operator: '&&' })) { + const consequent = logicExpr.get('right'); + if (consequent === jsx || jsx.findParent(p => p === consequent)) { + expr = t.conditionalExpression(lodash_1.cloneDeep(logicExpr.get('left').node), expr, array ? t.arrayExpression([]) : t.nullLiteral()); + } + } + return expr; +} +exports.setParentCondition = setParentCondition; +function generateAnonymousState(scope, expression, refIds, isLogical) { + let variableName = `anonymousState_${scope.generateUid()}`; + let statementParent = expression.getStatementParent(); + if (!statementParent) { + throw codeFrameError(expression.node.loc, '无法生成匿名 State,尝试先把值赋到一个变量上再把变量调换。'); + } + const jsx = isLogical ? expression : expression.findParent(p => p.isJSXElement()); + const callExpr = jsx.findParent(p => p.isCallExpression() && isArrayMapCallExpression(p)); + const ifExpr = jsx.findParent(p => p.isIfStatement()); + const blockStatement = jsx.findParent(p => p.isBlockStatement() && p.parentPath === ifExpr); + const expr = setParentCondition(jsx, lodash_1.cloneDeep(expression.node)); + if (!callExpr) { + refIds.add(t.identifier(variableName)); + statementParent.insertBefore(buildConstVariableDeclaration(variableName, expr)); + if (blockStatement && blockStatement.isBlockStatement()) { + blockStatement.traverse({ + VariableDeclarator: (p) => { + const { id, init } = p.node; + if (t.isIdentifier(id) && !id.name.startsWith(constant_1.LOOP_STATE)) { + const newId = scope.generateDeclaredUidIdentifier('$' + id.name); + refIds.forEach((refId) => { + if (refId.name === variableName && !variableName.startsWith('_$')) { + refIds.delete(refId); + } + }); + variableName = newId.name; + refIds.add(t.identifier(variableName)); + blockStatement.scope.rename(id.name, newId.name); + p.parentPath.replaceWith(template('ID = INIT;')({ ID: newId, INIT: init })); + } + } + }); + } + } + else { + variableName = `${constant_1.LOOP_STATE}_${callExpr.scope.generateUid()}`; + const func = callExpr.node.arguments[0]; + if (t.isArrowFunctionExpression(func)) { + if (!t.isBlockStatement(func.body)) { + func.body = t.blockStatement([ + buildConstVariableDeclaration(variableName, expr), + t.returnStatement(func.body) + ]); + } + else { + func.body.body.splice(func.body.body.length - 1, 0, buildConstVariableDeclaration(variableName, expr)); + } + } + } + const id = t.identifier(variableName); + expression.replaceWith(id); + return id; +} +exports.generateAnonymousState = generateAnonymousState; +function isArrayMapCallExpression(callExpression) { + return callExpression && + t.isCallExpression(callExpression.node) && + t.isMemberExpression(callExpression.node.callee) && + t.isIdentifier(callExpression.node.callee.property, { name: 'map' }); +} +exports.isArrayMapCallExpression = isArrayMapCallExpression; +function buildConstVariableDeclaration(variableName, expresion) { + return t.variableDeclaration('const', [ + t.variableDeclarator(t.identifier(variableName), expresion) + ]); +} +exports.buildConstVariableDeclaration = buildConstVariableDeclaration; +function setTemplate(name, path, templates) { + const parentPath = path.parentPath; + const jsxChildren = parentPath.findParent(p => p.isJSXElement()); + if (name && !jsxChildren) { + templates.set(name, path.node); + } +} +exports.setTemplate = setTemplate; +function isContainFunction(p) { + let bool = false; + p.traverse({ + CallExpression() { + bool = true; + } + }); + return bool; +} +exports.isContainFunction = isContainFunction; +function slash(input) { + const isExtendedLengthPath = /^\\\\\?\\/.test(input); + const hasNonAscii = /[^\u0000-\u0080]+/.test(input); + const hasChinese = /[^\u4e00-\u9fa5]+/.test(input); // has Chinese characters + if (isExtendedLengthPath || (hasNonAscii && !hasChinese)) { + return input; + } + return input.replace(/\\/g, '/'); +} +function pathResolver(source, location) { + const extName = path.extname(source); + const promotedPath = source; + if (!['js', 'tsx'].includes(extName)) { + try { + const pathExist = fs.existsSync(path.resolve(path.dirname(location), source, 'index.js')); + const tsxPathExist = fs.existsSync(path.resolve(path.dirname(location), source, 'index.tsx')); + if (pathExist || tsxPathExist) { + let p = path.join(promotedPath, 'index'); + if (!p.startsWith('.')) { + p = './' + p; + } + return slash(p); + } + return slash(promotedPath); + } + catch (error) { + return slash(promotedPath); + } + } + return slash(promotedPath.split('.').slice(0, -1).join('.')); +} +exports.pathResolver = pathResolver; +function codeFrameError(node, msg) { + let errMsg = ''; + try { + errMsg = code_frame_1.codeFrameColumns(exports.setting.sourceCode, node && node.type && node.loc ? node.loc : node, { + highlightCode: true + }); + } + catch (error) { + errMsg = 'failed to locate source'; + } + return new Error(`${msg} +----- +${errMsg}`); +} +exports.codeFrameError = codeFrameError; +exports.setting = { + sourceCode: '' +}; +function createUUID() { + return '$' + 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + let r = Math.random() * 16 | 0; + let v = c === 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }).replace(/-/g, '').slice(0, 8); +} +exports.createUUID = createUUID; +function createRandomLetters(n) { + const str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + return Array(n).join().split(',').map(function () { return str.charAt(Math.floor(Math.random() * str.length)); }).join(''); +} +exports.createRandomLetters = createRandomLetters; +function isBlockIfStatement(ifStatement, blockStatement) { + return ifStatement && blockStatement && + ifStatement.isIfStatement() && + blockStatement.isBlockStatement(); +} +exports.isBlockIfStatement = isBlockIfStatement; +function buildCodeFrame(code) { + return (loc) => code_frame_1.codeFrameColumns(code, loc); +} +exports.buildCodeFrame = buildCodeFrame; +function isNumeric(n) { + return !isNaN(parseFloat(n)) && isFinite(n); +} +exports.isNumeric = isNumeric; +function buildJSXAttr(name, value) { + return t.jSXAttribute(t.jSXIdentifier(name), t.jSXExpressionContainer(value)); +} +exports.buildJSXAttr = buildJSXAttr; +function newJSXIfAttr(jsx, value, path) { + const element = jsx.openingElement; + if (!t.isJSXIdentifier(element.name)) { + return; + } + if (element.name.name === 'Block' || element.name.name === 'block' || !path) { + element.attributes.push(buildJSXAttr(adapter_1.Adapter.if, value)); + } + else { + const block = jsx_1.buildBlockElement(); + newJSXIfAttr(block, value); + block.children.push(jsx); + path.node = block; + } +} +exports.newJSXIfAttr = newJSXIfAttr; +function getSlotName(name) { + return name.slice(6).toLowerCase(); +} +exports.getSlotName = getSlotName; +function isContainJSXElement(path) { + let matched = false; + path.traverse({ + JSXElement(p) { + matched = true; + p.stop(); + } + }); + return matched; +} +exports.isContainJSXElement = isContainJSXElement; +function hasComplexExpression(path) { + let matched = false; + if (isContainJSXElement(path)) { + return false; + } + if (path.isObjectExpression()) { + return true; + } + if (path.isTemplateLiteral() || path.isCallExpression()) { + return true; + } + if (path.isArrayExpression()) { + const { elements } = path.node; + if (elements.some(el => t.isObjectExpression(el) || t.isArrayExpression(el))) { + return true; + } + } + path.traverse({ + CallExpression: (p) => { + matched = true; + p.stop(); + }, + TemplateLiteral(p) { + matched = true; + p.stop(); + }, + ObjectExpression(p) { + matched = true; + p.stop(); + }, + ArrayExpression(p) { + const { elements } = p.node; + if (elements.some(el => t.isObjectExpression(el))) { + return true; + } + }, + TaggedTemplateExpression(p) { + matched = true; + p.stop(); + }, + MemberExpression(path) { + // @fix 放弃这个逻辑,导致后续变更 this.update 的 data 对应不上了 + // const jsxElement = path.findParent(p => p.isJSXExpressionContainer()); + // const object = path.get('object'); + // const property = path.get('property'); + // const parentPath = path.parentPath; + // if (jsxElement && + // object.isThisExpression() && + // property.isIdentifier({ name: 'data' }) && + // parentPath.isMemberExpression() && + // parentPath.parentPath.isMemberExpression()) { + // const sourceCode = parentPath.parentPath.getSource(); + // if (sourceCode.includes('[') && sourceCode.includes(']')) { + // matched = true; + // path.stop(); + // } + // } + } + }); + return matched; +} +exports.hasComplexExpression = hasComplexExpression; +function findFirstIdentifierFromMemberExpression(node, member) { + let id; + let object = node.object; + while (true) { + if (t.identifier(object) && !t.isMemberExpression(object)) { + id = object; + if (member) { + object = member; + } + break; + } + object = object.object; + } + return id; +} +exports.findFirstIdentifierFromMemberExpression = findFirstIdentifierFromMemberExpression; +function getArgumentName(arg) { + if (t.isThisExpression(arg)) { + return 'this'; + } + else if (t.isNullLiteral(arg)) { + return 'null'; + } + else if (t.isStringLiteral(arg) || t.isNumericLiteral(arg)) { + return arg.value; + } + else if (t.isIdentifier(arg)) { + return arg.name; + } + else { + return babel_generator_1.default(arg).code; + } + throw new Error(`bind 不支持传入该参数: ${arg}`); +} +exports.getArgumentName = getArgumentName; +function isAllLiteral(...args) { + return args.every(p => t.isLiteral(p)); +} +exports.isAllLiteral = isAllLiteral; +function reverseBoolean(expression) { + return t.unaryExpression('!', expression); +} +exports.reverseBoolean = reverseBoolean; +function isEmptyDeclarator(node) { + if (t.isVariableDeclarator(node) && + (node.init === null || + t.isNullLiteral(node.init))) { + return true; + } + return false; +} +exports.isEmptyDeclarator = isEmptyDeclarator; +function toLetters(num) { + let mod = num % 26; + let pow = num / 26 | 0; + let out = mod ? String.fromCharCode(64 + mod) : (--pow, 'Z'); + const letter = pow ? toLetters(pow) + out : out; + return letter.toLowerCase(); +} +exports.toLetters = toLetters; +function findIdentifierFromStatement(statement) { + if (t.isVariableDeclaration(statement)) { + const declarator = statement.declarations.find(s => t.isIdentifier(s.id)); + if (declarator && t.isIdentifier(declarator.id)) { + return declarator.id.name; + } + } + return '__return'; +} +exports.findIdentifierFromStatement = findIdentifierFromStatement; +//# sourceMappingURL=utils.js.map diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/utils.js.map b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/utils.js.map new file mode 100644 index 000000000..1bdc498be --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/lib/src/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";;AAAA,iCAAgC;AAChC,qDAAsC;AACtC,kDAAoD;AAEpD,yCAA0D;AAC1D,mCAAkC;AAClC,yBAAwB;AACxB,6BAA4B;AAC5B,+BAAyC;AACzC,uCAAmC;AACnC,uCAA4C;AAC5C,MAAM,QAAQ,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;AAE7B,QAAA,WAAW,GAAG,GAAG,EAAE;IAC9B,IAAI,EAAE,GAAG,CAAC,CAAA;IACV,OAAO,GAAG,EAAE,CAAC,EAAE,EAAE,CAAA;AACnB,CAAC,CAAA;AAED,SAAgB,iBAAiB,CAAE,IAAkC;IACnE,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC,UAAU,CAAA;IACvC,IAAI,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,EAAE;QAC9B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAA;QACtD,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ,EAAE;YACxC,MAAM,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU,CAAA;YAC3C,IAAI,WAAW,CAAC,mBAAmB,EAAE,EAAE;gBACrC,MAAM,MAAM,GAAG,WAAW,CAAC,IAAI,CAAC,MAAM,CAAA;gBACt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,CAAC,oBAAoB,CAAC,IAAI,CAAC;QAC5B,CAAC,IAAI,CAAC,IAAI,KAAK,IAAI;YACnB,CAAC,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAC3B;QACA,OAAO,IAAI,CAAA;KACZ;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AATD,8CASC;AAED,SAAgB,SAAS,CAAE,GAAW;IACpC,IAAI,GAAG,GAAG,GAAG,GAAG,EAAE,CAAA;IAClB,IAAI,GAAG,GAAG,GAAG,GAAG,EAAE,GAAG,CAAC,CAAA;IACtB,IAAI,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,GAAG,CAAC,CAAA;IAC5D,MAAM,MAAM,GAAG,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,CAAA;IAC/C,OAAO,MAAM,CAAC,WAAW,EAAE,CAAA;AAC7B,CAAC;AAND,8BAMC;AAED,SAAgB,2BAA2B,CAAE,SAAiB;IAC5D,IAAI,CAAC,CAAC,qBAAqB,CAAC,SAAS,CAAC,EAAE;QACtC,MAAM,UAAU,GAAG,SAAS,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;QACzE,IAAI,UAAU,IAAI,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE;YAC/C,OAAO,UAAU,CAAC,EAAE,CAAC,IAAI,CAAA;SAC1B;KACF;IACD,OAAO,UAAU,CAAA;AACnB,CAAC;AARD,kEAQC"} \ No newline at end of file diff --git a/packages/omi-cloudbase/scripts/taro-transformer-wx/package.json b/packages/omi-cloudbase/scripts/taro-transformer-wx/package.json new file mode 100644 index 000000000..845e860d7 --- /dev/null +++ b/packages/omi-cloudbase/scripts/taro-transformer-wx/package.json @@ -0,0 +1,93 @@ +{ + "name": "@tarojs/transformer-wx", + "version": "1.2.13", + "description": "Transfrom Nerv Component to Wechat mini program.", + "repository": { + "type": "git", + "url": "git+https://github.com/NervJS/taro.git" + }, + "main": "index.js", + "files": [ + "index.js", + "lib", + "cli.js", + "dist" + ], + "scripts": { + "test:cov": "jest --coverage && npm run lint", + "test": "jest", + "dev": "tsc -w --pretty", + "lint": "tslint", + "build": "tsc" + }, + "author": "O2Team", + "license": "MIT", + "jest": { + "testEnvironment": "node", + "transform": { + "^.+\\.tsx?$": "ts-jest" + }, + "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", + "moduleFileExtensions": [ + "ts", + "tsx", + "js", + "jsx", + "json", + "node" + ], + "testPathIgnorePatterns": [ + "node_modules", + "utils" + ] + }, + "dependencies": { + "@babel/code-frame": "^7.0.0-beta.44", + "babel-core": "^6.26.3", + "babel-eslint": "^8.2.3", + "babel-helper-evaluate-path": "^0.5.0", + "babel-helper-mark-eval-scopes": "^0.4.3", + "babel-helper-remove-or-void": "^0.4.3", + "babel-plugin-danger-remove-unused-import": "^1.1.1", + "babel-plugin-minify-dead-code": "^0.5.2", + "babel-plugin-remove-dead-code": "^1.3.2", + "babel-plugin-syntax-dynamic-import": "^6.18.0", + "babel-plugin-transform-class-properties": "^6.24.1", + "babel-plugin-transform-define": "^1.3.0", + "babel-plugin-transform-es2015-template-literals": "^6.22.0", + "babel-plugin-transform-flow-strip-types": "^6.22.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "eslint": "^4.15.0", + "eslint-plugin-taro": "1.2.13", + "html": "^1.0.0", + "lodash": "^4.17.5", + "prettier": "^1.14.2", + "typescript": "^3.2.2" + }, + "devDependencies": { + "@tarojs/taro": "1.2.13", + "@types/babel-core": "^6.25.5", + "@types/babel-generator": "^6.25.1", + "@types/babel-template": "^6.25.0", + "@types/babel-traverse": "6.25.3", + "@types/babel-types": "^6.25.2", + "@types/eslint": "^4.16.5", + "@types/jest": "^22.2.3", + "@types/lodash": "^4.14.105", + "@types/node": "^9.6.2", + "jest": "^23.0.1", + "jest-cli": "^22.1.4", + "ts-jest": "^22.4.6", + "tslint": "^5.10.0", + "tslint-config-prettier": "^1.10.0", + "tslint-config-standard": "^7.0.0" + }, + "publishConfig": { + "access": "public" + }, + "bugs": { + "url": "https://github.com/NervJS/taro/issues" + }, + "homepage": "https://github.com/NervJS/taro#readme" +} diff --git a/packages/omi-cloudbase/src/app.css b/packages/omi-cloudbase/src/app.css new file mode 100644 index 000000000..14c7a011c --- /dev/null +++ b/packages/omi-cloudbase/src/app.css @@ -0,0 +1,10 @@ +/**app.wxss**/ +.container { + height: 100%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: space-between; + /* padding: 20rpx 0; */ + box-sizing: border-box; +} diff --git a/packages/omi-cloudbase/src/app.js b/packages/omi-cloudbase/src/app.js new file mode 100644 index 000000000..e2bd038bc --- /dev/null +++ b/packages/omi-cloudbase/src/app.js @@ -0,0 +1,113 @@ + +import './app.css' +import './pages/list/index' +import { render, WeElement, define } from 'omi' + +define('my-app', class extends WeElement { + + config = { + pages: [ + 'pages/list/index', + 'pages/detail/index', + 'pages/mp/index', + 'pages/import/index', + 'pages/index/index', + 'pages/about/index', + 'pages/code/index' + ], + window: { + backgroundTextStyle: 'light', + navigationBarBackgroundColor: '#fff', + navigationBarTitleText: 'Omi Cloud', + navigationBarTextStyle: 'black' + }, + tabBar: { + color: "#575656", + selectedColor: "white", + borderStyle: "black", + backgroundColor: "black", + list: [ + { + pagePath: "pages/list/index", + text: "首页", + iconPath: "images/home-unslt.png", + "selectedIconPath": "images/home.png" + }, + { + pagePath: "pages/mp/index", + text: "小程序", + iconPath: "images/mp-unslt.png", + selectedIconPath: "images/mp.png" + }, + { + pagePath: "pages/about/index", + text: "omijs.org", + iconPath: "images/omi-unslt.png", + selectedIconPath: "images/omi.png" + } + ] + } + } + + globalData = { + userInfo: null + } + + install() { + // 展示本地存储能力 + var logs = wx.getStorageSync('logs') || [] + logs.unshift(Date.now()) + wx.setStorageSync('logs', logs) + + // 登录 + wx.login({ + success: res => { + // 发送 res.code 到后台换取 openId, sessionKey, unionId + } + }) + // 获取用户信息 + wx.getSetting({ + success: res => { + if (res.authSetting['scope.userInfo']) { + // 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框 + wx.getUserInfo({ + success: res => { + // 可以将 res 发送给后台解码出 unionId + this.globalData.userInfo = res.userInfo + + // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 + // 所以此处加入 callback 以防止这种情况 + if (this.userInfoReadyCallback) { + this.userInfoReadyCallback(res) + } + } + }) + } + } + }) + + if (!wx.cloud) { + console.error('请使用 2.2.3 或以上的基础库以使用云能力') + } else { + wx.cloud.init({ + traceUser: true, + }) + this.globalData.db = wx.cloud.database({ + env: 'test-06eb2e' + }) + } + } + + onShow() { } + + onHide() { } + + render() { + return ( + + ) + } +}) + + +render(, '#app') diff --git a/packages/omi-cloudbase/src/cloud/login/index.js b/packages/omi-cloudbase/src/cloud/login/index.js new file mode 100644 index 000000000..608ebeac6 --- /dev/null +++ b/packages/omi-cloudbase/src/cloud/login/index.js @@ -0,0 +1,31 @@ +// 云函数模板 +// 部署:在 cloud-functions/login 文件夹右击选择 “上传并部署” + +const cloud = require('wx-server-sdk') + +// 初始化 cloud +cloud.init() + +/** + * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端 + * + * event 参数包含小程序端调用传入的 data + * + */ +exports.main = (event, context) => { + console.log(event) + console.log(context) + + // 可执行其他自定义逻辑 + // console.log 的内容可以在云开发云函数调用日志查看 + + // 获取 WX Context (微信调用上下文),包括 OPENID、APPID、及 UNIONID(需满足 UNIONID 获取条件) + const wxContext = cloud.getWXContext() + + return { + event, + openid: wxContext.OPENID, + appid: wxContext.APPID, + unionid: wxContext.UNIONID, + } +} diff --git a/packages/omi-cloudbase/src/cloud/login/package.json b/packages/omi-cloudbase/src/cloud/login/package.json new file mode 100644 index 000000000..540894edd --- /dev/null +++ b/packages/omi-cloudbase/src/cloud/login/package.json @@ -0,0 +1,14 @@ +{ + "name": "login", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "wx-server-sdk": "latest" + } +} diff --git a/packages/omi-cloudbase/src/cloud/remove/index.js b/packages/omi-cloudbase/src/cloud/remove/index.js new file mode 100644 index 000000000..42c2d087e --- /dev/null +++ b/packages/omi-cloudbase/src/cloud/remove/index.js @@ -0,0 +1,18 @@ +// 云函数模板 +const cloud = require('wx-server-sdk') + +// 初始化 cloud +cloud.init() + +const db = cloud.database() +const _ = db.command + +exports.main = async (event, context) => { + try { + return await db.collection('todo').where({ + done: true + }).remove() + } catch (e) { + console.error(e) + } +} \ No newline at end of file diff --git a/packages/omi-cloudbase/src/cloud/remove/package.json b/packages/omi-cloudbase/src/cloud/remove/package.json new file mode 100644 index 000000000..540894edd --- /dev/null +++ b/packages/omi-cloudbase/src/cloud/remove/package.json @@ -0,0 +1,14 @@ +{ + "name": "login", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "wx-server-sdk": "latest" + } +} diff --git a/packages/omi-cloudbase/src/components/comi/comi.js b/packages/omi-cloudbase/src/components/comi/comi.js new file mode 100644 index 000000000..994ade650 --- /dev/null +++ b/packages/omi-cloudbase/src/components/comi/comi.js @@ -0,0 +1,7 @@ + + +var WxParse = require('./wxParse.js'); + +module.exports = function comi(md, scope) { + WxParse.wxParse('article', 'md', md, scope, 5); +} \ No newline at end of file diff --git a/packages/omi-cloudbase/src/components/comi/comi.wxml b/packages/omi-cloudbase/src/components/comi/comi.wxml new file mode 100644 index 000000000..2eff5136e --- /dev/null +++ b/packages/omi-cloudbase/src/components/comi/comi.wxml @@ -0,0 +1,3 @@ + + +