Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

用r.js对多个JS打包后去掉AMD包管理代码的方法 #20

Open
abeet opened this issue Feb 13, 2017 · 0 comments
Open

用r.js对多个JS打包后去掉AMD包管理代码的方法 #20

abeet opened this issue Feb 13, 2017 · 0 comments

Comments

@abeet
Copy link
Owner

abeet commented Feb 13, 2017

有多个基于AMD包管理的js在“js”目录下,要打包为一个去掉AMD包管理代码的JS。
其中core.js里内容如下

define([], function (console) {
	var jQuery = function () {};
	window.jQuery=jQuery;
	return jQuery;
});

其中selector.js里内容如下

define(["./core"], function (jQuery) {
	jQuery.find = function () {};
	return jQuery;
});

其中jquery.js里内容如下

define([
		"./core",
		"./selector"
	], function (jQuery) {
	return jQuery;
});

用r.js打包命令
r.js.cmd -o baseUrl=js name=jquery optimize=none out=build.js
打包后的jquery.js内容如下

define('core',[], function (console) {
	var jQuery = function () {};
	window.jQuery=jQuery;
	return jQuery;
});
define('selector',["./core"], function (jQuery) {
	jQuery.find = function () {};
	return jQuery;
});
define('jquery',[
		"./core",
		"./selector"
	], function (jQuery) {
	return jQuery;
});

怎么样去掉AMD包管理相关代码?
在百度上搜索没有找到,在bing上搜索 remove require define r.js 看到 Stack Overflow 上的一个讨论
http://stackoverflow.com/questions/23855295/how-to-remove-all-require-and-define-statements-form-my-javascript-library-using
再进入到
http://stackoverflow.com/questions/19885845/jquery-source-code-uses-require-js-but-the-final-file-doesnt
再进入到
https://github.com/jquery/jquery/blob/b24a3d5368ab1243ac43c773b318519da2f0ae7b/build/tasks/build.js#L44
找到了配置 onBuildWrite 方法来去掉AMD包管理的方案,稍作精简,
r.js.config.js 配置如下

({
	baseUrl : "./js",
	name : "jquery",
	optimize : "none",
	out : "build.js",
	wrap : {
		start : "!(function() {\n",
		end : "}());"
	},
	onBuildWrite : function (name, path, contents) {
		if (name !== "jquery") {
			contents = contents
				.replace(/\s*return\s+[^\}]+(\}\);[^\w\}]*)$/, "$1")
				.replace(/\s*exports\.\w+\s*=\s*\w+;/g, "");
		}
		contents = contents
			.replace(/define\([^{]*?{/, "")
			.replace(/\}\);[^}\w]*$/, "");
		contents = contents
			.replace(/define\(\[[^\]]+\]\)[\W\n]+$/, "");
		return contents;
	}
})

执行命令
r.js.cmd -o .\r.js.config.js
打包后的jquery.js内容如下

!(function() {

	var jQuery = function () {};
	window.jQuery=jQuery;

	jQuery.find = function () {};

	return jQuery;

}());

以上

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant