This repository has been archived by the owner on Jan 21, 2021. It is now read-only.
/
babel.js
299 lines (270 loc) 路 8.59 KB
/
babel.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
import evaluateSimple from 'babel-helper-evaluate-path'
import evaluateComplex from 'linaria/lib/babel/evaluate'
import jsx from '@babel/plugin-syntax-jsx'
import { create } from './factory'
const { StyleSheet, StyleResolver, setI18nManager } = create()
// This function returns the extracted CSS to save in a .css file.
// It must be called after all the files are processed by Babel.
export function getCss() {
return StyleResolver.getStyleSheet().flush()
}
export default function(babel) {
let setI18n = false
return {
name: 'style-sheet/babel',
inherits: jsx,
visitor: {
Program: {
enter(path, state) {
if (!setI18n && typeof state.opts.rtl === 'boolean') {
setI18n = true
setI18nManager({
isRTL: state.opts.rtl,
doLeftAndRightSwapInRTL: state.opts.rtl,
})
}
},
exit(path, state) {
const { types: t } = babel
if (!state.hasStyleSheetImport && state.needsStyleSheetImport) {
const importSpecifier = t.identifier(
state.opts.importName || 'StyleSheet'
)
const importDeclaration = t.importDeclaration(
[t.importSpecifier(importSpecifier, importSpecifier)],
t.stringLiteral(state.opts.packageName || 'style-sheet')
)
path.node.body.unshift(importDeclaration)
}
if (!state.hasStylePropImport && state.needsStylePropImport) {
const importSpecifier = t.identifier('createElement')
const importDeclaration = t.importDeclaration(
[t.importSpecifier(importSpecifier, importSpecifier)],
t.stringLiteral(state.opts.stylePropPackageName)
)
path.node.body.unshift(importDeclaration)
}
},
},
JSXAttribute(path, state) {
if (!state.opts.stylePropName) {
state.opts.stylePropName = 'css'
}
if (path.node.name.name !== state.opts.stylePropName) {
return
}
const value = path.get('value')
if (!value.isJSXExpressionContainer()) {
return
}
let expression = value.get('expression')
const { types: t } = babel
const cloneNode = t.cloneNode || t.cloneDeep
const importName = state.opts.importName || 'StyleSheet'
let isExpressionArray = false
let expressions
if (expression.isArrayExpression()) {
isExpressionArray = true
expressions = expression.get('elements')
} else {
expressions = [expression]
}
const hoisted = expressions
.map(expression => {
if (!expression.isPure()) {
return
}
const replacement = t.callExpression(
t.memberExpression(
t.identifier(importName),
t.identifier('create')
),
[
t.objectExpression([
t.objectProperty(
t.identifier('__styleProp'),
cloneNode(expression.node)
),
]),
]
)
expression.replaceWith(replacement)
processReferencePath(babel, expression, state)
return expression.hoist()
})
.filter(Boolean)
if (isExpressionArray && hoisted.length === expressions.length) {
expression.hoist()
}
state.needsStylePropImport = true
if (!state.opts.stylePropPackageName) {
throw path.buildCodeFrameError(
`
Found \`${state.opts.stylePropName}\` prop but you didn't specify the path to the custom createElement in the Babel configuration.
Please set the \`stylePropPackageName\` option.
{
"plugins": [
[
"style-sheet/babel",
{
"stylePropName": "${state.opts.stylePropName}",
"stylePropPackageName": "./path/to/createElement.js"
}
]
]
}
Read more about how to create the style prop package at https://github.com/giuseppeg/style-sheet
`
)
}
},
ImportDeclaration(path, state) {
const stylePropPackageName = state.opts.stylePropPackageName
state.needsStylePropImport = Boolean(stylePropPackageName)
state.hasStylePropImport =
path.node.source.value === stylePropPackageName
const packageName = state.opts.packageName || 'style-sheet'
if (path.node.source.value !== packageName) {
return
}
const importName = state.opts.importName || 'StyleSheet'
const specifier = path.get('specifiers').find(specifier => {
return (
specifier.isImportSpecifier() &&
specifier.get('imported').node.name === importName
)
})
if (!specifier) {
return
}
state.hasStyleSheetImport = true
// Find all the references to StyleSheet.create.
const binding = path.scope.getBinding(specifier.node.local.name)
if (!binding || !Array.isArray(binding.referencePaths)) {
return
}
binding.referencePaths
.map(referencePath => referencePath.parentPath.parentPath)
.forEach(path => {
if (path.isCallExpression()) {
processReferencePath(babel, path, state)
}
})
},
},
}
}
function processReferencePath(babel, path, state) {
const t = babel.types
const cloneNode = t.cloneNode || t.cloneDeep
// From
//
// StyleSheet.create({
// root: {
// color: 'red'
// }
// })
//
// grabs
//
// {
// root: {
// color: 'red'
// }
// }
const rulesPath = path.get('arguments')[0]
const extractableProperties = []
// For each property
//
// root: {
// color: 'red'
// }
const properties = rulesPath.get('properties')
properties.forEach(property => {
// Ignore complex stuff like spread elements for now.
if (!property.isObjectProperty()) {
return
}
// Try to resolve to static...
// evaluate() will also compile static styles, which are the ones
// that we will extract to file.
const evaluated = evaluate(babel, property.get('value'), state)
if (evaluated.value === null) {
return
}
extractableProperties.push(
t.objectProperty(
cloneNode(property.get('key').node),
t.arrayExpression(evaluated.value.map(value => t.stringLiteral(value)))
)
)
property.remove()
})
// If we couldn't resolve anything we exit.
if (extractableProperties.length === 0) {
state.needsStyleSheetImport = true
return
}
const extractedStylesObjectLiteral = t.objectExpression(extractableProperties)
// When some rules could not be extracted (maybe there are dynamic styles)
// we will spread StyleSheet.create({...}) to the replacement object
//
// ({
// static: [/* ... */],
// ...StyleSheet.create({
// someDynamicRule: {
// color: props.color,
// }
// })
// })
if (properties.length !== extractableProperties.length) {
state.needsStyleSheetImport = true
extractedStylesObjectLiteral.properties.push(
t.spreadElement(cloneNode(path.node))
)
}
path.replaceWith(extractedStylesObjectLiteral)
}
function compileRule(rule) {
const compiled = StyleSheet.create({ static: rule }).static
StyleResolver.resolve(compiled)
return compiled
}
function evaluate(babel, path, state) {
let result = evaluateSimple(path)
if (result.confident) {
return {
value: compileRule(result.value),
dependencies: [],
}
}
try {
result = evaluateComplex(
path,
babel.types,
state.file.opts.filename,
text => {
return babel.transformSync(text, {
babelrc: false,
filename: state.file.opts.filename,
plugins: [
// Include this plugin to avoid extra config when using { module: false } for webpack
'@babel/plugin-transform-modules-commonjs',
'@babel/plugin-proposal-export-namespace-from',
// We don't support dynamic imports when evaluating, but don't wanna syntax error
// This will replace dynamic imports with an object that does nothing
// eslint-disable-next-line no-undef
require.resolve('linaria/lib/babel/dynamic-import-noop'),
],
exclude: /node_modules/,
})
}
)
if (result.value !== null) {
result.value = compileRule(result.value)
}
} catch (error) {
result = { value: null, dependencies: [] }
}
return result
}