util.js
3.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
let _ = require('lodash');
let path = require('path');
let acorn = require('acorn');
let escodegen = require('escodegen');
let shelljs = require('shelljs');
let chalk = require('chalk');
let fs = require('fs');
let CLIEngine = require("eslint").CLIEngine;
let cli = new CLIEngine({
fix: true
});
let util = {
complieFile(templateData, dirPath, codeMode, restPath) {
let originPath = path.join(__dirname, 'template', codeMode);
dirPath = path.join(originPath, dirPath);
let list = fs.readdirSync(dirPath);
_.each(list, p => {
if (p.match(/^\./)){
return;
}
let filePath = path.join(dirPath, p);
let stat = fs.statSync(filePath);
let restFilePath = filePath.replace(originPath, '');
if (stat.isDirectory()) {
shelljs.exec(`mkdir -p ${path.join(restPath, restFilePath)}`);
return this.complieFile(templateData, restFilePath, codeMode, restPath);
}
let content = fs.readFileSync(filePath, 'utf-8');
_.each(templateData, (val, key) => {
let regx = new RegExp(`#{${key}}`, 'g');
content = content.replace(regx, val);
});
let matchs = restFilePath.match(/_([^\/_]+)_/);
if (matchs) {
restFilePath = restFilePath.replace(matchs[0], templateData[matchs[1]]);
}
fs.writeFileSync(path.join(restPath, restFilePath), content, 'utf-8');
})
return true;
},
complieRef(refFile, refName) {
let importScript = require('./script/import')(refName);
let exportScript = require('./script/export')(refName);
let regModuleContent;
if (fs.existsSync(refFile)) {
regModuleContent = fs.readFileSync(refFile, 'utf-8');
let expression = acorn.parse(regModuleContent, {
sourceType: 'module'
});
if (_.some(expression.body, node => node.type === 'ImportDeclaration' && _.some(node.specifiers, spec => spec.local.name === refName))) {
console.log(chalk.yellow(`已经存在'${refName}'的引用,跳过步骤`));
return false;
}
let importIndex = _.findLastIndex(expression.body, node => node.type === 'ImportDeclaration');
let exportExpress = _.find(expression.body, node => node.type === 'ExportDefaultDeclaration');
expression.body.splice(importIndex + 1, 0, importScript);
exportExpress.declaration.properties.push(exportScript);
regModuleContent = escodegen.generate(expression);
} else {
let expression = {
"type": "Program",
"body": [
importScript,
{
"type": "ExportDefaultDeclaration",
"declaration": {
"type": "ObjectExpression",
"properties": [
exportScript
]
}
}
],
"sourceType": "module"
};
regModuleContent = escodegen.generate(expression);
}
let report = cli.executeOnText(regModuleContent);
if (report.results.length) {
regModuleContent = report.results[0].output;
}
fs.writeFileSync(refFile, regModuleContent, 'utf-8');
return true;
}
}
module.exports = util;