From f19975ca5fd60ad7e727739a924b1a90d7f87bec Mon Sep 17 00:00:00 2001 From: coding Date: Wed, 11 Oct 2017 17:39:51 +0000 Subject: [PATCH] =?UTF-8?q?feat:=20require=E5=85=BC=E5=AE=B9=E7=9B=AE?= =?UTF-8?q?=E5=BD=95=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/resources/core/require.js | 52 +++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/src/main/resources/core/require.js b/src/main/resources/core/require.js index 031e6c2..26de84d 100644 --- a/src/main/resources/core/require.js +++ b/src/main/resources/core/require.js @@ -6,6 +6,7 @@ (function (parent) { 'use strict'; var File = Java.type("java.io.File"); + var paths = ['', parent, parent + '/core', parent + '/kit', parent + '/modules']; /** * 解析模块名称为文件 @@ -16,29 +17,51 @@ * 模块目录 /modules * @param name 模块名称 */ - function resolve(name) { + function resolve(name, parent) { if (_canonical(name)) { name = _canonical(name); } - name = normalizeName(name, '.js'); - return resolveAsFile(parent, name) || - resolveAsFile(name) || - resolveAsFile(core_dir, name) || - resolveAsFile(miao_module_dir, name) || - undefined; + var temp = [parent].concat(paths); + for(var i in temp) { + var path = temp[i]; + var result = resolveAsFile(path, name) || resolveAsDirectory(path, name); + if (result) { + return result; + } + } + return undefined; } /** * 解析文件 - * @constructor(file) - * @constructor(dir,file) * @returns {*} */ - function resolveAsFile() { - var file = arguments.length > 1 ? new File(arguments[0], arguments[1]) : new File(arguments[0]); - if (file.exists()) { + function resolveAsFile(dir, file) { + var file = ext.notNull(dir) ? new File(dir, file) : new File(file); + if (file.isFile()) { 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) { @@ -80,7 +103,6 @@ require: exports(file.parentFile) }; try { - // 预编译模块 var compiledWrapper = compileJs(file); compiledWrapper.apply(module.exports, [ module, module.exports, module.require @@ -120,9 +142,9 @@ var file = resolve(name, path); if (file === undefined) { log.w("模块 %s 加载失败! 未找到该模块!", name); - return; + return {exports:{}}; } - // 重定向文件名称 + // 重定向文件名称和类型 name = file.name.split(".")[0]; var id = _canonical(file); var module = cacheModules[id];