@lvl/wxapp-cli
Version:
wxapp-cli
125 lines (106 loc) • 3.34 kB
JavaScript
const {
logWithSpinner,
stopSpinner,
log,
error,
clearConsole
} = require('../utils');
const fs = require('fs-extra');
const path = require('path');
/**
* Page目录与对应的模板关系
*/
const fileExtensionsMap = {
json: '/src/pages/demo/demo.json',
wxml: '/src/pages/demo/demo.wxml',
wxss: '/src/pages/demo/demo.wxss',
js: '/src/pages/demo/demo.js'
}
async function add(pageName) {
console.info('new create page name is ' + pageName);
const cwd = process.cwd()
const pageDirPath = path.resolve(cwd, pageName)
//创建文件夹
fs.ensureDir(pageDirPath, function () {
createPageFiles(pageName, pageDirPath);
});
// 寻找app.json文件
const appConfigFile = findAPPConfigFile(cwd);
// 将路径写入到app.json
const pagePath = getPageConfigPath(pageDirPath) + pageName;
// 创建页面组成文件
fs.readJson(appConfigFile, (err, packageObj) => {
if (err) console.error(err)
packageObj.pages.push(pagePath);
fs.writeJson(appConfigFile, packageObj, {
spaces: '\t'
}, err => {
if (err) return console.error(err)
console.log('success')
});
})
}
/**
* 获取页面的相对于Pages的父级路径
* @param {*} absolutePath
*/
function getPageConfigPath(absolutePath) {
const pathLevelArray = absolutePath && absolutePath.split(path.sep);
const pageIndex = pathLevelArray.indexOf('pages');
const newPathArray = pathLevelArray.slice(pageIndex);
let newPath = ''
newPathArray.forEach(element => {
newPath += element + '/'
});
return newPath;
}
/**
* 在指定目录下创建Page所需要的目录文件
* @param {*} pageName
* @param {*} parentPath
*/
function createPageFiles(pageName, parentPath) {
const sourcePagePath = getPageSourcePath();
for (const extension in fileExtensionsMap) {
if (fileExtensionsMap.hasOwnProperty(extension)) {
const element = fileExtensionsMap[extension];
const filePath = parentPath + '/' + pageName + '.' + extension;
const sourceFilePath = sourcePagePath + element;
fs.readFile(sourceFilePath, 'utf8', (err, data) => {
if (err) return console.error(err)
fs.outputFile(filePath, data, err => {
err && console.log(err) // => null
})
})
}
}
}
let stackCount = 0;
/**
* 根据当前的路径寻找当前工程中的app.js文件
* @param {*} currentPath
*/
function findAPPConfigFile(currentPath) {
const appConfigFilePath = currentPath + '/app.json';
if (fs.existsSync(appConfigFilePath)) {
return appConfigFilePath;
} else if (stackCount++ < 10) {
return findAPPConfigFile(path.dirname(currentPath));
} else {
throw new Error('找了10层还没找到,请确认文件是否真实存在');
}
}
/**
* 获取源文件路径
*/
function getPageSourcePath() {
return `${path.resolve(cliRoot, 'node_modules', tplModuleName)}`;
}
const tplModuleName = '@lvl/wxapp-cli-t-common';
const { cliRoot } = require('../config/wxapp-cli.config');
module.exports = (...args) => {
return add(...args).catch(err => {
error(err)
// process.exit(1)
})
}