Skip to content

Instantly share code, notes, and snippets.

@yyfrankyy
Created May 3, 2012 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yyfrankyy/2583839 to your computer and use it in GitHub Desktop.
Save yyfrankyy/2583839 to your computer and use it in GitHub Desktop.
spm的分段打包

又有人提到spm的分段打包,http://segmentfault.com/question/1244/ 之前没做是因为想得太复杂,今天实际动手试验了一把,其实挺简单。

spm已经支持了局部压缩,假设 a -> b -> c -> d

spm build c.js

则仅仅会合并cd,而spm还提供有同步和异步两种方案进行require

仔细想了下,鉴于你的需求,我比较倾向于这样处理:

a 里面 require('b')
b 里面 require.async('c')
c 里面 require('d')

这样spm build的时候可以分开两步:

spm build a.js
spm build c.js

这样可以打包为两个文件,因为这种局部打包其实说到最后还是怎么界定优化策略的问题,spm无法做得太多(或许还是不够聪明),但是因为seajs利用正则把require变成异步的方案仅推荐在开发的时候用,正式上线的时候还是区分开异步(require.async)和同步比较好。

define(function(require, exports, module) {
require('./b').run('a');
});
define(function(require, exports, module) {
exports.run = function(target) {
console.log('b.js run from %s', target);
};
require.async('./c', function(c) {
c.run('async c');
});
});
define(function(require, exports, module) {
exports.run = function(target) {
console.log('c.js run from %s', target);
};
require('./d').run('c');
});
define(function(require, exports, module) {
exports.run = function(target) {
console.log('d.js run from %s', target);
};
console.log('I\'m D');
});
<!doctype html>
<html>
<head>
<meta charset="utf8" />
<title>spm packaging strategy</title>
</head>
<body>
<script src="http://a.tbcdn.cn/libs/seajs/1.1.0/sea.js" data-main="./__build/a"></script>
<script>
seajs.config({
base: './'
});
</script>
</body>
</html>
a.js:2b.js run from a
c.js:2I'm D
c.js:2d.js run from c
c.js:1c.js run from async c
spm build a.js --combine --app_url .
spm build c.js --combine --app_url .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment