seed
seed copied to clipboard
当我把多个模块合成到一个文件后,如何引用其中的模块
当我把多个模块合成到一个文件后,如何引用其中的模块? 例如:mod1,mod2,mod3,... 合成后的文件为all.js 那我如何单独使用其中的一些模块呢?
seed.use('mod1'');
seed.use(['mod2'],function(mod2){
console.log('test ---');
});
@winnieBear 这是一个很好的问题。
假如有 a b c 三个模块,c 依赖了 a & b,并且3个模块是合并到一起的,那么 c.js 的代码结构如下:
define( 'a', function(){
return 'a';
});
define( 'b', function(){
return 'b';
});
define('c', ['a', 'b'], function( a, b ){
return a + '-' + b;
});
现在我要使用 c 模块,那么下面的代码没什么特别的:
seed.use( 'c', function( c ){
console.log( c ); // a-b
});
这里需要注意的是,seed.use 是一个 异步 方法,下面的写法肯定会出问题的:
seed.use( 'c', function( c ){
console.log( c );
});
seed.use( 'a', function( a ){
console.log( a );
});
a 模块包含在 c.js 中,在请求 a 模块时并不知道 c 模块的具体加载情况。所以上面的代码是没法正常工作的,将请求 a 模块的代码放到请求 c 模块的回调中,这样是不会有问题的:
seed.use( 'c', function( c ){
console.log( c );
seed.use( 'a', function( a ){
console.log( a );
});
});
当然还可以直接访问 seed.module[ modName ] 接口。
seed.use( 'c', function( c ){
console.log( c );
console.log( seed.module.a.exports );
});
第一种方法使用起来会更直观。