Skip to content

Commit

Permalink
fix: 可视化
Browse files Browse the repository at this point in the history
  • Loading branch information
msojocs committed Feb 3, 2022
1 parent cc00feb commit 0a3d71d
Show file tree
Hide file tree
Showing 29 changed files with 19,974 additions and 10 deletions.
1 change: 1 addition & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ jobs:
sudo find -maxdepth 1 -not -name ${{ env.name }} -not -name . -exec mv {} ${{ env.name }} \;
ls -l
sudo cp -r "${{ env.name }}/package.nw/node_modules/nodegit" nodegit
sudo cp -r "${{ env.name }}/compiler" compiler
env:
name: 'release-${{ github.ref_name }}'

Expand Down
96 changes: 96 additions & 0 deletions compiler/wcc_node/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
const util = require('./util')
const path = require('path')

let wcc
try {
console.warn('wcc load')
wcc = require('./src/wcc')
} catch (err) {
console.error('wcc', err)
// wcc = require('./build/Release/wcc.node')
}

const fs = util.fs

exports = async function (options) {
// console.warn('wcc init options:', options);
if (!options) throw Error('options is required')

const lazyload = !!options.lazyloadConfig

options = Object.assign(
{
files: [], // FILES
contents: [],
replaceContent: {},
verbose: false,
debug: false, // -d
debugWXS: false, // -ds
showNewTree: false,
isPlugin: false,
addTestAttre: false,
independent: false,
genfuncname: '$gwx', // -gn
isCut: false, // --split
cwd: process.cwd,
debug: false,
lazyload, // -ll
lazyloadConfig: '',
},
options,
)

return new Promise(async (resolve, reject) => {
let st = Date.now()

// 获取文件内容
if (!options.contents.length) {
const tasks = options.files.map((file) => {
if (typeof options.replaceContent[file] === 'string') {
return options.replaceContent[file]
}
return fs.readFile(path.resolve(options.cwd, file), 'utf8')
})
options.contents = await Promise.all(tasks) || []
}
// console.warn('wcc get files', Date.now() - st, options.contents)
let result
try {
// console.warn('final options:', options);
// TODO: fix
result = wcc(options.cwd, options.files, {cut: options.isCut}, options)
// console.warn('wcc result', result)
} catch(errmsg) {
reject(new Error(errmsg))
return
}

// console.log('wcc get compile', Date.now() - st)
if (options.output) {
const output = path.resolve(options.cwd, options.output)
const dir = path.dirname(output)
if (lazyload) {
// lazyload 为 true时,wcc 返回值是个对象, 需要序列化一下
result = JSON.stringify(result)
}
try {
await fs.stat(dir)
} catch (e) {
await fs.mkdir(dir, {
recursive: true,
})
}
await fs.writeFile(output, result, 'utf8')
}
console.warn('wcc get output', Date.now() - st)
resolve(result)
})
}

Object.defineProperty(exports, 'version', {
get() {
return wcc.version
},
})

module.exports = exports
25 changes: 25 additions & 0 deletions compiler/wcc_node/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "miniprogram-wcc",
"version": "0.0.1",
"description": "WCC node C++ addon",
"main": "index.js",
"scripts": {
"install": "node-gyp-build",
"rebuild": "node-gyp rebuild",
"build:dist": "node scripts/build",
"build": "node-gyp build",
"test": "node ./test/index",
"format": "prettier *.js test/*.js scripts/*.js --write"
},
"author": "coverguo",
"license": "MIT",
"dependencies": {
"node-gyp-build": "^4.2.1"
},
"devDependencies": {
"eustia-module": "^1.21.2",
"licia": "^1.21.2",
"ncp": "^2.0.0",
"node-gyp": "^7.0.0"
}
}
30 changes: 30 additions & 0 deletions compiler/wcc_node/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const path = require('path')
const vm = require('vm')
const glob = require('glob')
const unescapeJs = require('unescape-js')

const wcc = require('./wcc')

module.exports = {
wxmlToJs(rootPath) {
// wcc 编译器需要完整的 wxml 文件列表
const files = glob.sync('**/*.wxml', {
cwd: rootPath,
nodir: true,
dot: true,
ignore: ['node_modules/**/*.wxml'],
})
const wxsFiles = glob.sync('**/*.wxs', {
cwd: rootPath,
nodir: true,
dot: true,
ignore: ['node_modules/**/*.wxs'],
})
const compileResult = wcc(rootPath, files.map(file => file.substring(0, file.length - 5)), wxsFiles)

return `
${compileResult};
return $gwx;
`
},
}
129 changes: 129 additions & 0 deletions compiler/wcc_node/src/wcc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
const { spawnSync } = require('child_process')
const fs = require('fs')
const path = require('path')

/**
* 获取 wxml 编译器路径
*/
let wxmlParserPath = ''
function getWXMLParsePath() {
if (wxmlParserPath) return wxmlParserPath

const fileName = process.platform === 'darwin' ? '../bin/mac/wcc' : process.platform === 'linux' ? '../bin/linux/wcc' : '../bin/windows/wcc.exe'
wxmlParserPath = path.join(__dirname, fileName)

// 尝试修改权限
try {
fs.chmodSync(wxmlParserPath, 0o777)
} catch (err) {
// ignore
}

return wxmlParserPath
}

/**
* 获取自定义组件编译参数
*/
function getComponentArgs(files) {
let args = []
let count = 0

files.forEach(file => {
const fileJson = file.fileJson

if (fileJson.usingComponents) {
args.push(file.pagePath)
args.push(Object.keys(fileJson.usingComponents).length)
args = args.concat(Object.keys(fileJson.usingComponents))
count++
}
})
args.unshift(count)

return args
}

/**
* 获取完整文件列表,包括自定义组件
*/
function getAllFiles(rootPath, files) {
const ret = []
const hasCheckMap = {}

for (let i = 0, len = files.length; i < len; i++) {
const file = files[i]

let fileJson = {}
const realPath = path.join(rootPath, file)
if (hasCheckMap[realPath]) continue
hasCheckMap[realPath] = true
try {
fileJson = require(`${realPath}.json`)
} catch(err) {
// ignore
}

// 自定义组件
if (fileJson.usingComponents) {
Object.keys(fileJson.usingComponents).forEach(subFileKey => {
const subFile = fileJson.usingComponents[subFileKey]

len++

let relativePath = path.relative(rootPath, path.join(path.dirname(realPath), subFile))
relativePath = relativePath.replace(/\\/g, '/')
files.push(relativePath)
})
}

ret.push({
pagePath: `${file}.wxml`,
jsonPath: `${file}.json`,
fileJson,
})
}

return ret
}

/**
* 入口
* 编译 wxml 到 js
* files
*
* @param {*} rootPath
* @param {*} files 文件列表,包含组件
* @param {*} param2
* @param {*} options 配置选项
* @returns
*/
function wxmlToJS(rootPath, files, { cut } = {}, options={}) {
const type = cut ? '-xc' : '-cc'
// files = getAllFiles(rootPath, files)

// @TODO,如果遇到参数过长被操作系统干掉的情况,可以使用 --config-path FILE 配置,参数空格换成空行
// const componentArgs = getComponentArgs(files), componentArgs.join(' ')
const args = ['-d', '--split', options.wxmlCompileConfigSplit, type, options.wxmlCompileConfig]
.concat(files)
.concat(['-gn', '$gwx'])

// TODO:可用性检测
// wxs调试
if(options.debugWXS)args.unshift('-ds')
// 懒加载
if(options.lazyload)args=args.concat(['-ll', options.lazyloadConfig])

// wxmlParserPath 二进制可执行文件路径
const wxmlParserPath = getWXMLParsePath()
// console.warn('wcc args:', args)
const wcc = spawnSync(wxmlParserPath, args, { cwd: rootPath })

if (wcc.status === 0) {
return wcc.stdout.toString()
} else {
throw new Error(`编译 .wxml 文件错误:${wcc.stderr.toString()}`)
}
}

module.exports = wxmlToJS
Loading

0 comments on commit 0a3d71d

Please sign in to comment.