-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
102 lines (93 loc) · 2.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* @file: index
* @author: Cuttle Cong
* @date: 2017/12/11
* @description:
*/
var babel = require('babel-core')
var qs = require('querystring')
var t = babel.types
var corePlugin = {
visitor: {
ObjectProperty: function(path) {
var keyPath = path.get('key')
var value = path.get('value')
if (
keyPath.node.name === 'component' &&
t.isStringLiteral(value)
) {
var requestString = value.node.value || ''
requestString = requestString.trim()
var result
requestString = requestString.replace(/^(.*?!)?/, function (m) {
if (m === 'sync!') {
result = m
return ''
}
return m
})
var requireCode = 'require(' + JSON.stringify(requestString) + ')'
requireCode = requireCode + '.default || ' + requireCode
var chunkname = calcChunkname(requestString)
// has result, must === 'sync!'
if (result) {
value.replaceWithSourceString(
requireCode
)
}
else {
keyPath.node.name = 'getComponent'
value.replaceWithSourceString(
'function getComponent(location, callback) {\n' +
' require.ensure([], function () {\n' +
' callback(null, ' + requireCode + ')\n' +
' }, ' + JSON.stringify(chunkname) +')\n' +
'}'
)
}
}
}
}
}
/**
* case 1:
* in: 'react'
* out: 'react'
* case 2:
* in: './../react',
* out: 'react'
* case 3:
* in: './../react?n=aliasName'
* out: 'aliasName'
* case 4:
* in: '!some-loader!./../react'
* out: 'react'
*/
function calcChunkname(requestString) {
requestString = requestString.trim()
var qIndex = requestString.lastIndexOf('?')
if (qIndex >= 0) {
var name = qs.parse(requestString.slice(qIndex + 1)).n
if (typeof name !== 'undefined') {
return name
}
requestString = requestString.slice(0, qIndex)
}
requestString = stripeLoaderString(requestString)
return requestString.replace(/^(\.\/|\.\.\/)+/, '')
}
function stripeLoaderString(string = '') {
var arr = string.split('!')
return arr[arr.length - 1]
}
module.exports = function (content) {
if (this.cacheable) {
this.cacheable()
}
var code = babel.transform(content, {
plugins: [
corePlugin
]
}).code
return code
}