1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | var Module = module.constructor
|
7 | var helper = require('./helper')
|
8 | var vm = require('vm')
|
9 |
|
10 |
|
11 | var _compile = Module.prototype._compile
|
12 | var _resolveFilename = Module._resolveFilename
|
13 | var moduleStack = []
|
14 |
|
15 | Module._resolveFilename = function(request, parent) {
|
16 | request = request.replace(/\?.*$/, '')
|
17 | request = helper.parseAlias(request)
|
18 | return _resolveFilename(request, parent)
|
19 | }
|
20 |
|
21 | Module.prototype._compile = function(content, filename) {
|
22 | moduleStack.push(this)
|
23 | try {
|
24 | return _compile.call(this, content, filename)
|
25 | }
|
26 | finally {
|
27 | moduleStack.pop()
|
28 | }
|
29 | }
|
30 |
|
31 |
|
32 | global.seajs = {
|
33 | config: helper.configFn,
|
34 | use: createAsync(module),
|
35 | cache: require.cache,
|
36 | log: console.log,
|
37 | version: require('../package.json').version
|
38 | }
|
39 |
|
40 | global.define = function(factory) {
|
41 | var ret = factory
|
42 | var module = moduleStack[moduleStack.length - 1] || require.main
|
43 |
|
44 |
|
45 | if (typeof factory === 'function') {
|
46 | module.uri = module.id
|
47 |
|
48 | var req = function(id) {
|
49 | return module.require(id)
|
50 | }
|
51 | req.async = createAsync(module)
|
52 |
|
53 | ret = factory.call(
|
54 | global,
|
55 | req,
|
56 | module.exports,
|
57 | module)
|
58 |
|
59 | if (ret !== undefined) {
|
60 | module.exports = ret
|
61 | }
|
62 | }
|
63 |
|
64 | else {
|
65 | module.exports = factory
|
66 | }
|
67 | }
|
68 |
|
69 | function createAsync(module) {
|
70 |
|
71 | return function(ids, callback) {
|
72 | if (typeof ids === 'string') ids = [ids]
|
73 |
|
74 | var args = []
|
75 | var remain = ids.length
|
76 |
|
77 | ids.forEach(function(id, index) {
|
78 |
|
79 |
|
80 | if (/^https?:\/\//.test(id)) {
|
81 | helper.readFile(id, function(data) {
|
82 | var m = {
|
83 | id: id,
|
84 | exports: {}
|
85 | }
|
86 |
|
87 | moduleStack.push(m)
|
88 | vm.runInThisContext(data, id)
|
89 | moduleStack.pop()
|
90 |
|
91 | done(m.exports, index)
|
92 | })
|
93 | }
|
94 |
|
95 | else {
|
96 | done(module.require(id), index)
|
97 | }
|
98 | })
|
99 |
|
100 | function done(data, index) {
|
101 | args[index] = data
|
102 | if (--remain === 0 && callback) {
|
103 | callback.apply(null, args)
|
104 | }
|
105 | }
|
106 | }
|
107 |
|
108 | }
|
109 |
|
110 |
|
111 | module.exports = global.seajs
|
112 |
|
113 |
|
114 |
|
115 |
|
116 |
|
117 |
|