轉換js腳本:
const fs = require('fs');
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
const ngHtmlToWxml = ngHtmlFilePath => {
const exists = fs.existsSync(ngHtmlFilePath);
if (!exists) {
console.error(ngHtmlFilePath + '不存在。 ');
return;
}
const data = fs.readFileSync(ngHtmlFilePath, 'utf8');
const dom = new JSDOM(data);
// dom.window.document.querySelector("ion-content").innerHTML;
const elements = dom.window.document.getElementsByTagName('*');
for (let index = 0; index < elements.length; index++) {
const element = elements[index];
let clickValue = element.getAttribute('(click)');
if (clickValue) {
element.removeAttribute('(click)');
element.setAttribute('bindtap', clickValue.substring(0, clickValue.indexOf('(')));
const paramsArray = clickValue
.substring(clickValue.indexOf('(') + 1, clickValue.lastIndexOf(')'))
.split(',');
paramsArray.forEach(ele => {
const paramsName = ele.trim();
if (paramsName) {
element.setAttribute('data-' + paramsName, `{{${paramsName}}}`);
}
});
}
let ifValue = element.getAttribute('*ngIf');
if (ifValue) {
element.removeAttribute('*ngIf');
element.setAttribute('wx:if', `{{${ifValue}}}`);
}
let forValue = element.getAttribute('*ngFor');
if (forValue) {
let forValueArrays = forValue.split(' ');
element.removeAttribute('*ngFor');
element.setAttribute('wx:for', `{{${forValueArrays[3]}}}`);
element.setAttribute('wx:for-index', `i`);
element.setAttribute('wx:for-item', `${forValueArrays[1]}`);
element.setAttribute('wx:key', 'id');
}
// TODO 這裏只處理了input
let ngModel = element.getAttribute('[(ngModel)]');
if (ngModel) {
element.removeAttribute('[(ngModel)]');
// input
element.setAttribute('bindinput', ngModel);
}
// TODO 未完待續 哈哈哈 20200325 01:10
}
const body = dom.window.document.getElementsByTagName('body');
const newHtml = body[0].innerHTML;
return newHtml;
};
const saveWxml = (wxmlFilePath, wxml) => {
const exists = fs.existsSync(wxmlFilePath);
if (exists) {
console.error(wxmlFilePath + '已存在!');
return;
}
fs.writeFileSync(wxmlFilePath, wxml);
console.log('wxml轉換成功,請檢查測試!');
};
const ngHtmlFilePath = './mall-product-details.page.html';
const wxml = ngHtmlToWxml(ngHtmlFilePath);
const wxmlFilePath = ngHtmlFilePath.replace('.html', '.wxml');
saveWxml(wxmlFilePath, wxml);
依賴信息:
{
"name": "wx-cli",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"fs": "0.0.1-security",
"jsdom": "^15.2.0"
}
}
執行方式: node index.js