feat: require兼容目录解析

This commit is contained in:
coding 2017-10-11 17:39:51 +00:00
parent 8e30399465
commit f19975ca5f

View File

@ -6,6 +6,7 @@
(function (parent) { (function (parent) {
'use strict'; 'use strict';
var File = Java.type("java.io.File"); var File = Java.type("java.io.File");
var paths = ['', parent, parent + '/core', parent + '/kit', parent + '/modules'];
/** /**
* 解析模块名称为文件 * 解析模块名称为文件
@ -16,29 +17,51 @@
* 模块目录 /modules * 模块目录 /modules
* @param name 模块名称 * @param name 模块名称
*/ */
function resolve(name) { function resolve(name, parent) {
if (_canonical(name)) { if (_canonical(name)) {
name = _canonical(name); name = _canonical(name);
} }
name = normalizeName(name, '.js'); var temp = [parent].concat(paths);
return resolveAsFile(parent, name) || for(var i in temp) {
resolveAsFile(name) || var path = temp[i];
resolveAsFile(core_dir, name) || var result = resolveAsFile(path, name) || resolveAsDirectory(path, name);
resolveAsFile(miao_module_dir, name) || if (result) {
undefined; return result;
}
}
return undefined;
} }
/** /**
* 解析文件 * 解析文件
* @constructor(file)
* @constructor(dir,file)
* @returns {*} * @returns {*}
*/ */
function resolveAsFile() { function resolveAsFile(dir, file) {
var file = arguments.length > 1 ? new File(arguments[0], arguments[1]) : new File(arguments[0]); var file = ext.notNull(dir) ? new File(dir, file) : new File(file);
if (file.exists()) { if (file.isFile()) {
return file; return file;
} }
var ef = new File(normalizeName(_canonical(file)));
if (ef.isFile()) {
return ef;
}
}
/**
* 解析目录
* @returns {*}
*/
function resolveAsDirectory(dir, file) {
var file = ext.notNull(dir) ? new File(dir, file) : new File(file);
var _package = new File(file, 'package.json');
if (_package.exists()) {
var json = JSON.parse(base.read(_package));
if (json.main) {
return resolveAsFile(file, json.main);
}
}
// if no package or package.main exists, look for index.js
return resolveAsFile(file, 'index.js');
} }
function normalizeName(fileName, ext) { function normalizeName(fileName, ext) {
@ -80,7 +103,6 @@
require: exports(file.parentFile) require: exports(file.parentFile)
}; };
try { try {
// 预编译模块
var compiledWrapper = compileJs(file); var compiledWrapper = compileJs(file);
compiledWrapper.apply(module.exports, [ compiledWrapper.apply(module.exports, [
module, module.exports, module.require module, module.exports, module.require
@ -120,9 +142,9 @@
var file = resolve(name, path); var file = resolve(name, path);
if (file === undefined) { if (file === undefined) {
log.w("模块 %s 加载失败! 未找到该模块!", name); log.w("模块 %s 加载失败! 未找到该模块!", name);
return; return {exports:{}};
} }
// 重定向文件名称 // 重定向文件名称和类型
name = file.name.split(".")[0]; name = file.name.split(".")[0];
var id = _canonical(file); var id = _canonical(file);
var module = cacheModules[id]; var module = cacheModules[id];