fastchar-appjs
Version:
快速搭建VUE项目工具类的基本库,主要用于每个功能页面独立生成html,不使用vue单页面功能。
663 lines (662 loc) • 28.6 kB
JavaScript
define(["require", "exports"], function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BuildOption = exports.FastInjectJsPlugin = exports.Pages = exports.System = void 0;
/**
* 项目相关操作
* @author Janesen
*/
var System = /** @class */ (function () {
function System() {
}
/**
* 获取默认的vue配置文件
* @param dirName 项目根目录,建议取值 {@link __dirname}
* @param options 更多选项配置 {@link BuildOption}
*/
System.getDefaultVueConfig = function (dirName, options) {
var _this = this;
if (!options) {
options = new BuildOption();
}
if (options.injectJsFiles) {
if (Object.prototype.toString.call(options.injectJsFiles) === '[object Array]') {
options.injectJsFiles.push("fastchar-appjs/FastErrorHandler");
}
else {
options.injectJsFiles["fastchar-appjs/FastErrorHandler"] = {};
}
}
if (options.finalParams) {
this.setFinalParams(options.finalParams);
}
if (options.projectTitle) {
this.projectTitle = options.projectTitle;
}
var pages = Pages.getBuildPages(dirName, options);
if (options.createIndexPage) {
pages["index"] = Pages.createIndexPage(JSON.stringify(pages, null, "\t"), dirName, options);
}
this.setGlobalConfig("projectTitle", this.projectTitle);
this.setGlobalConfig("projectModel", process.env.NODE_ENV);
this.setGlobalConfig("projectVersion", process.env.npm_package_version);
this.setGlobalConfig("projectDebug", this.isServiceDebug() || this.isVueCliServerServer());
if (options.globalConfig) {
for (var globalConfigKey in options.globalConfig) {
// @ts-ignore
var value = options.globalConfig[globalConfigKey];
this.setGlobalConfig(globalConfigKey, value);
}
}
var defineValue = {
FastGlobalConfig: this.projectGlobalConfig
};
if (options.injectVariable) {
for (var dataKey in options.injectVariable) {
if (options.injectVariable[dataKey] === undefined) {
continue;
}
if (dataKey === "FastGlobalConfig") {
continue;
}
if (dataKey === "FinalParams") {
continue;
}
var value = options.injectVariable[dataKey];
if (typeof value === 'function') {
defineValue[dataKey] = value;
}
else {
defineValue[dataKey] = JSON.stringify(value);
}
}
}
var payTypes = this.getServicePay();
if (payTypes.indexOf("ali") >= 0) {
defineValue["NativeZF1"] = function (orderPrefix, orderTitle, orderMoney, orderData, callBack) {
// @ts-ignore
return FastNative.Core.executeByPromise("aliPay", [orderPrefix, orderTitle, parseFloat(orderMoney).toFixed(2), orderData], function (result) {
if (callBack) {
callBack(result.success, result.message, result.data);
}
});
};
defineValue["NativeAuthor1"] = function (callBack) {
// @ts-ignore
return FastNative.Core.executeByPromise("aliAuthor", [], function (result) {
if (callBack) {
callBack(result.success, result.message, result.data);
}
});
};
defineValue["NativeAuthorCode1"] = function (callBack) {
// @ts-ignore
return FastNative.Core.executeByPromise("aliAuthorCode", [], function (result) {
if (callBack) {
callBack(result.success, result.message, result.data);
}
});
};
}
if (payTypes.indexOf("wx") >= 0) {
defineValue["NativeZF2"] = function (orderPrefix, orderTitle, orderMoney, orderData, callBack) {
// @ts-ignore
return FastNative.Core.executeByPromise("wxPay", [orderPrefix, orderTitle, parseFloat(orderMoney).toFixed(2), orderData], function (result) {
if (callBack) {
callBack(result.success, result.message, result.data);
}
});
};
defineValue["NativeAuthor2"] = function (callBack) {
// @ts-ignore
return FastNative.Core.executeByPromise("wxAuthor", [], function (result) {
if (callBack) {
callBack(result.success, result.message, result.data);
}
});
};
defineValue["NativeAuthorCode2"] = function (callBack) {
// @ts-ignore
return FastNative.Core.executeByPromise("wxAuthorCode", [], function (result) {
if (callBack) {
callBack(result.success, result.message, result.data);
}
});
};
}
if (!options.cacheVueLoader && this.isVueCliServerBuild()) {
var path_1 = require("path");
var cacheDir = path_1.join(dirName, Pages.nodeModulesDir, ".cache", "vue-loader");
System.removeFile(cacheDir);
}
return {
outputDir: this.getServiceClient() === 'all' ? 'dist' : 'dist_' + this.getServiceClient(),
assetsDir: 'assets',
productionSourceMap: false,
publicPath: this.isVueCliServerBuild() ? "./" : '/',
pages: pages,
css: {
extract: false //取消css单独生成文件
},
chainWebpack: function (config) {
//创息标签croshe-builder加载器
config.module
.rule('vue')
.use('fastchar-appjs/src/cjs/FastVueBuilderLoader')
.loader('fastchar-appjs/src/cjs/FastVueBuilderLoader')
.end();
// ============压缩图片 start============
config.module
.rule('images')
.use('image-webpack-loader')
.loader('image-webpack-loader')
.options({ bypassOnDebug: true })
.end();
// ============压缩图片 end============
},
configureWebpack: function (config) {
if (_this.isVueCliServerServer() || _this.isServiceDebug()) {
var vConsolePlugin = require('vconsole-webpack-plugin');
config.plugins.push(new vConsolePlugin({
filter: [],
enable: true
}));
}
if (_this.isProduction() && !_this.isServiceDebug()) {
config.optimization.minimizer[0].options.terserOptions.compress.warnings = false;
config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true;
config.optimization.minimizer[0].options.terserOptions.compress.drop_debugger = true;
config.optimization.minimizer[0].options.terserOptions.compress.pure_funcs = ['console.log', 'console.debug'];
}
config.plugins.push(new FastInjectJsPlugin(options));
var webpack = require("webpack");
config.plugins.push(new webpack.DefinePlugin(defineValue));
config.optimization.splitChunks = {
cacheGroups: {
vendors: {
name: 'chunk-vendors',
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'initial'
},
common: {
name: 'chunk-common',
minChunks: 2,
priority: -20,
chunks: 'initial',
reuseExistingChunk: true
}
}
};
}
};
};
/**
* 是否是 vue-cli-service build 命令构建模式
*/
System.isVueCliServerBuild = function () {
if (process.env.npm_lifecycle_script && process.env.npm_lifecycle_script.toString().indexOf("vue-cli-service build") >= 0) {
return true;
}
return false;
};
/**
* 是否是 vue-cli-service server 命令构建模式
*/
System.isVueCliServerServer = function () {
if (process.env.npm_lifecycle_script && process.env.npm_lifecycle_script.toString().indexOf("vue-cli-service serve") >= 0) {
return true;
}
return false;
};
/**
* 是否是正式版本,production
*/
System.isProduction = function () {
return process.env.NODE_ENV === 'production';
};
/**
* 是否的打包开发版本,development
*/
System.isDevelopment = function () {
return process.env.NODE_ENV === 'development';
};
/**
* 是否的打包测试版本,test
*/
System.isVueTest = function () {
return process.env.NODE_ENV === 'test';
};
/**
* 获取运行脚本 npm_lifecycle_script 里的参数值,例如:--model production 参数名:--model 参数值:production
* @param argument
*/
System.getScriptArgumentValue = function (argument) {
if (process.env.npm_lifecycle_script) {
var index = process.env.npm_lifecycle_script.indexOf(argument.trim());
if (index >= 0) {
var argumentVar = process.env.npm_lifecycle_script.toString().substring(index).trim();
var splitArray = argumentVar.split(" ");
if (splitArray.length > 1) {
return splitArray[1].trim();
}
return "";
}
}
return null;
};
/**
* 获取命令参数 --client 或 --client-strict 的值
*/
System.getServiceClient = function () {
var client = this.getScriptArgumentValue("--client");
if (!client || client.length === 0) {
client = this.getScriptArgumentValue("--client-strict");
}
if (!client || client.length === 0) {
return "all";
}
return client;
};
/**
* 是否使用了命令参数 --client-strict
*/
System.isServiceClientStrict = function () {
var client = this.getScriptArgumentValue("--client-strict");
return client != null && client.length > 0;
};
/**
* 获取命令参数 --debug 的值
*/
System.isServiceDebug = function () {
var debugValue = this.getScriptArgumentValue("--debug");
if (debugValue == null) {
return false;
}
if (debugValue.length === 0) {
return true;
}
return debugValue === "true";
};
/**
* 获取打包支持的支付方式,避免ios上架失败,不允许支付宝支付等功能
*/
System.getServicePay = function () {
var pay = this.getScriptArgumentValue("--pay");
if (!pay || pay.length === 0) {
return ["ali", "wx", "ios", "apple"];
}
return pay.split(",");
};
/**
* 设置全局变量值
* @param key 变量名
* @param data 变量值
*/
System.setGlobalConfig = function (key, data) {
if (typeof data === 'function') {
this.projectGlobalConfig[key] = data;
}
else {
this.projectGlobalConfig[key] = JSON.stringify(data);
}
};
/**
* 设置FastServer请求接口的全局默认参数
* @param data 参数对象
*/
System.setFinalParams = function (data) {
this.setGlobalConfig("FinalParams", data);
};
/**
* 彻底删除指定目录文件
* @param path
*/
System.removeFile = function (path) {
var fs = require("fs");
var files = [];
if (fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach(function (file, index) {
var curPath = path + "/" + file;
if (fs.statSync(curPath).isDirectory()) {
System.removeFile(curPath); //递归删除文件夹
}
else {
fs.unlinkSync(curPath); //删除文件
}
});
fs.rmdirSync(path); // 删除文件夹自身
}
};
/**
* 项目标题
*/
System.projectTitle = "创息软件";
/**
* 项目的全局配置对象,将会自动生成到base.html中
*/
System.projectGlobalConfig = {};
return System;
}());
exports.System = System;
/**
* 页面相关操作
*/
var Pages = /** @class */ (function () {
function Pages() {
}
/**
* 获取vue页面配置,vue.config.js 中的pages配置
* @param dirName 项目的根目录
* @param options 更多配置
*/
Pages.getBuildPages = function (dirName, options) {
var fs = require("fs");
var path = require("path");
if (!options) {
options = new BuildOption();
}
var pagesMap = {};
var rootPagePath = path.join(dirName, Pages.pagesDir);
var pageFiles = fs.readdirSync(rootPagePath);
for (var i = 0; i < pageFiles.length; i++) {
var fileName = pageFiles[i];
if (fileName.indexOf(".") === 0) {
continue;
}
var subPageDirPath = path.join(rootPagePath, fileName);
if (System.getServiceClient() !== "all") {
if (options.clientStrict || System.isServiceClientStrict()) {
subPageDirPath = path.join(subPageDirPath, System.getServiceClient());
}
else if (fs.existsSync(path.join(subPageDirPath, System.getServiceClient()))) {
subPageDirPath = path.join(subPageDirPath, System.getServiceClient());
}
}
if (!fs.existsSync(subPageDirPath)) {
continue;
}
if (fs.statSync(subPageDirPath).isFile()) {
continue;
}
var mainFilePath = path.join(subPageDirPath, Pages.mainFileName);
if (fs.existsSync(mainFilePath)) {
pagesMap[fileName] = {
entry: mainFilePath,
title: System.projectTitle,
filename: fileName + ".html"
};
var templateFilePath = path.join(subPageDirPath, Pages.templateFileName);
if (fs.existsSync(templateFilePath)) {
pagesMap[fileName]["template"] = path.join(Pages.pagesDir, fileName, Pages.templateFileName);
}
else {
pagesMap[fileName]["template"] = "public/index.html";
}
}
var configFilePath = path.join(subPageDirPath, Pages.configFileName);
if (fs.existsSync(configFilePath)) {
var configContent = fs.readFileSync(configFilePath);
var configObj = JSON.parse(configContent);
for (var configObjKey in configObj) {
pagesMap[fileName][configObjKey] = configObj[configObjKey];
}
}
if (options.createConfigFile && Object.keys(pagesMap).length > 0) {
fs.writeFileSync(configFilePath, JSON.stringify(pagesMap[fileName], null, "\t"), {});
}
}
return pagesMap;
};
/**
* 创建默认的index索引页面
* @param pagesValue
* @param dirName
* @param options
*/
Pages.createIndexPage = function (pagesValue, dirName, options) {
var fs = require("fs");
var path = require("path");
if (!options) {
options = new BuildOption();
}
var baseDir = path.join(dirName, Pages.pagesDir, "index");
if (System.getServiceClient() !== "all") {
if (options.clientStrict || System.isServiceClientStrict()) {
baseDir = path.join(baseDir, System.getServiceClient());
}
else if (fs.existsSync(path.join(baseDir, System.getServiceClient()))) {
baseDir = path.join(baseDir, System.getServiceClient());
}
}
if (!fs.existsSync(baseDir)) {
fs.mkdirSync(baseDir);
}
var indexJsContent = "import {createApp} from \"vue\";\n";
indexJsContent += "import main from \"./main\";\n";
indexJsContent += "let app = createApp(main);\n";
indexJsContent += "app.config.globalProperties.pages = " + pagesValue + ";\n";
indexJsContent += "app.mount(\"#app\");";
var indexPath = path.join(baseDir, "index.js");
fs.writeFileSync(indexPath, indexJsContent, {});
var configDiv = "<template >\n" +
" <template v-for=\"(value,name) in pages\" :key=\"name\">\n" +
" <van-cell :title=\"value.filename\" is-link :url=\"value.urlParams?value.filename+'?'+value.urlParams:value.filename\" />\n" +
" </template>\n" +
"</template>\n" +
"<script>\n" +
"import {Cell} from 'vant';\n" +
"export default {\n" +
" name: \"main\",\n" +
" components: {\n" +
" [Cell.name]: Cell\n" +
" }\n" +
"}\n" +
"</script>";
fs.writeFileSync(path.join(baseDir, "main.vue"), configDiv, {});
return {
entry: indexPath,
title: System.projectTitle + "首页"
};
};
/**
* 快速复制一个vue子页面开发
* @param dirName 项目根目录
* @param copyPageName 复制目标的文件夹名
* @param newPageName 新生成的文件夹名
*/
Pages.copyPage = function (dirName, copyPageName, newPageName) {
var fs = require("fs");
var path = require("path");
var rootPath = path.join(dirName, Pages.pagesDir);
var copyPagePath = path.join(rootPath, copyPageName);
var newPagePath = path.join(rootPath, newPageName);
if (fs.existsSync(copyPagePath)) {
if (!fs.existsSync(newPagePath)) {
fs.mkdirSync(newPagePath);
}
var copyPageMainFilePath = path.join(copyPagePath, Pages.mainFileName);
var newPageMainFilePath = path.join(newPagePath, Pages.mainFileName);
if (fs.existsSync(copyPageMainFilePath)) {
var copyPageMainFileContent = fs.readFileSync(copyPageMainFilePath);
var newPageMainFileContent = copyPageMainFileContent.toString().replace(new RegExp(copyPageName, "g"), newPageName);
fs.writeFileSync(newPageMainFilePath, newPageMainFileContent, {});
var vueContent = "<template>\n" +
"\n" +
"</template>\n" +
"\n" +
"<script>\n" +
"export default {\n" +
" name: \"" + newPageName + "\"\n" +
"}\n" +
"</script>\n" +
"\n" +
"<style scoped>\n" +
"\n" +
"</style>";
fs.writeFileSync(path.join(newPagePath, newPageName + ".vue"), vueContent, {});
console.log("复制成功!" + newPagePath);
}
else {
console.error("目标文件夹入口文件:" + copyPageMainFilePath + " 不存在!");
}
}
else {
console.error("目标文件夹:" + copyPagePath + " 不存在!");
}
};
/**
* 第三方插件存放目录文件夹,默认:node_modules
*/
Pages.nodeModulesDir = "node_modules";
/**
* vue页面的相对目录文件夹,默认:src/pages/
*/
Pages.pagesDir = "src/pages/";
/**
* 入口文件名,默认:index.js
*/
Pages.mainFileName = "index.js";
/**
* 页面的默认配置json,按照vue的格式配置即可
*/
Pages.configFileName = "config.json";
/**
* 入口文件的模板名称,默认:index.html
*/
Pages.templateFileName = "index.html";
return Pages;
}());
exports.Pages = Pages;
/**
* 全局注入脚本插件
*/
var FastInjectJsPlugin = /** @class */ (function () {
function FastInjectJsPlugin(options) {
this.options = options;
}
FastInjectJsPlugin.prototype.filter = function (key, targetFilter) {
if (targetFilter) {
if (targetFilter.include) {
for (var i = 0; i < targetFilter.include.length; i++) {
if (targetFilter.include[i] === key) {
return true;
}
}
return false;
}
if (targetFilter.exclude) {
for (var i = 0; i < targetFilter.exclude.length; i++) {
if (targetFilter.exclude[i] === key) {
return false;
}
}
}
}
return true;
};
FastInjectJsPlugin.prototype.injectArray = function (local, entry, targetInjectJsFiles) {
if (Object.prototype.toString.call(targetInjectJsFiles) !== '[object Array]') {
return;
}
var path = require('path');
var fs = require('fs');
for (var i = 0; i < targetInjectJsFiles.length; i++) {
var value = targetInjectJsFiles[i];
if (typeof value === 'string') {
var jsPath = path.join(local, value);
if (fs.existsSync(jsPath)) {
for (var entryKey in entry) {
if (!this.filter(entryKey, this.options.injectJsFilter)) {
continue;
}
var entryArray = entry[entryKey];
entryArray.unshift(jsPath);
}
}
}
else {
this.injectObject(local, entry, value);
}
}
};
FastInjectJsPlugin.prototype.injectObject = function (local, entry, targetInjectJsFiles) {
if (typeof targetInjectJsFiles !== 'object') {
return;
}
var path = require('path');
var fs = require('fs');
for (var injectJsFilesKey in targetInjectJsFiles) {
var jsPath = path.join(local, injectJsFilesKey);
if (fs.existsSync(jsPath)) {
for (var entryKey in entry) {
if (!this.filter(entryKey, targetInjectJsFiles[injectJsFilesKey])) {
continue;
}
var entryArray = entry[entryKey];
entryArray.unshift(jsPath);
}
}
}
};
FastInjectJsPlugin.prototype.apply = function (compiler) {
var _this = this;
if (compiler.hooks && this.options) {
compiler.hooks.entryOption.tap({ name: 'FastInjectJsPlugin' }, function (local, entry) {
if (Object.prototype.toString.call(_this.options.injectJsFiles) == '[object Array]') {
_this.injectArray(local, entry, _this.options.injectJsFiles);
}
else if (typeof _this.options.injectJsFiles === 'object') {
_this.injectObject(local, entry, _this.options.injectJsFiles);
}
});
}
};
return FastInjectJsPlugin;
}());
exports.FastInjectJsPlugin = FastInjectJsPlugin;
/**
* 获取编译配置的选项配置,配置选项如下:
* <br/>
* {@link projectTitle } 项目名称
* <br/>
* {@link createConfigFile } 是否在每个页面目录下自动创建config.json文件
* <br/>
* {@link createIndexPage } 是否自动创建项目的index页面
* <br/>
* {@link globalConfig } 系统的全局配置
* <br/>
* {@link finalParams } FastServer请求接口全局请求参数,web项目的全局参数优先级大于原生APP的全局参数
* <br/>
* {@link injectJsFiles } 所有页面全局注入的js文件
* <br/>
* {@link injectJsFilter } 所有页面全局注入js文件过滤器
* <br/>
* {@link injectVariable } 所有页面全局注入js变量
* <br/>
* {@link cacheVueLoader } 是否使用vue默认的cache-loader,默认使用
*/
var BuildOption = /** @class */ (function () {
function BuildOption() {
/**
* 是否在每个页面目录下自动创建config.json文件
*/
this.createConfigFile = false;
/**
* 是否自动创建项目的index页面
*/
this.createIndexPage = false;
/**
* 是否使用vue默认的cache-loader缓存vue-loader,如果不使用,则在build版本前将删除缓存的目录.cache/vue-loader
*/
this.cacheVueLoader = false;
/**
* 是否强制检测配置客户端 --client 编译完全匹配
*/
this.clientStrict = false;
}
return BuildOption;
}());
exports.BuildOption = BuildOption;
});